jinhai-2012 commited on
Commit
1ee0da9
·
1 Parent(s): 367f6bc

Refactor user register & login (#1971)

Browse files

### What problem does this PR solve?

1. Rename the variable
2. Refactor error message
3. Format the code

### Type of change

- [x] Refactoring

---------

Signed-off-by: Jin Hai <[email protected]>

Files changed (1) hide show
  1. api/apps/user_app.py +65 -46
api/apps/user_app.py CHANGED
@@ -37,23 +37,25 @@ from api.utils.api_utils import get_json_result, construct_response
37
 
38
  @manager.route('/login', methods=['POST', 'GET'])
39
  def login():
40
- login_channel = "password"
41
  if not request.json:
42
- return get_json_result(data=False, retcode=RetCode.AUTHENTICATION_ERROR,
43
- retmsg='Unautherized!')
 
44
 
45
  email = request.json.get('email', "")
46
  users = UserService.query(email=email)
47
  if not users:
48
- return get_json_result(
49
- data=False, retcode=RetCode.AUTHENTICATION_ERROR, retmsg=f'This Email is not registered!')
 
50
 
51
  password = request.json.get('password')
52
  try:
53
  password = decrypt(password)
54
  except BaseException:
55
- return get_json_result(
56
- data=False, retcode=RetCode.SERVER_ERROR, retmsg='Fail to crypt password')
 
57
 
58
  user = UserService.query_user(email, password)
59
  if user:
@@ -66,18 +68,20 @@ def login():
66
  msg = "Welcome back!"
67
  return construct_response(data=response_data, auth=user.get_id(), retmsg=msg)
68
  else:
69
- return get_json_result(data=False, retcode=RetCode.AUTHENTICATION_ERROR,
70
- retmsg='Email and Password do not match!')
 
71
 
72
 
73
  @manager.route('/github_callback', methods=['GET'])
74
  def github_callback():
75
  import requests
76
- res = requests.post(GITHUB_OAUTH.get("url"), data={
77
- "client_id": GITHUB_OAUTH.get("client_id"),
78
- "client_secret": GITHUB_OAUTH.get("secret_key"),
79
- "code": request.args.get('code')
80
- }, headers={"Accept": "application/json"})
 
81
  res = res.json()
82
  if "error" in res:
83
  return redirect("/?error=%s" % res["error_description"])
@@ -87,29 +91,33 @@ def github_callback():
87
 
88
  session["access_token"] = res["access_token"]
89
  session["access_token_from"] = "github"
90
- userinfo = user_info_from_github(session["access_token"])
91
- users = UserService.query(email=userinfo["email"])
 
92
  user_id = get_uuid()
93
  if not users:
 
94
  try:
95
  try:
96
- avatar = download_img(userinfo["avatar_url"])
97
  except Exception as e:
98
  stat_logger.exception(e)
99
  avatar = ""
100
  users = user_register(user_id, {
101
  "access_token": session["access_token"],
102
- "email": userinfo["email"],
103
  "avatar": avatar,
104
- "nickname": userinfo["login"],
105
  "login_channel": "github",
106
  "last_login_time": get_format_time(),
107
  "is_superuser": False,
108
  })
109
  if not users:
110
- raise Exception('Register user failure.')
111
  if len(users) > 1:
112
- raise Exception('Same E-mail exist!')
 
 
113
  user = users[0]
114
  login_user(user)
115
  return redirect("/?auth=%s" % user.get_id())
@@ -117,6 +125,8 @@ def github_callback():
117
  rollback_user_registration(user_id)
118
  stat_logger.exception(e)
119
  return redirect("/?error=%s" % str(e))
 
 
120
  user = users[0]
121
  user.access_token = get_uuid()
122
  login_user(user)
@@ -127,19 +137,25 @@ def github_callback():
127
  @manager.route('/feishu_callback', methods=['GET'])
128
  def feishu_callback():
129
  import requests
130
- app_access_token_res = requests.post(FEISHU_OAUTH.get("app_access_token_url"), data=json.dumps({
131
- "app_id": FEISHU_OAUTH.get("app_id"),
132
- "app_secret": FEISHU_OAUTH.get("app_secret")
133
- }), headers={"Content-Type": "application/json; charset=utf-8"})
 
 
134
  app_access_token_res = app_access_token_res.json()
135
  if app_access_token_res['code'] != 0:
136
  return redirect("/?error=%s" % app_access_token_res)
137
 
138
- res = requests.post(FEISHU_OAUTH.get("user_access_token_url"), data=json.dumps({
139
- "grant_type": FEISHU_OAUTH.get("grant_type"),
140
- "code": request.args.get('code')
141
- }), headers={"Content-Type": "application/json; charset=utf-8",
142
- 'Authorization': f"Bearer {app_access_token_res['app_access_token']}"})
 
 
 
 
143
  res = res.json()
144
  if res['code'] != 0:
145
  return redirect("/?error=%s" % res["message"])
@@ -148,29 +164,33 @@ def feishu_callback():
148
  return redirect("/?error=contact:user.email:readonly not in scope")
149
  session["access_token"] = res["data"]["access_token"]
150
  session["access_token_from"] = "feishu"
151
- userinfo = user_info_from_feishu(session["access_token"])
152
- users = UserService.query(email=userinfo["email"])
 
153
  user_id = get_uuid()
154
  if not users:
 
155
  try:
156
  try:
157
- avatar = download_img(userinfo["avatar_url"])
158
  except Exception as e:
159
  stat_logger.exception(e)
160
  avatar = ""
161
  users = user_register(user_id, {
162
  "access_token": session["access_token"],
163
- "email": userinfo["email"],
164
  "avatar": avatar,
165
- "nickname": userinfo["en_name"],
166
  "login_channel": "feishu",
167
  "last_login_time": get_format_time(),
168
  "is_superuser": False,
169
  })
170
  if not users:
171
- raise Exception('Register user failure.')
172
  if len(users) > 1:
173
- raise Exception('Same E-mail exist!')
 
 
174
  user = users[0]
175
  login_user(user)
176
  return redirect("/?auth=%s" % user.get_id())
@@ -178,6 +198,8 @@ def feishu_callback():
178
  rollback_user_registration(user_id)
179
  stat_logger.exception(e)
180
  return redirect("/?error=%s" % str(e))
 
 
181
  user = users[0]
182
  user.access_token = get_uuid()
183
  login_user(user)
@@ -232,12 +254,10 @@ def setting_user():
232
  new_password = request_data.get("new_password")
233
  if not check_password_hash(
234
  current_user.password, decrypt(request_data["password"])):
235
- return get_json_result(
236
- data=False, retcode=RetCode.AUTHENTICATION_ERROR, retmsg='Password error!')
237
 
238
  if new_password:
239
- update_dict["password"] = generate_password_hash(
240
- decrypt(new_password))
241
 
242
  for k in request_data.keys():
243
  if k in ["password", "new_password"]:
@@ -249,13 +269,12 @@ def setting_user():
249
  return get_json_result(data=True)
250
  except Exception as e:
251
  stat_logger.exception(e)
252
- return get_json_result(
253
- data=False, retmsg='Update failure!', retcode=RetCode.EXCEPTION_ERROR)
254
 
255
 
256
  @manager.route("/info", methods=["GET"])
257
  @login_required
258
- def user_info():
259
  return get_json_result(data=current_user.to_dict())
260
 
261
 
@@ -337,7 +356,7 @@ def user_add():
337
  # Validate the email address
338
  if not re.match(r"^[\w\._-]+@([\w_-]+\.)+[\w-]{2,4}$", email_address):
339
  return get_json_result(data=False,
340
- retmsg=f'Invalid Email address: {email_address}!',
341
  retcode=RetCode.OPERATING_ERROR)
342
 
343
  # Check if the email address is already used
@@ -365,7 +384,7 @@ def user_add():
365
  if not users:
366
  raise Exception(f'Fail to register {email_address}.')
367
  if len(users) > 1:
368
- raise Exception(f'Same E-mail: {email_address} exists!')
369
  user = users[0]
370
  login_user(user)
371
  return construct_response(data=user.to_json(),
 
37
 
38
  @manager.route('/login', methods=['POST', 'GET'])
39
  def login():
 
40
  if not request.json:
41
+ return get_json_result(data=False,
42
+ retcode=RetCode.AUTHENTICATION_ERROR,
43
+ retmsg='Unauthorized!')
44
 
45
  email = request.json.get('email', "")
46
  users = UserService.query(email=email)
47
  if not users:
48
+ return get_json_result(data=False,
49
+ retcode=RetCode.AUTHENTICATION_ERROR,
50
+ retmsg=f'Email: {email} is not registered!')
51
 
52
  password = request.json.get('password')
53
  try:
54
  password = decrypt(password)
55
  except BaseException:
56
+ return get_json_result(data=False,
57
+ retcode=RetCode.SERVER_ERROR,
58
+ retmsg='Fail to crypt password')
59
 
60
  user = UserService.query_user(email, password)
61
  if user:
 
68
  msg = "Welcome back!"
69
  return construct_response(data=response_data, auth=user.get_id(), retmsg=msg)
70
  else:
71
+ return get_json_result(data=False,
72
+ retcode=RetCode.AUTHENTICATION_ERROR,
73
+ retmsg='Email and password do not match!')
74
 
75
 
76
  @manager.route('/github_callback', methods=['GET'])
77
  def github_callback():
78
  import requests
79
+ res = requests.post(GITHUB_OAUTH.get("url"),
80
+ data={
81
+ "client_id": GITHUB_OAUTH.get("client_id"),
82
+ "client_secret": GITHUB_OAUTH.get("secret_key"),
83
+ "code": request.args.get('code')},
84
+ headers={"Accept": "application/json"})
85
  res = res.json()
86
  if "error" in res:
87
  return redirect("/?error=%s" % res["error_description"])
 
91
 
92
  session["access_token"] = res["access_token"]
93
  session["access_token_from"] = "github"
94
+ user_info = user_info_from_github(session["access_token"])
95
+ email_address = user_info["email"]
96
+ users = UserService.query(email=email_address)
97
  user_id = get_uuid()
98
  if not users:
99
+ # User isn't try to register
100
  try:
101
  try:
102
+ avatar = download_img(user_info["avatar_url"])
103
  except Exception as e:
104
  stat_logger.exception(e)
105
  avatar = ""
106
  users = user_register(user_id, {
107
  "access_token": session["access_token"],
108
+ "email": email_address,
109
  "avatar": avatar,
110
+ "nickname": user_info["login"],
111
  "login_channel": "github",
112
  "last_login_time": get_format_time(),
113
  "is_superuser": False,
114
  })
115
  if not users:
116
+ raise Exception(f'Fail to register {email_address}.')
117
  if len(users) > 1:
118
+ raise Exception(f'Same email: {email_address} exists!')
119
+
120
+ # Try to log in
121
  user = users[0]
122
  login_user(user)
123
  return redirect("/?auth=%s" % user.get_id())
 
125
  rollback_user_registration(user_id)
126
  stat_logger.exception(e)
127
  return redirect("/?error=%s" % str(e))
128
+
129
+ # User has already registered, try to log in
130
  user = users[0]
131
  user.access_token = get_uuid()
132
  login_user(user)
 
137
  @manager.route('/feishu_callback', methods=['GET'])
138
  def feishu_callback():
139
  import requests
140
+ app_access_token_res = requests.post(FEISHU_OAUTH.get("app_access_token_url"),
141
+ data=json.dumps({
142
+ "app_id": FEISHU_OAUTH.get("app_id"),
143
+ "app_secret": FEISHU_OAUTH.get("app_secret")
144
+ }),
145
+ headers={"Content-Type": "application/json; charset=utf-8"})
146
  app_access_token_res = app_access_token_res.json()
147
  if app_access_token_res['code'] != 0:
148
  return redirect("/?error=%s" % app_access_token_res)
149
 
150
+ res = requests.post(FEISHU_OAUTH.get("user_access_token_url"),
151
+ data=json.dumps({
152
+ "grant_type": FEISHU_OAUTH.get("grant_type"),
153
+ "code": request.args.get('code')
154
+ }),
155
+ headers={
156
+ "Content-Type": "application/json; charset=utf-8",
157
+ 'Authorization': f"Bearer {app_access_token_res['app_access_token']}"
158
+ })
159
  res = res.json()
160
  if res['code'] != 0:
161
  return redirect("/?error=%s" % res["message"])
 
164
  return redirect("/?error=contact:user.email:readonly not in scope")
165
  session["access_token"] = res["data"]["access_token"]
166
  session["access_token_from"] = "feishu"
167
+ user_info = user_info_from_feishu(session["access_token"])
168
+ email_address = user_info["email"]
169
+ users = UserService.query(email=email_address)
170
  user_id = get_uuid()
171
  if not users:
172
+ # User isn't try to register
173
  try:
174
  try:
175
+ avatar = download_img(user_info["avatar_url"])
176
  except Exception as e:
177
  stat_logger.exception(e)
178
  avatar = ""
179
  users = user_register(user_id, {
180
  "access_token": session["access_token"],
181
+ "email": email_address,
182
  "avatar": avatar,
183
+ "nickname": user_info["en_name"],
184
  "login_channel": "feishu",
185
  "last_login_time": get_format_time(),
186
  "is_superuser": False,
187
  })
188
  if not users:
189
+ raise Exception(f'Fail to register {email_address}.')
190
  if len(users) > 1:
191
+ raise Exception(f'Same email: {email_address} exists!')
192
+
193
+ # Try to log in
194
  user = users[0]
195
  login_user(user)
196
  return redirect("/?auth=%s" % user.get_id())
 
198
  rollback_user_registration(user_id)
199
  stat_logger.exception(e)
200
  return redirect("/?error=%s" % str(e))
201
+
202
+ # User has already registered, try to log in
203
  user = users[0]
204
  user.access_token = get_uuid()
205
  login_user(user)
 
254
  new_password = request_data.get("new_password")
255
  if not check_password_hash(
256
  current_user.password, decrypt(request_data["password"])):
257
+ return get_json_result(data=False, retcode=RetCode.AUTHENTICATION_ERROR, retmsg='Password error!')
 
258
 
259
  if new_password:
260
+ update_dict["password"] = generate_password_hash(decrypt(new_password))
 
261
 
262
  for k in request_data.keys():
263
  if k in ["password", "new_password"]:
 
269
  return get_json_result(data=True)
270
  except Exception as e:
271
  stat_logger.exception(e)
272
+ return get_json_result(data=False, retmsg='Update failure!', retcode=RetCode.EXCEPTION_ERROR)
 
273
 
274
 
275
  @manager.route("/info", methods=["GET"])
276
  @login_required
277
+ def user_profile():
278
  return get_json_result(data=current_user.to_dict())
279
 
280
 
 
356
  # Validate the email address
357
  if not re.match(r"^[\w\._-]+@([\w_-]+\.)+[\w-]{2,4}$", email_address):
358
  return get_json_result(data=False,
359
+ retmsg=f'Invalid email address: {email_address}!',
360
  retcode=RetCode.OPERATING_ERROR)
361
 
362
  # Check if the email address is already used
 
384
  if not users:
385
  raise Exception(f'Fail to register {email_address}.')
386
  if len(users) > 1:
387
+ raise Exception(f'Same email: {email_address} exists!')
388
  user = users[0]
389
  login_user(user)
390
  return construct_response(data=user.to_json(),