欢迎访问宙启技术站
智能推送

使用HTTPTokenAuth()实现基于Token的用户认证功能的Python代码示例

发布时间:2023-12-24 15:28:37

import hashlib

import time

class User:

    def __init__(self, username, password):

        self.username = username

        self.password = self.encrypt_password(password)

    

    def encrypt_password(self, password):

        # 使用哈希函数将密码加密

        return hashlib.sha256(password.encode()).hexdigest()

class Token:

    def __init__(self, user):

        self.user = user

        self.expiry_time = time.time() + 3600  # 设置Token的过期时间为1小时

        

    def is_valid(self):

        return time.time() < self.expiry_time

    

    def get_user(self):

        return self.user

class HTTPTokenAuth:

    def __init__(self):

        # 初始化用户列表

        self.users = []

        # 初始化Token列表

        self.tokens = []

    

    def register_user(self, username, password):

        # 注册新用户

        user = User(username, password)

        self.users.append(user)

    

    def login(self, username, password):

        # 验证用户登录

        for user in self.users:

            if user.username == username and user.password == user.encrypt_password(password):

                # 生成新的Token并返回

                token = Token(user)

                self.tokens.append(token)

                return token

    

    def authenticate(self, token):

        # 验证Token的有效性

        for t in self.tokens:

            if t == token and t.is_valid():

                return t.get_user()

        

        return None

# 示例程序

auth = HTTPTokenAuth()

# 注册用户

auth.register_user("Alice", "password1")

auth.register_user("Bob", "password2")

# 用户登录

alice_token = auth.login("Alice", "password1")

bob_token = auth.login("Bob", "password2")

# 验证Token

alice = auth.authenticate(alice_token)

bob = auth.authenticate(bob_token)

if alice:

    print("Alice is authenticated!")

else:

    print("Alice is not authenticated!")

if bob:

    print("Bob is authenticated!")

else:

    print("Bob is not authenticated!")