|
4 | 4 | :copyright: © 2020 by the Lin team. |
5 | 5 | :license: MIT, see LICENSE for more details. |
6 | 6 | """ |
7 | | -from operator import and_ |
8 | | - |
| 7 | +from flask import current_app, request |
9 | 8 | from flask_jwt_extended import ( |
10 | 9 | create_access_token, |
11 | 10 | create_refresh_token, |
12 | 11 | get_current_user, |
13 | 12 | get_jwt_identity, |
14 | 13 | verify_jwt_refresh_token_in_request, |
15 | 14 | ) |
| 15 | +from itsdangerous import JSONWebSignatureSerializer as JWSSerializer |
16 | 16 | from lin import manager, permission_meta |
17 | 17 | from lin.db import db |
18 | 18 | from lin.exception import Duplicated, Failed, NotFound, ParameterError, Success |
|
21 | 21 | from lin.redprint import Redprint |
22 | 22 |
|
23 | 23 | from app.exception.api import RefreshFailed |
| 24 | +from app.util.captcha import CaptchaTool |
24 | 25 | from app.util.common import split_group |
25 | 26 | from app.validator.form import ( |
26 | 27 | ChangePasswordForm, |
@@ -48,13 +49,20 @@ def register(): |
48 | 49 |
|
49 | 50 |
|
50 | 51 | @user_api.route("/login", methods=["POST"]) |
51 | | -@permission_meta(name="登录", module="用户", mount=False) |
52 | 52 | def login(): |
53 | 53 | form = LoginForm().validate_for_api() |
| 54 | + # 校对验证码 |
| 55 | + if current_app.config.get("LOGIN_CAPTCHA"): |
| 56 | + tag = request.headers.get("tag") |
| 57 | + secret_key = current_app.config.get("SECRET_KEY") |
| 58 | + serializer = JWSSerializer(secret_key) |
| 59 | + if form.captcha.data != serializer.loads(tag): |
| 60 | + raise Failed("验证码校验失败") |
| 61 | + |
54 | 62 | user = manager.user_model.verify(form.username.data, form.password.data) |
55 | 63 | # 用户未登录,此处不能用装饰器记录日志 |
56 | 64 | Log.create_log( |
57 | | - message=f"{user.username}登陆成功获取了令牌", |
| 65 | + message=f"{user.username}登录成功获取了令牌", |
58 | 66 | user_id=user.id, |
59 | 67 | username=user.username, |
60 | 68 | status_code=200, |
@@ -169,3 +177,17 @@ def _register_user(form: RegisterForm): |
169 | 177 | user_group.user_id = user.id |
170 | 178 | user_group.group_id = group_id |
171 | 179 | db.session.add(user_group) |
| 180 | + |
| 181 | + |
| 182 | +@user_api.route("/captcha", methods=["GET", "POST"]) |
| 183 | +def get_captcha(): |
| 184 | + """ |
| 185 | + 获取图形验证码 |
| 186 | + """ |
| 187 | + if not current_app.config.get("LOGIN_CAPTCHA"): |
| 188 | + return {"tag": "", "image": ""} |
| 189 | + image, code = CaptchaTool().get_verify_code() |
| 190 | + secret_key = current_app.config.get("SECRET_KEY") |
| 191 | + serializer = JWSSerializer(secret_key) |
| 192 | + tag = serializer.dumps(code) |
| 193 | + return {"tag": tag, "image": image} |
0 commit comments