File size: 2,525 Bytes
bbb6398
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

身份验证模块 - 处理用户认证、令牌管理等功能

"""
import json
import os
import secrets
from datetime import datetime, timedelta
from config import AUTH_FILE, TOKEN_EXPIRY_DAYS

class AuthManager:
    """认证管理器 - 负责处理认证令牌的生成、存储和验证"""
    
    @staticmethod
    def load_tokens():
        """加载认证令牌数据"""
        if not os.path.exists(AUTH_FILE):
            with open(AUTH_FILE, 'w', encoding='utf-8') as f:
                json.dump({"tokens": {}}, f, ensure_ascii=False, indent=2)
            return {"tokens": {}}
        
        try:
            with open(AUTH_FILE, 'r', encoding='utf-8') as f:
                return json.load(f)
        except json.JSONDecodeError:
            return {"tokens": {}}

    @staticmethod
    def save_tokens(data):
        """保存认证令牌数据"""
        with open(AUTH_FILE, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)

    @staticmethod
    def generate_token():
        """生成安全随机令牌"""
        return secrets.token_hex(32)

    @staticmethod
    def store_token(token):
        """存储令牌并设置过期时间"""
        auth_data = AuthManager.load_tokens()
        expiry = (datetime.now() + timedelta(days=TOKEN_EXPIRY_DAYS)).isoformat()
        auth_data["tokens"][token] = {"expiry": expiry}
        AuthManager.save_tokens(auth_data)
        return token

    @staticmethod
    def verify_token(token):
        """验证令牌是否有效"""
        if not token:
            return False
        
        auth_data = AuthManager.load_tokens()
        token_data = auth_data["tokens"].get(token)
        
        if not token_data:
            return False
        
        # 检查令牌是否过期
        expiry = datetime.fromisoformat(token_data["expiry"])
        if datetime.now() > expiry:
            # 删除过期令牌
            del auth_data["tokens"][token]
            AuthManager.save_tokens(auth_data)
            return False
        
        return True

    @staticmethod
    def remove_token(token):
        """从存储中删除令牌"""
        if not token:
            return False
            
        auth_data = AuthManager.load_tokens()
        if token in auth_data["tokens"]:
            del auth_data["tokens"][token]
            AuthManager.save_tokens(auth_data)
            return True
        return False