Skip to content

Commit cf49467

Browse files
authored
Update users.py
1 parent 9ec4b74 commit cf49467

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

api_views/users.py

+62
Original file line numberDiff line numberDiff line change
@@ -206,3 +206,65 @@ def delete_user(username):
206206
return Response(error_message_helper("User not found!"), 404, mimetype="application/json")
207207
else:
208208
return Response(error_message_helper("Only Admins may delete users!"), 401, mimetype="application/json")
209+
210+
211+
def get_user_by_email(email):
212+
"""
213+
Retrieve user details by email address.
214+
"""
215+
user = User.query.filter_by(email=email).first()
216+
if user:
217+
return jsonify(user.json()), 200
218+
else:
219+
return Response(error_message_helper(), 404, mimetype="application/json")
220+
221+
222+
def promote_user_to_admin(username):
223+
"""
224+
Promote a user to admin status. Only accessible by current admins.
225+
"""
226+
resp = token_validator(request.headers.get('Authorization'))
227+
if "expired" in resp or "Invalid token" in resp:
228+
return Response(error_message_helper(resp), 401, mimetype="application/json")
229+
230+
current_user = User.query.filter_by(username=resp).first()
231+
if not current_user.admin:
232+
return Response(error_message_helper("Only Admins may promote users!"), 401, mimetype="application/json")
233+
234+
user = User.query.filter_by(username=username).first()
235+
if user:
236+
user.admin = True
237+
db.session.commit()
238+
responseObject = {
239+
'status': 'success',
240+
'message': 'User promoted to admin.'
241+
}
242+
return Response(json.dumps(responseObject), 200, mimetype="application/json")
243+
else:
244+
return Response(error_message_helper("User not found!"), 404, mimetype="application/json")
245+
246+
247+
def deactivate_user_account(username):
248+
"""
249+
Deactivate a user account. Only accessible by current admins.
250+
"""
251+
resp = token_validator(request.headers.get('Authorization'))
252+
if "expired" in resp or "Invalid token" in resp:
253+
return Response(error_message_helper(resp), 401, mimetype="application/json")
254+
255+
current_user = User.query.filter_by(username=resp).first()
256+
if not current_user.admin:
257+
return Response(error_message_helper("Only Admins may deactivate user accounts!"), 401, mimetype="application/json")
258+
259+
user = User.query.filter_by(username=username).first()
260+
if user:
261+
user.active = False # Assuming 'active' is a column to manage account status
262+
db.session.commit()
263+
responseObject = {
264+
'status': 'success',
265+
'message': 'User account deactivated.'
266+
}
267+
return Response(json.dumps(responseObject), 200, mimetype="application/json")
268+
else:
269+
return Response(error_message_helper("User not found!"), 404, mimetype="application/json")
270+

0 commit comments

Comments
 (0)