-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathauth.py
More file actions
240 lines (205 loc) · 7.43 KB
/
auth.py
File metadata and controls
240 lines (205 loc) · 7.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
from flask import Blueprint, request, jsonify
from models import db, User
from sqlalchemy.exc import IntegrityError
from functools import wraps
auth_bp = Blueprint('auth', __name__, url_prefix='/auth')
# 移除了邮箱格式和密码强度验证函数
@auth_bp.route('/register', methods=['POST'])
def register():
"""用户注册接口"""
try:
# 获取请求数据
data = request.get_json()
if not data:
return jsonify({
'success': False,
'message': 'Invalid request data'
}), 400
username = data.get('username', '').strip()
email = data.get('email', '').strip() if data.get('email') else None
password = data.get('password', '')
# 移除了用户名和密码为空的检测
# 检查用户名是否已存在
existing_user = User.query.filter(User.username == username).first()
if existing_user:
return jsonify({
'success': False,
'message': 'Username already exists'
}), 409
# 如果提供了邮箱,检查邮箱是否已存在
if email:
existing_email = User.query.filter(User.email == email).first()
if existing_email:
return jsonify({
'success': False,
'message': 'Email already registered'
}), 409
# 创建新用户
new_user = User(username=username, password=password, email=email)
db.session.add(new_user)
db.session.commit()
return jsonify({
'success': True,
'message': 'Registration successful',
'user': new_user.to_dict()
}), 201
except IntegrityError:
db.session.rollback()
return jsonify({
'success': False,
'message': 'Database constraint error'
}), 409
except Exception as e:
db.session.rollback()
return jsonify({
'success': False,
'message': f'Registration failed: {str(e)}'
}), 500
@auth_bp.route('/login', methods=['POST'])
def login():
"""用户登录接口"""
try:
# 获取请求数据
data = request.get_json()
if not data:
return jsonify({
'success': False,
'message': 'Invalid request data'
}), 400
username_or_email = data.get('username', '').strip()
password = data.get('password', '')
# 移除了用户名/邮箱和密码为空的检测
# 查找用户(支持用户名或邮箱登录)
user = User.query.filter(
(User.username == username_or_email) |
(User.email.isnot(None) & (User.email == username_or_email))
).first()
if not user:
return jsonify({
'success': False,
'message': 'User not found'
}), 404
# 检查用户是否激活
if not user.is_active:
return jsonify({
'success': False,
'message': 'Account disabled'
}), 403
# 验证密码
if not user.check_password(password):
return jsonify({
'success': False,
'message': 'Invalid password'
}), 401
return jsonify({
'success': True,
'message': 'Login successful',
'user': user.to_dict(),
'token': user.id # 返回用户ID作为认证token
}), 200
except Exception as e:
return jsonify({
'success': False,
'message': f'Login failed: {str(e)}'
}), 500
@auth_bp.route('/logout', methods=['POST'])
def logout():
"""用户登出接口"""
try:
# 获取请求数据
data = request.get_json()
if not data:
return jsonify({
'success': False,
'message': 'Invalid request data'
}), 400
username_or_email = data.get('username', '').strip()
# 查找用户(支持用户名或邮箱登出)
user = User.query.filter(
(User.username == username_or_email) |
(User.email.isnot(None) & (User.email == username_or_email))
).first()
if not user:
return jsonify({
'success': False,
'message': 'User not found'
}), 404
# 检查用户是否激活
if not user.is_active:
return jsonify({
'success': False,
'message': 'Account disabled'
}), 403
return jsonify({
'success': True,
'message': 'Logout successful',
'user': user.to_dict()
}), 200
except Exception as e:
return jsonify({
'success': False,
'message': f'Logout failed: {str(e)}'
}), 500
@auth_bp.route('/status', methods=['GET'])
def status():
"""服务状态检查接口"""
return jsonify({
'success': True,
'message': 'Auth service running',
'service': 'ToDoList Auth Service'
}), 200
# 简单的Token认证装饰器:Authorization: Bearer <token>
# token可为用户id、用户名或邮箱
def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
auth_header = request.headers.get('Authorization', '')
if not auth_header or not auth_header.startswith('Bearer '):
return jsonify({'message': 'Missing or invalid Authorization header'}), 401
token = auth_header.split('Bearer ', 1)[1].strip()
if not token:
return jsonify({'message': 'Token missing'}), 401
user = User.query.filter(
(User.id == token) | (User.username == token) | (User.email == token)
).first()
if not user:
return jsonify({'message': 'Invalid token'}), 401
if not user.is_active:
return jsonify({'message': 'Account disabled'}), 403
return f(current_user=user, *args, **kwargs)
return decorated
@auth_bp.route('/change-password', methods=['POST'])
@token_required
def change_password(current_user):
"""修改密码接口"""
try:
data = request.get_json()
if not data:
return jsonify({
'success': False,
'message': 'Invalid request data'
}), 400
old_password = data.get('old_password', '')
new_password = data.get('new_password', '')
if not old_password or not new_password:
return jsonify({
'success': False,
'message': 'Both old and new passwords are required'
}), 400
if not current_user.check_password(old_password):
return jsonify({
'success': False,
'message': 'Invalid old password'
}), 401
current_user.set_password(new_password)
db.session.commit()
return jsonify({
'success': True,
'message': 'Password changed successfully'
}), 200
except Exception as e:
db.session.rollback()
return jsonify({
'success': False,
'message': f'Change password failed: {str(e)}'
}), 500