用户登录功能
This commit is contained in:
@@ -1,11 +1,81 @@
|
||||
from flask import Blueprint, request, jsonify
|
||||
from flask import Blueprint, request, jsonify, session
|
||||
from datetime import datetime, timedelta
|
||||
from models import db, Task, TimeRecord
|
||||
from models import db, Task, TimeRecord, User
|
||||
from ai_service import ai_service
|
||||
import json
|
||||
|
||||
api = Blueprint('api', __name__)
|
||||
|
||||
# 认证API
|
||||
@api.route('/auth/login', methods=['POST'])
|
||||
def login():
|
||||
"""用户登录"""
|
||||
data = request.get_json()
|
||||
|
||||
if not data or 'username' not in data or 'password' not in data:
|
||||
return jsonify({'error': '用户名和密码不能为空'}), 400
|
||||
|
||||
username = data['username']
|
||||
password = data['password']
|
||||
|
||||
user = User.query.filter_by(username=username).first()
|
||||
|
||||
if user and user.check_password(password):
|
||||
# 登录成功,设置session
|
||||
session['user_id'] = user.id
|
||||
session['username'] = user.username
|
||||
return jsonify({
|
||||
'message': '登录成功',
|
||||
'user': user.to_dict()
|
||||
})
|
||||
else:
|
||||
return jsonify({'error': '用户名或密码错误'}), 401
|
||||
|
||||
@api.route('/auth/logout', methods=['POST'])
|
||||
def logout():
|
||||
"""用户登出"""
|
||||
session.clear()
|
||||
return jsonify({'message': '登出成功'})
|
||||
|
||||
@api.route('/auth/check', methods=['GET'])
|
||||
def check_auth():
|
||||
"""检查登录状态"""
|
||||
if 'user_id' in session:
|
||||
user = User.query.get(session['user_id'])
|
||||
if user:
|
||||
return jsonify({
|
||||
'authenticated': True,
|
||||
'user': user.to_dict()
|
||||
})
|
||||
return jsonify({'authenticated': False}), 401
|
||||
|
||||
@api.route('/auth/register', methods=['POST'])
|
||||
def register():
|
||||
"""用户注册(可选,用于创建初始用户)"""
|
||||
data = request.get_json()
|
||||
|
||||
if not data or 'username' not in data or 'password' not in data:
|
||||
return jsonify({'error': '用户名和密码不能为空'}), 400
|
||||
|
||||
username = data['username']
|
||||
password = data['password']
|
||||
|
||||
# 检查用户是否已存在
|
||||
if User.query.filter_by(username=username).first():
|
||||
return jsonify({'error': '用户名已存在'}), 400
|
||||
|
||||
# 创建新用户
|
||||
user = User(username=username)
|
||||
user.set_password(password)
|
||||
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
return jsonify({
|
||||
'message': '注册成功',
|
||||
'user': user.to_dict()
|
||||
}), 201
|
||||
|
||||
# 任务管理API
|
||||
@api.route('/tasks', methods=['GET'])
|
||||
def get_tasks():
|
||||
|
||||
Reference in New Issue
Block a user