python - 限制用户尝试登录的次数

标签 python python-3.x authentication basic-authentication bottle

我正在使用 Bottle 的 @auth_basic 装饰器来构建我的登录模块。我想添加一个功能,如果用户输入错误的密码,他们将被限制在 5 秒内重试。如何使用 Bottle 的 @auth_basic 来实现这一点?

最佳答案

显然我没有实际的登录部分。但这里有一种利用烧杯和装饰器来跟踪登录尝试的方法。

import gevent
from gevent import monkey, signal
monkey.patch_all()
from gevent.pywsgi import WSGIServer
from mainapp import mainappRoute
import bottle
from bottle import request, get, post, template
from beaker.middleware import SessionMiddleware
from whitenoise import WhiteNoise

staticfolder = 'static'
beakerconfig = {
    'session.type': 'memory',
    'session.auto': True,
    'session.cookie_path': '/',
    'session.key': 'site_id',
    'session.secret' : 'lsfkjsdlfhofuhrlifuheroifh',
    'session.httponly' : True
}

class user(object):
    def __init__(self):
        self.session = request.environ['beaker.session']
        self.login_attempts = 0

    def set(self, **kwargs):
        for k,v in kwargs.items():
            self.session[k] = v
        self.__dict__.update(self.session)

    def attempt(self):
        self.session['login_attempts'] = self.session.get('login_attempts', 0) + 1
        if self.session['login_attempts'] == 3:
            #do something like redirect
            pass


def check_login(fn):
    def check_uid(**kwargs):
        u = user()
        u.attempt()
        return fn(**kwargs)
    return check_uid

def shutdown():
    print('Shutting down ...')
    server.stop(timeout=60)
    exit(signal.SIGTERM)

@get('/login')
def login():
    return template('login.html')

@post('/login')
@check_login
def process_login():
    u = user()
    #let javascript handle the timeout
    return template('index.html', attempts=u.login_attempts)


botapp = bottle.app()
for Route in (mainappRoute,):
    botapp.merge(Route)
botapp = SessionMiddleware(botapp, beakerconfig)
botapp = WhiteNoise(botapp)
botapp.add_files(staticfolder, prefix='static/')
server = WSGIServer(("0.0.0.0", int(80)), botapp)
gevent.signal(signal.SIGTERM, shutdown)
gevent.signal(signal.SIGINT, shutdown)  # CTRL C
server.serve_forever()

关于python - 限制用户尝试登录的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57267556/

相关文章:

python - Rust vs python 程序性能结果问题

Python:切换 "verbose"输出的最有效方法?

python - 在Python中调整base64图像的大小

python-3.x - 如果给定列表中的值存在于多列中并计算列数

python - 获取两个整数列表并创建类型列表对的更快方法

python - cx_Freeze 构建错误?

authentication - 如何在 API 后端从 AWS Cognito 验证 JWT?

php - Joomla 2.5 - 无需密码即可登录用户

php - Laravel 5.2 通过 API 进行身份验证

django - 为什么我的 mod_wsgi 模块即使存在也找不到 "libpython3.7m.so.1.0"?