security.py
2.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# -*- coding: utf-8 -*-
"""
文件名: app/core/security.py
职责: 认证安全工具:密码哈希、JWT 生成与校验、账号/密码规则校验。
注意: 不要删除这个注释。
"""
import re
from datetime import datetime, timedelta, timezone
from typing import Optional
from jose import JWTError, jwt
from passlib.context import CryptContext
from pydantic import ValidationError
from app.core.config import settings
from app.schemas.user import TokenPayload
# JWT 配置
SECRET_KEY = getattr(settings, "SECRET_KEY", "change-me-in-production-32-char-long-key")
if len(SECRET_KEY) < 32:
SECRET_KEY = SECRET_KEY.ljust(32, "x")
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
REMEMBER_TOKEN_EXPIRE_DAYS = 7
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
# ========== 账号/密码规则 ==========
def validate_username(value: str) -> bool:
"""账号规则:字母+数字,长度大于6小于15"""
if not value:
return False
return bool(re.fullmatch(r"^[a-zA-Z0-9]{7,14}$", value))
def validate_password(value: str) -> bool:
"""密码规则:包含大小写字母+数字+特殊符号,长度大于8位小于20"""
if not value:
return False
if len(value) <= 8 or len(value) >= 20:
return False
if not re.search(r"[a-z]", value):
return False
if not re.search(r"[A-Z]", value):
return False
if not re.search(r"\d", value):
return False
if not re.search(r"[!@#$%^&*()_+\-=\[\]{}|;':\",./<>?]", value):
return False
return True
# ========== 密码哈希 ==========
def verify_password(plain_password: str, hashed_password: str) -> bool:
return pwd_context.verify(plain_password, hashed_password)
def get_password_hash(password: str) -> str:
return pwd_context.hash(password)
# ========== JWT Token ==========
def create_access_token(username: str, remember: bool = False) -> str:
if remember:
expire = datetime.now(timezone.utc) + timedelta(days=REMEMBER_TOKEN_EXPIRE_DAYS)
else:
expire = datetime.now(timezone.utc) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
to_encode = {"sub": username, "exp": int(expire.timestamp())}
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
def decode_access_token(token: str) -> Optional[TokenPayload]:
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
return TokenPayload(**payload)
except (JWTError, ValidationError):
return None
def token_remaining_seconds(token: str) -> int:
payload = decode_access_token(token)
if not payload:
return 0
now = int(datetime.now(timezone.utc).timestamp())
return max(0, payload.exp - now)