我创建了一个面向公众的网络应用程序。例如,IT部门将使用一些管理工具来管理数据库中的某些内容。
我拥有数据库的所有路由和模型,我只是想了解一下我的功能是否适合将路由器的IP地址列入白名单以及是否遗漏了某些内容。
def allowed_ip(request):
if not request:
now = time.strftime("%b-%d-%Y_%H:%M:%S", time.gmtime(time.time()))
app.logger.info('No request was sent -=- {}'.format(now))
return False
if request and request.headers['X-Real-IP']:
if request.headers['X-Real-IP'] not in config.Config.ALLOWED_IPS:
now = time.strftime("%b-%d-%Y_%H:%M:%S", time.gmtime(time.time()))
app.logger.info('Request received from non-whitelist client {} -=- {}'.format(request.headers['X-Real-IP'],
now))
return False
else:
now = time.strftime("%b-%d-%Y_%H:%M:%S", time.gmtime(time.time()))
app.logger.info('Request received from whitelisted client {} -=- {}'.format(request.headers['X-Real-IP'],
now))
return True
else:
now = time.strftime("%b-%d-%Y_%H:%M:%S", time.gmtime(time.time()))
app.logger.info('Request received from but no IP sent -=- {}'.format(now))
return False
该函数检查它是否收到请求,(我知道这似乎毫无意义,但我收到了一些奇怪的错误,没有这一行),如果收到请求,它会检查X-Real-IP标头,看它是否在我们的白名单中。
有什么我想念的,可以在这里操纵吗?
我很欣赏这可能是一个广泛或偏离主题的问题,但我也对其他方法持开放态度。也许我会更好地管理Nginx级别的白名单?
我的答案适应了我的代码:
from functools import wraps
def whitelisted(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if request.headers['X-Real-IP'] not in app.config.get('ALLOWED_IPS'):
return redirect(url_for('login', next=request.url))
return f(*args, **kwargs)
return decorated_function
现在这是可能的:
@app.route('/map')
@whitelisted
@login_required
def show_all():
我会做这样的事情:
# helpers.py
from flask import request, current_app
def check_ip():
def decorator(f):
def wrapped_function(*args, **kwargs):
ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
if ip:
if ip in current_app.config.get('ALLOWED_IPS'):
return f(*args, **kwargs)
return 'Nice try! <3' # Do a real thing like real http code for forbiden, etc ... use response
return update_wrapper(wrapped_function, f)
return decorator
# routes.py
index = Blueprint('index ', __name__)
@index.route('/')
@check_ip()
def hello_world():
return render_template('home.html')
但是使用IP并不安全,如果你想要更好的东西,你应该在我看来使用flask_login或类似的东西。