Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Marty Bode
committed
Jan 29, 2024
1 parent
7ba0906
commit e4c5577
Showing
1 changed file
with
36 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
from werkzeug.security import check_password_hash | ||
from flask_restful import Resource | ||
from flask import request | ||
from middleware.user_queries import user_get_results | ||
import uuid | ||
|
||
|
||
class ApiKey(Resource): | ||
def __init__(self, **kwargs): | ||
self.psycopg2_connection = kwargs["psycopg2_connection"] | ||
|
||
def get(self): | ||
""" | ||
Generate an API key for a user that successfully logs in | ||
""" | ||
try: | ||
data = request.get_json() | ||
email = data.get("email") | ||
password = data.get("password") | ||
cursor = self.psycopg2_connection.cursor() | ||
user_data = user_get_results(cursor, email) | ||
|
||
if check_password_hash(user_data["password_digest"], password): | ||
api_key = uuid.uuid4().hex | ||
user_id = str(user_data["id"]) | ||
cursor.execute( | ||
"UPDATE users SET api_key = %s WHERE id = %s", (api_key, user_id) | ||
) | ||
payload = {"api_key": api_key} | ||
self.psycopg2_connection.commit() | ||
return payload | ||
|
||
except Exception as e: | ||
self.psycopg2_connection.rollback() | ||
print(str(e)) | ||
return {"error": str(e)} |