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

使用Python和CGI创建基于cookie的用户认证系统

发布时间:2023-12-19 02:53:23

在Python中使用CGI创建基于cookie的用户认证系统可以实现用户的注册、登录和注销等功能。下面将详细说明如何使用Python和CGI创建这样的系统,并提供示例代码作为参考。

首先,需要在服务器上设置CGI环境。可以通过Apache服务器或其他的Web服务器来搭建CGI环境。具体的配置方法因服务器而异,请根据服务器的文档进行设置。

接下来,创建一个名为auth.py的Python脚本,作为我们的认证系统的入口文件。这个脚本将使用CGI模块来处理HTTP请求和响应。首先导入必要的模块:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import cgi
import cgitb
import hashlib
import os
import time

接下来定义几个辅助函数,用于处理用户信息和cookie。

def create_user(username, password):
    # 将用户名和密码加密存储
    password_hash = hashlib.md5(password.encode()).hexdigest()
    with open('users.txt', 'a') as f:
        f.write(f'{username}:{password_hash}
')

def get_user(username):
    # 根据用户名获取用户信息
    with open('users.txt', 'r') as f:
        for line in f:
            if line.split(':')[0] == username:
                return line.split(':')[1].strip()
    return None

def check_password(username, password):
    # 检查用户名和密码是否匹配
    user_password = get_user(username)
    if user_password:
        password_hash = hashlib.md5(password.encode()).hexdigest()
        if password_hash == user_password:
            return True
    return False

def set_cookie(username):
    # 设置cookie
    expiration = time.time() + 60 * 60 * 24 * 7  # 设置过期时间为一周
    cookie_value = hashlib.md5(os.urandom(16)).hexdigest()
    with open('cookies.txt', 'a') as f:
        f.write(f'{username}:{cookie_value}:{expiration}
')
    print(f'Set-Cookie: session={cookie_value}; expires={time.ctime(expiration)}; path=/')

def get_cookie():
    # 从cookie中获取用户名
    cookie = os.environ.get('HTTP_COOKIE')
    if cookie:
        with open('cookies.txt', 'r') as f:
            for line in f:
                username, cookie_value, expiration = line.split(':')
                if cookie_value == cookie and float(expiration) > time.time():
                    return username
    return None

def remove_cookie(username):
    # 从cookie中移除用户名
    with open('cookies.txt', 'r+') as f:
        lines = f.readlines()
        f.seek(0)
        for line in lines:
            if line.split(':')[0] != username:
                f.write(line)
        f.truncate()

然后定义处理各种请求的函数。

def register_form():
    # 显示注册表单
    print('Content-Type: text/html
')
    print('<form method="post" action="/auth.py">')
    print('<label for="username">用户名:</label><input type="text" id="username" name="username"><br>')
    print('<label for="password">密码:</label><input type="password" id="password" name="password"><br>')
    print('<input type="submit" value="注册">')
    print('</form>')

def login_form():
    # 显示登录表单
    print('Content-Type: text/html
')
    print('<form method="post" action="/auth.py">')
    print('<label for="username">用户名:</label><input type="text" id="username" name="username"><br>')
    print('<label for="password">密码:</label><input type="password" id="password" name="password"><br>')
    print('<input type="submit" value="登录">')
    print('</form>')

def register():
    # 处理注册请求
    form = cgi.FieldStorage()
    username = form.getvalue('username')
    password = form.getvalue('password')

    if username and password:
        create_user(username, password)
        login_form()
    else:
        register_form()

def login():
    # 处理登录请求
    form = cgi.FieldStorage()
    username = form.getvalue('username')
    password = form.getvalue('password')

    if username and password and check_password(username, password):
        set_cookie(username)
        print('Content-Type: text/html
')
        print(f'欢迎,{username}!')
    else:
        login_form()

def logout():
    # 处理注销请求
    username = get_cookie()
    if username:
        remove_cookie(username)
    login_form()

def main():
    cgitb.enable()  # 启用CGI错误回溯
    form = cgi.FieldStorage()  # 解析表单数据

    if 'register' in form:
        register()
    elif 'login' in form:
        login()
    elif 'logout' in form:
        logout()
    else:
        if get_cookie():
            print('Content-Type: text/html
')
            print(f'已登录,欢迎回来,{get_cookie()}!')
        else:
            login_form()

if __name__ == '__main__':
    main()

在这个脚本中,我们使用了cgi.FieldStorage()来解析表单数据,cgi.FieldStoragegetvalue()方法可以获取表单中字段的值。根据不同的请求,我们调用不同的函数来处理。

register()login()函数中,我们使用set_cookie()来为认证通过的用户设置cookie。set_cookie()函数生成一个随机的cookie值,将其与用户名和过期时间一起存储在cookies.txt文件中。在每个请求中,我们使用get_cookie()函数来检查用户是否已通过认证。

最后,在main()函数中,我们根据表单的不同参数来调用相应的处理函数。如果用户已通过认证,则显示欢迎消息;否则,显示登录表单。

示例代码中的用户信息和cookie都是存储在文本文件中的。在实际应用中,你可以使用更安全的数据库来存储这些信息。

以上就是使用Python和CGI创建基于cookie的用户认证系统的方法和示例代码。这个简单的示例可以作为你构建更复杂认证系统的基础。希望对你有帮助!