Rapportsystem API - of D03N
Hovedprosjekt FiV Programmering 20-24
Loading...
Searching...
No Matches
updatePassword.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('/updatePassword')
24 class UpdatePassword(Resource):
25 new_password_model = UM.update_password_model(ns)
26
27 #Documentation for swagger UI
28 @ns.doc('/updatePassword',
29 description='Updates a users password when given new password and a exact duplicate of the new password.\n\nRequires valid JWT token authentication.',
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 password data from user
44 def post(self):
45 current_user = get_jwt_identity()
46 data = request.get_json()
47
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(current_user['user_id'], current_user['email'], new_pass1, new_pass2)
56
57#Function for updating password
58def updatePassword(user_id, 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 connection.execute_query(SQLQ.SQLQueries.update_user_login_password(user_id, hashed_password))
70 connection.execute_query(SQLQ.SQLQueries.update_sql_user_password(email, hashed_password))
71 connection.execute_query(SQLQ.SQLQueries.flush_privileges())
72 connection.cnx.commit()
73 connection.close()
74
75 # Lager en instans av UserTokenHandler
76 token_handler = TH.UserTokenHandler()
77
78 # Logger ut brukeren
79 token_handler.logout()
80
81 return {"Password": "Updated!", "New password": "PROTECTED"}, 200