Rapportsystem API - of D03N
Hovedprosjekt FiV Programmering 20-24
Loading...
Searching...
No Matches
adminUpdateUsersPass.py
Go to the documentation of this file.
1#Imports nessesary modules
2from flask_restx import Resource
3from flask import request
4from flask_jwt_extended import jwt_required, get_jwt_identity
5
6#imports os
7import os
8current_directory = os.getcwd()
9#imports sys
10import sys
11sys.path.append(os.path.join(current_directory))
12
13#imports custom modules
14from SQLAdminConnections import SQL_AdminConnector as SQLC
15from SQLAdminConnections import SQL_AdminQuerys as SQLQ
16from PW_hashHandler import pw_manager as hash
17from Models import user_model as UM
18from Common.Requirements import valid_token as vt
19from USER_session import tokenHandler as TH
20
21# Update password route
23 @ns.route('/updateUsersPassword')
24 class admin_UpdatePassword(Resource):
25 new_password_model = UM.admin_update_password_model(ns)
26
27 #Documentation for swagger UI
28 @ns.doc('/updateUsersPassword',
29 description='Updates a users password when given username, password and a exact duplicate of the new password.\n\nRequires valid adminaccount and JWT token.',
30 responses={
31 200: 'OK',
32 400: 'Invalid Argument or faulty data',
33 500: 'Internal server error'
34 })
35
36 #Validates input
37 @ns.expect(new_password_model, validate=True)
38
39 #Requires valid JWT token authentication
40 @jwt_required()
41 @vt.require_valid_token
42
43 #recives user and password from admin and updates the password
44 def post(self):
45 data = request.get_json()
46
47 username = data['username']
48 new_pass1 = data['password1']
49 new_pass2 = data['password2']
50
51 if not data:
52 return {"Error": "No data provided"}
53
54 #updates password
55 return updatePassword(username, new_pass1, new_pass2)
56
57#Function for updating password
58def updatePassword(email, new_password1, new_password2):
59 if not new_password1 == new_password2:
60 return {"Password": "Does not match."}, 400
61
62 #hashes password
63 hashed_password = hash.hash(new_password1)
64
65 #Connects to the database and updates the password
66 connection = SQLC.SQLConAdmin()
67 connection.connect()
68 connection.execute_query(SQLQ.SQLQueries.use_users_database())
69
70 #gets user id
71 user_id = connection.execute_query(SQLQ.SQLQueries.get_user_id_by_email(email))
72 if not user_id:
73 return {"Error": "User not found."}, 400
74 user_id = user_id[0][0]
75
76 #updates password
77 connection.execute_query(SQLQ.SQLQueries.update_user_login_password(user_id, hashed_password))
78 connection.execute_query(SQLQ.SQLQueries.update_sql_user_password(email, new_password1))
79 connection.execute_query(SQLQ.SQLQueries.flush_privileges())
80 connection.cnx.commit()
81 connection.close()
82
83 # Lager en instans av UserTokenHandler
84 token_handler = TH.UserTokenHandler()
85
86 # Logger ut brukeren
87 token_handler.logout()
88
89 return {"User": email, "Password": "Updated"}, 200