重构后的用户权限与登录管理模块

1. 后端接口(Flask)

python

from werkzeug.security import generate_password_hash, check_password_hash

import re

def validate_password(password):

    """密码复杂度校验:至少8位,包含大小写字母和数字"""

    if len(password) < 8:

        return False

    if not re.search(r"[A-Z]", password):

        return False

    if not re.search(r"[a-z]", password):

        return False

    if not re.search(r"\d", password):

        return False

    return True

@app.route('/register', methods=['POST'])

def register():

    """用户注册(包含角色和学号校验)"""

    data = request.json

    required_fields = ['username', 'password', 'role']

    if not all(field in data for field in required_fields):

        return jsonify({"error": "缺少必填字段"}), 400

    # 密码复杂度校验

    if not validate_password(data['password']):

        return jsonify({"error": "密码需至少8位,包含大小写字母和数字"}), 400

    # 角色合法性校验

    valid_roles = ['Admin', 'Teacher', 'Student']

    if data['role'] not in valid_roles:

        return jsonify({"error": "无效角色类型"}), 400

    # 学生角色需验证学号

    if data['role'] == 'Student' and 'studentId' not in data:

        return jsonify({"error": "学生角色必须提供学号"}), 400

    try:

        db = get_db_connection()

        cursor = db.cursor()

        # 检查学号是否存在(若为学生)

        if data['role'] == 'Student':

            cursor.execute("SELECT 1 FROM Students WHERE StudentID = %s", (data['studentId'],))

            if not cursor.fetchone():

                return jsonify({"error": "学号不存在"}), 404

        # 注册用户

        hashed_password = generate_password_hash(data['password'], method='sha256')

        sql = """

            INSERT INTO Users (Username, Password, Role, StudentID)

            VALUES (%s, %s, %s, %s)

        """

        values = (

            data['username'],

            hashed_password,

            data['role'],

            data.get('studentId')

        )

        cursor.execute(sql, values)

        db.commit()

        return jsonify({"message": "注册成功"}), 201

    except mysql.connector.IntegrityError:

        return jsonify({"error": "用户名已存在"}), 409

    except Error as e:

        return jsonify({"error": str(e)}), 500

    finally:

        cursor.close()

        db.close()

@app.route('/login', methods=['POST'])

def login():

    """用户登录(返回Token)"""

    data = request.json

    username = data.get('username')

    password = data.get('password')

    try:

        db = get_db_connection()

        cursor = db.cursor(dictionary=True)

        cursor.execute("SELECT * FROM Users WHERE Username = %s", (username,))

        user = cursor.fetchone()

        if user and check_password_hash(user['Password'], password):

            # 生成Token(示例使用JWT)

            token = generate_token(user['UserID'], user['Role'])  # 假设已实现JWT生成函数

            return jsonify({"message": "登录成功", "token": token, "role": user['Role']}), 200

        else:

            return jsonify({"error": "用户名或密码错误"}), 401

    except Error as e:

        return jsonify({"error": str(e)}), 500

    finally:

        cursor.close()

        db.close()

2. 前端界面(Vue.js)

vue

<template>

  <div>

    <form @submit.prevent="login">

      <input v-model="credentials.username" placeholder="用户名" required>

      <input v-model="credentials.password" type="password" placeholder="密码" required>

      <button type="submit">登录</button>

      <p v-if="error" class="error">{{ error }}</p>

    </form>

  </div>

</template>

<script>

export default {

  data() {

    return {

      credentials: { username: '', password: '' },

      error: ''

    };

  },

  methods: {

    login() {

      fetch('http://localhost:5000/login', {

        method: 'POST',

        headers: { 'Content-Type': 'application/json' },

        body: JSON.stringify(this.credentials)

      })

      .then(response => {

        if (!response.ok) throw response;

        return response.json();

      })

      .then(data => {

        localStorage.setItem('authToken', data.token); // 存储Token

        this.$router.push('/dashboard');              // 跳转到仪表盘

      })

      .catch(err => {

        err.json().then(e => this.error = e.error || "登录失败");

      });

    }

  }

};

</script>

<style scoped>

.error { color: red; }

</style>

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐