?概述
我們在開篇的時候實現了簡單的登陸功能,也實現了一個前后端聯調的登陸功能,但是你有沒有發現,那個登陸只是一個簡單的登陸,且密碼在接口返回的過程中是銘文密碼,在生產環境中使用肯定是不行的,一般密碼都是需要加密的,要么是MD5加密,或者哈希加密,接下來我們重構登陸接口,一同連登陸頁面的風格也進行重構,使得風格更加現代化
首先設計數據庫關聯
用戶表(
sys_user
)
CREATE TABLE `sys_user` (`id` bigint NOT NULL AUTO_INCREMENT COMMENT '用戶ID',`username` varchar(50) NOT NULL COMMENT '用戶名',`password` varchar(100) NOT NULL COMMENT '密碼哈希',`name` varchar(50) NOT NULL COMMENT '姓名',`email` varchar(100) DEFAULT NULL COMMENT '郵箱',`phone` varchar(20) DEFAULT NULL COMMENT '手機號',`status` tinyint NOT NULL DEFAULT '1' COMMENT '狀態(0-禁用,1-正常)',`create_by` bigint NOT NULL COMMENT '創建人ID',`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '創建時間',`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新時間',PRIMARY KEY (`id`),UNIQUE KEY `uk_username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='系統用戶';-- 默認超級管理員 (密碼: admin123)
INSERT INTO `sys_user` (`id`, `username`, `password`, `name`, `email`, `status`, `create_by`)
VALUES (1, 'admin', '$2a$10$7JB720yubVSZvUI0rEqK/.VqGOZTH.ulu33dHOiBE8ByOhJIrdAu2', '超級管理員', 'admin@example.com', 1, 1);
角色表(
sys_role
)
CREATE TABLE `sys_role` (`id` bigint NOT NULL AUTO_INCREMENT COMMENT '角色ID',`role_name` varchar(50) NOT NULL COMMENT '角色名稱',`role_code` varchar(50) NOT NULL COMMENT '角色編碼',`description` varchar(255) DEFAULT NULL COMMENT '角色描述',`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '創建時間',`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新時間',PRIMARY KEY (`id`),UNIQUE KEY `uk_role_code` (`role_code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='角色表';-- 默認角色
INSERT INTO `sys_role` (`id`, `role_name`, `role_code`, `description`)
VALUES (1, '超級管理員', 'SUPER_ADMIN', '擁有系統所有權限'),(2, '普通用戶', 'NORMAL_USER', '擁有基礎操作權限');
用戶角色關聯表(
sys_user_role
)
CREATE TABLE `sys_user_role` (`id` bigint NOT NULL AUTO_INCREMENT COMMENT 'ID',`user_id` bigint NOT NULL COMMENT '用戶ID',`role_id` bigint NOT NULL COMMENT '角色ID',`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '創建時間',PRIMARY KEY (`id`),UNIQUE KEY `uk_user_role` (`user_id`,`role_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用戶角色關聯表';-- 超級管理員關聯超級管理員角色
INSERT INTO `sys_user_role` (`user_id`, `role_id`) VALUES (1, 1);
菜單表(
sys_menu
)
CREATE TABLE `sys_menu` (`id` bigint NOT NULL AUTO_INCREMENT COMMENT '菜單ID',`parent_id` bigint NOT NULL DEFAULT '0' COMMENT '父菜單ID',`menu_name` varchar(50) NOT NULL COMMENT '菜單名稱',`path` varchar(255) DEFAULT NULL COMMENT '路由路徑',`component` varchar(255) DEFAULT NULL COMMENT '前端組件',`icon` varchar(50) DEFAULT NULL COMMENT '圖標',`sort` int NOT NULL DEFAULT '0' COMMENT '排序',`menu_type` tinyint NOT NULL COMMENT '菜單類型(1-目錄,2-菜單,3-按鈕)',`permission` varchar(100) DEFAULT NULL COMMENT '權限標識',`is_show` tinyint NOT NULL DEFAULT '1' COMMENT '是否顯示(0-隱藏,1-顯示)',`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '創建時間',`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新時間',PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='菜單表';-- 默認菜單示例
INSERT INTO `sys_menu` (`menu_name`, `parent_id`, `path`, `component`, `icon`, `sort`, `menu_type`, `permission`)
VALUES
('系統管理', 0, '/system', 'Layout', 'el-icon-setting', 1, 1, NULL),
('用戶管理', 1, 'user', 'system/user/index', NULL, 1, 2, 'system:user:list'),
('角色管理', 1, 'role', 'system/role/index', NULL, 2, 2, 'system:role:list'),
('菜單管理', 1, 'menu', 'system/menu/index', NULL, 3, 2, 'system:menu:list'),
('用戶查詢', 2, NULL, NULL, NULL, 1, 3, 'system:user:query'),
('用戶新增', 2, NULL, NULL, NULL, 2, 3, 'system:user:add'),
('用戶編輯', 2, NULL, NULL, NULL, 3, 3, 'system:user:edit'),
('用戶刪除', 2, NULL, NULL, NULL, 4, 3, 'system:user:delete');
角色權限關聯表(
sys_role_menu
)
CREATE TABLE `sys_role_menu` (`id` bigint NOT NULL AUTO_INCREMENT COMMENT 'ID',`role_id` bigint NOT NULL COMMENT '角色ID',`menu_id` bigint NOT NULL COMMENT '菜單ID',`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '創建時間',PRIMARY KEY (`id`),UNIQUE KEY `uk_role_menu` (`role_id`,`menu_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='角色菜單關聯表';-- 超級管理員擁有所有權限
INSERT INTO `sys_role_menu` (`role_id`, `menu_id`) SELECT 1, id FROM sys_menu;
我們的密碼現在是使用的bcrypt加密,所以需要在utils工具中編寫JTW,用戶解密與數據庫中的密碼進行比對,符合賬號正確密碼正確才能登陸系統
# apis/utils/jwt.py
from functools import wraps
import jwt
from datetime import datetime, timedelta
from flask import current_app, g, request, jsonify
from sqlalchemy import select
from extensions import dbdef generate_token(user_id):"""生成JWT Token"""expire = datetime.utcnow() + timedelta(seconds=current_app.config['JWT_ACCESS_TOKEN_EXPIRES'])payload = {'exp': expire, 'sub': user_id}return jwt.encode(payload,current_app.config['JWT_SECRET_KEY'],algorithm='HS256')def verify_token(token):"""驗證Token"""try:payload = jwt.decode(token,current_app.config['JWT_SECRET_KEY'],algorithms=['HS256'])return payload['sub'] # 返回用戶IDexcept (jwt.ExpiredSignatureError, jwt.InvalidTokenError):return Nonedef login_required(f):"""登錄認證裝飾器"""@wraps(f)def decorated_function(*args, **kwargs):# 1. 檢查白名單(如果有配置)whitelist = current_app.config.get('PERMISSION_WHITELIST', [])if request.path in whitelist:return f(*args, **kwargs)# 2. 獲取Tokentoken = request.headers.get('Authorization')if not token or not token.startswith('Bearer '):return jsonify(code=401, message='未授權訪問'), 401# 3. 驗證Tokenuser_id = verify_token(token[7:])if not user_id:return jsonify(code=401, message='Token已過期或無效'), 401# 4. 檢查用戶狀態sys_user = db.metadata.tables['sys_user']user = db.session.execute(select(sys_user).where(sys_user.c.id == user_id)).first()if not user or user.status != 1:return jsonify(code=401, message='用戶不存在或已被禁用'), 401# 5. 保存用戶信息到請求上下文g.user_id = user_idg.user = dict(user) # 將行轉換為字典# 6. 設置到request對象中,供admin_required使用request.current_user_id = user_idreturn f(*args, **kwargs)return decorated_functiondef admin_required(f):"""管理員權限裝飾器"""@wraps(f)def decorated_function(*args, **kwargs):# 確保先經過login_required認證if not hasattr(request, 'current_user_id'):return jsonify(code=401, message='請先登錄'), 401user_id = request.current_user_id# 檢查用戶是否為超級管理員sys_user_role = db.metadata.tables['sys_user_role']sys_role = db.metadata.tables['sys_role']# 查詢用戶是否有超級管理員角色is_admin = db.session.execute(select(1).select_from(sys_user_role).join(sys_role, sys_user_role.c.role_id == sys_role.c.id).where((sys_user_role.c.user_id == user_id) &(sys_role.c.role_code == 'SUPER_ADMIN') # 使用role_code而不是roleName)).scalar()if not is_admin:return jsonify(code=403, message='需要管理員權限'), 403return f(*args, **kwargs)return decorated_functiondef permission_required(permission):"""權限校驗裝飾器"""def decorator(f):@wraps(f)def decorated_function(*args, **kwargs):if not hasattr(g, 'user_id'):return jsonify(code=401, message='未授權訪問'), 401# 這里需要根據您的權限系統實現具體的權限檢查邏輯# 暫時先返回成功,等權限系統完善后再實現return f(*args, **kwargs)return decorated_functionreturn decorator
建立好數據模型
menu.py
# models/menu.py
from extensions import db # 從 extensions.py 導入 db,而非 from . import dbclass Menu(db.Model):__tablename__ = 'sys_menu' # 對應數據庫中的 sys_menu 表# __table__ = db.metadata.tables['sys_menu'] # 直接關聯反射表id = db.Column(db.BigInteger, primary_key=True)parent_id = db.Column(db.BigInteger, default=0, nullable=False) # 父菜單IDmenu_name = db.Column(db.String(50), nullable=False) # 菜單名稱path = db.Column(db.String(255)) # 路由路徑component = db.Column(db.String(255)) # 前端組件menu_type = db.Column(db.SmallInteger, nullable=False) # 1-目錄 2-菜單 3-按鈕permission = db.Column(db.String(100)) # 權限標識(如 system:user:list)sort = db.Column(db.Integer, default=0) # 排序is_show = db.Column(db.SmallInteger, default=1) # 是否顯示
relationship.py
# models/relationship.py
from sqlalchemy import Table, Column, BigInteger, ForeignKey
from . import db # 導入你的 db 實例(SQLAlchemy)# 顯式定義 sys_user_role 關聯表(數據庫中已存在的表)
sys_user_role = Table('sys_user_role', # 數據庫表名(必須與手動創建的表名一致)db.metadata,Column('id', BigInteger, primary_key=True),Column('user_id', BigInteger, ForeignKey('sys_user.id'), nullable=False), # 關聯 sys_user.idColumn('role_id', BigInteger, ForeignKey('sys_role.id'), nullable=False) # 關聯 sys_role.id
)# 顯式定義 sys_role_menu 關聯表
sys_role_menu = Table('sys_role_menu', # 數據庫表名(必須與手動創建的表名一致)db.metadata,Column('id', BigInteger, primary_key=True),Column('role_id', BigInteger, ForeignKey('sys_role.id'), nullable=False),Column('menu_id', BigInteger, ForeignKey('sys_menu.id'), nullable=False)
)
role.py
# models/role.py
from extensions import db # 從 extensions.py 導入 db
from .menu import Menu # 導入 Menu 模型(此時 Menu 模型已能正確導入 db)
from .relationship import sys_role_menu # 導入關聯表 Table 對象class Role(db.Model):__tablename__ = 'sys_role'# _table__ = db.metadata.tables['sys_role'] # 直接關聯反射表id = db.Column(db.BigInteger, primary_key=True)role_name = db.Column(db.String(50), nullable=False)role_code = db.Column(db.String(50), unique=True, nullable=False)description = db.Column(db.String(255))menus = db.relationship(Menu, secondary=sys_role_menu, backref='roles') # 直接使用 Menu 類
user.py
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from extensions import db # 從 extensions.py 導入 db
from .role import Role # 導入 Role 模型
from .relationship import sys_user_roleclass User(db.Model):__tablename__ = 'sys_user' # 使用已設計的用戶表id = db.Column(db.BigInteger, primary_key=True)username = db.Column(db.String(50), unique=True, nullable=False)password = db.Column(db.String(100), nullable=False)name = db.Column(db.String(50), nullable=False)status = db.Column(db.SmallInteger, default=1, nullable=False)create_by = db.Column(db.BigInteger, nullable=False)created_at = db.Column(db.DateTime, default=datetime.utcnow)# 修復多對多關系:使用導入的 sys_user_role Table 對象roles = db.relationship(Role, secondary=sys_user_role, backref='users') # 直接使用 Role 類def set_password(self, password):self.password = generate_password_hash(password)def check_password(self, password):return check_password_hash(self.password, password)
重構登陸接口
# -*- coding:utf-8 -*-
import jsonfrom flask import Blueprint
from flask import Blueprint, request, jsonify, g
from models import db
from models.role import Role
from models.user import User
# from utils.jwt import generate_token,login_required
from extensions import db # 導入 db 實例
from utils.jwt import login_requiredapp_user = Blueprint("app_user", __name__)# 原有登錄接口改造
from sqlalchemy import select
import bcrypt # 導入 bcrypt 庫@app_user.route("/api/user/login", methods=['POST'])
def login():data = request.get_json()username = data.get('username')password = data.get('password', '').encode('utf-8') # 前端密碼轉為 bytes# 1. 反射 sys_user 表并查詢用戶sys_user = db.metadata.tables['sys_user']query = select(sys_user).where(sys_user.c.username == username)user = db.session.execute(query).fetchone()# 2. 基礎驗證(用戶存在 + 狀態正常)if not user:return jsonify(code=40000, message="用戶不存在"), 401 # 用戶不存在if user.status != 1: # 假設 1=正常,0=禁用return jsonify(code=40000, message="用戶禁用"), 403 # 用戶禁用# 3. bcrypt 密碼驗證(核心修復)db_password = user.password.encode('utf-8') # 數據庫密文轉為 bytesif not bcrypt.checkpw(password, db_password): # 驗證明文密碼與密文是否匹配return jsonify(code=40000, message="密碼錯誤"), 401 # 密碼錯誤# 4. 登錄成功(生成 Token 等后續邏輯)return jsonify(code=20000, message="success", data={"token": "your_token"})# 新增用戶信息接口
# apis/user.py(假設 info 接口代碼)
@app_user.route("/api/user/info", methods=['GET'])
def get_user_info():token = request.args.get('token')# 1. 驗證 token(省略,假設已驗證通過)# 2. 查詢用戶信息(使用之前反射表的方式)sys_user = db.metadata.tables['sys_user']user = db.session.execute(select(sys_user).where(sys_user.c.username == 'admin')).fetchone()# 3. 構造符合前端預期的響應格式return jsonify({"code": 20000, # 成功狀態碼(必須為前端約定的值)"message": "success", # 成功消息"data": {"name": user.name, # 用戶名(從數據庫獲取)"roles": ["admin"], # 用戶角色(根據實際權限獲取)"avatar": "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif" # 頭像(可選)}})# 新增用戶管理接口(管理員創建子賬號)
@app_user.route("/api/system/user", methods=['POST'])
@login_required
def create_user():current_user = g.user# 1. 校驗管理員權限if not any(role.role_code == 'SUPER_ADMIN' for role in current_user.roles):return jsonify(code=403, message='無權限創建用戶'), 403# 2. 處理請求數據data = request.get_json()new_user = User(username=data['username'],name=data['name'],create_by=current_user.id)new_user.set_password(data['password']) # 密碼加密# 3. 關聯角色role_ids = data.get('role_ids', [])roles = Role.query.filter(Role.id.in_(role_ids)).all()new_user.roles = rolesdb.session.add(new_user)db.session.commit()return jsonify(code=20000, message='用戶創建成功')
配置文件中需要做如下配置,在config中增加配置
# 權限相關配置
JWT_SECRET_KEY = 'your-jwt-secret-key' # 已有的 JWT 密鑰
JWT_ACCESS_TOKEN_EXPIRES = 3600 # Token 有效期 1 小時(已有的配置)# 添加:權限白名單路徑(無需認證即可訪問的接口)
PERMISSION_WHITELIST = ['/api/user/login', # 登錄接口(必須添加,否則無法登錄)'/api/user/register', # 注冊接口(如果有)'/api/common/captcha', # 驗證碼接口(如果有)# 前端靜態資源路徑(如果需要,如 /login.html, /favicon.ico)'/', '/login.html', '/favicon.ico'
]
重啟服務后重新登陸系統此時可以成功登錄
重構登陸頁面,之前的登陸頁面效果如下,看著不是很直觀,我們現在重構下風格--重構前
重構后源碼如下:
<template><div class="login-container"><!-- 左側背景區域 --><div class="login-left"><div class="left-content"><div class="logo"><svg-icon icon-class="logo" /><img src="@/assets/logo.gif" alt="R-B平臺LOGO" class="platform-logo"><span class="logo-text"></span></div><h1 class="welcome-text">歡迎回來</h1><p class="welcome-subtext">高效、安全、穩定的RB業務測試平臺 簡稱REBORT</p><div class="features"><div class="feature-item"><svg-icon icon-class="shield" class="feature-icon" /><div><h3>安全可靠</h3><p>需求統計管理</p></div></div><div class="feature-item"><svg-icon icon-class="rocket" class="feature-icon" /><div><h3>高效穩定</h3><p>99.9%的可用性,工具集成,自動化</p></div></div><div class="feature-item"><svg-icon icon-class="customize" class="feature-icon" /><div><h3>靈活跳轉</h3><p>環境地址快速跳轉</p></div></div></div></div><div class="copyright">? 2025 REBORT平臺 版權所有 一切皆有可能</div></div><!-- 右側登錄表單區域 --><div class="login-right"><div class="login-form-container"><div class="form-header"><h2>RB-TEST 平臺</h2><p>使用您的賬號密碼登錄系統</p></div><el-formref="loginForm":model="loginForm":rules="loginRules"class="login-form"auto-complete="on"label-position="left"><el-form-item prop="username" class="form-item"><span class="svg-container"><svg-icon icon-class="user" /></span><el-inputref="username"v-model="loginForm.username"placeholder="請輸入用戶名"name="username"type="text"tabindex="1"auto-complete="on"/></el-form-item><el-form-item prop="password" class="form-item"><span class="svg-container"><svg-icon icon-class="password" /></span><el-input:key="passwordType"ref="password"v-model="loginForm.password":type="passwordType"placeholder="請輸入密碼"name="password"tabindex="2"auto-complete="on"@keyup.enter.native="handleLogin"/><span class="show-pwd" @click="showPwd"><svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" /></span></el-form-item><div class="form-options"><el-checkbox v-model="rememberMe">記住我</el-checkbox><router-link to="/forgot-password" class="forgot-password">忘記密碼?</router-link></div><el-button:loading="loading"type="primary"class="login-btn"@click.native.prevent="handleLogin"><span v-if="!loading">登 錄</span><span v-else>登錄中...</span></el-button><div class="other-login"><p class="divider"><span>其他登錄方式</span></p><div class="social-login"><el-tooltip content="微信登錄" placement="top"><div class="social-icon wechat"><svg-icon icon-class="wechat" /></div></el-tooltip><el-tooltip content="企業微信" placement="top"><div class="social-icon QYwx"><svg-icon icon-class="QYwx" /></div></el-tooltip><el-tooltip content="QQ登錄" placement="top"><div class="social-icon QQ"><svg-icon icon-class="QQ" /></div></el-tooltip></div></div><div class="register-tip">還沒有賬號? <router-link to="/register">立即注冊</router-link></div></el-form></div></div></div>
</template><script>
import { validUsername } from '@/utils/validate'export default {name: 'Login',data() {const validateUsername = (rule, value, callback) => {if (!validUsername(value)) {callback(new Error('請輸入正確的用戶名'))} else {callback()}}const validatePassword = (rule, value, callback) => {if (value.length < 6) {callback(new Error('密碼長度不能少于6位'))} else {callback()}}return {loginForm: {username: '',password: ''},loginRules: {username: [{ required: true, trigger: 'blur', validator: validateUsername }],password: [{ required: true, trigger: 'blur', validator: validatePassword }]},loading: false,passwordType: 'password',redirect: undefined,rememberMe: false}},watch: {$route: {handler: function(route) {this.redirect = route.query && route.query.redirect},immediate: true}},methods: {showPwd() {if (this.passwordType === 'password') {this.passwordType = ''} else {this.passwordType = 'password'}this.$nextTick(() => {this.$refs.password.focus()})},handleLogin() {this.$refs.loginForm.validate(valid => {if (valid) {this.loading = truethis.$store.dispatch('user/login', this.loginForm).then(() => {this.$router.push({ path: this.redirect || '/' })this.loading = false}).catch(() => {this.loading = false})} else {console.log('error submit!!')return false}})}}
}
</script><style lang="scss" scoped>
// 顏色變量 - 統一紫色背景色
$primary-color: #4361ee;
$primary-hover: #3a56d4;
$white: #ffffff;
$light-bg: #f8fafc;
$text-color: #2d3748;
$light-text: #718096;
$border-color: #e2e8f0;
$error-color: #ef4444;
$purple-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%); // 統一的紫色漸變
$purple-dark: #5a4ca8; // 深紫色,用于裝飾元素.login-container {display: flex;min-height: 100vh;width: 100%;background: $purple-gradient; // 容器應用統一漸變背景// 左側內容區域.login-left {flex: 1;color: $white;padding: 2rem;display: flex;flex-direction: column;justify-content: space-between;position: relative;overflow: hidden;// 裝飾元素 - 統一風格&::before {content: '';position: absolute;top: 10%;left: 15%;width: 60px;height: 60px;background: rgba(255, 255, 255, 0.1);border-radius: 50%;}&::after {content: '';position: absolute;bottom: 15%;right: 20%;width: 120px;height: 120px;background: rgba(255, 255, 255, 0.05);border-radius: 50%;}/* 大LOGO樣式 */.platform-logo {width: 300px;height: 300px;object-fit: contain;}.left-content {position: relative;z-index: 2;max-width: 500px;margin: 0 auto;padding: 2rem;.logo {display: flex;align-items: center;margin-bottom: 3rem;.svg-icon {width: 40px;height: 40px;}.logo-text {font-size: 1.5rem;font-weight: bold;margin-left: 0.75rem;}}.welcome-text {font-size: 2.5rem;font-weight: 600;margin-bottom: 1rem;}.welcome-subtext {font-size: 1.125rem;opacity: 0.9;margin-bottom: 3rem;}.features {.feature-item {display: flex;align-items: center;margin-bottom: 1.5rem;.feature-icon {width: 40px;height: 40px;margin-right: 1rem;background: rgba(255, 255, 255, 0.1);border-radius: 8px;padding: 8px;}h3 {font-size: 1.125rem;margin: 0 0 0.25rem;}p {margin: 0;opacity: 0.8;font-size: 0.875rem;}}}}.copyright {position: relative;z-index: 2;text-align: center;font-size: 0.875rem;opacity: 0.7;padding: 1rem;}}// 右側登錄表單區域 - 關鍵修改:移除獨立背景色,使用容器統一背景.login-right {width: 590px;display: flex;align-items: center;padding: 2rem 1rem;position: relative; // 用于定位裝飾元素// 添加與左側風格一致的裝飾元素&::before {content: '';position: absolute;top: 20%;right: 30%;width: 60px;height: 60px;background: rgba(255, 255, 255, 0.1);border-radius: 50%;}&::after {content: '';position: absolute;bottom: 25%;right: 25%;width: 30px;height: 30px;background: rgba(255, 255, 255, 0.2);border-radius: 50%;}.login-form-container {width: 300%;max-width: 350px; // 表單調整margin: 0 auto;background: $white;padding: 2.5rem 1.5rem;border-radius: 12px;box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);animation: fadeIn 0.5s ease;position: relative;z-index: 2; // 確保表單在裝飾元素之上.form-header {margin-bottom: 1.5rem;text-align: center;h2 {font-size: 1.5rem;color: $text-color;margin: 0 0 0.5rem;}p {color: $light-text;margin: 0;font-size: 0.875rem;}}.login-form {.form-item {margin-bottom: 1rem;.el-input {width: 100%;::v-deep .el-input__inner {height: 42px;padding-left: 40px;border-radius: 6px;border: 1px solid $border-color;transition: all 0.3s;&:focus {border-color: $primary-color;box-shadow: 0 0 0 2px rgba(67, 97, 238, 0.2);}}}.svg-container {position: absolute;left: 12px;top: 50%;transform: translateY(-50%);color: $light-text;z-index: 2;}.show-pwd {position: absolute;right: 12px;top: 50%;transform: translateY(-50%);color: $light-text;cursor: pointer;z-index: 2;&:hover {color: $primary-color;}}}.form-options {display: flex;justify-content: space-between;align-items: center;margin-bottom: 1rem;font-size: 0.8rem;::v-deep .el-checkbox {color: $light-text;}.forgot-password {color: $light-text;font-size: 0.8rem;text-decoration: none;&:hover {color: $primary-color;text-decoration: underline;}}}.login-btn {width: 100%;height: 42px;background: $primary-color;border: none;border-radius: 6px;font-size: 0.9rem;font-weight: 500;color: $white;margin-bottom: 1rem;transition: all 0.3s;&:hover {background: $primary-hover;}&:active {transform: scale(0.98);}}.other-login {margin: 1rem 0;.divider {display: flex;align-items: center;color: $light-text;font-size: 0.7rem;margin: 0.5rem 0;&::before, &::after {content: "";flex: 1;height: 1px;background: $border-color;margin: 0 0.5rem;}}.social-login {display: flex;justify-content: center;gap: 1rem;.social-icon {width: 36px;height: 36px;border-radius: 50%;display: flex;align-items: center;justify-content: center;cursor: pointer;transition: all 0.3s;background: $light-bg;.svg-icon {width: 18px;height: 18px;}&.wechat {color: #07c160;&:hover {background: rgba(7, 193, 96, 0.1);}}&.QYwx {color: #2AAB7F;&:hover {background: rgba(42, 171, 127, 0.1);}}&.QQ {color: $primary-color;&:hover {background: rgba(67, 97, 238, 0.1);}}}}}.register-tip {text-align: center;color: $light-text;font-size: 0.8rem;margin-top: 1rem;a {color: $primary-color;text-decoration: none;font-weight: 500;&:hover {text-decoration: underline;}}}}}}
}// 動畫效果
@keyframes fadeIn {from {opacity: 0;transform: translateY(10px);}to {opacity: 1;transform: translateY(0);}
}// 響應式調整
@media (max-width: 992px) {.login-container {flex-direction: column;.login-left {display: none;}.login-right {width: 100%;padding: 2rem 1rem;}}
}// 錯誤狀態樣式
::v-deep .el-form-item.is-error {.el-input__inner {border-color: $error-color !important;}.svg-container {color: $error-color !important;}
}
</style>
看看重構后的效果,整體效果是不是看上去更加直觀
好了,登陸重構到這里結束
?