beginning to add user session functionality

This commit is contained in:
Lucas Mathews
2024-05-21 00:05:43 +02:00
parent 544b9e1c2f
commit 139bda89a3
9 changed files with 83 additions and 42 deletions

14
api.py
View File

@@ -8,14 +8,26 @@
import connexion # Imports connexion module
from config import CONFIG # Imports the configuration file
from manager import * # Imports the Manager file that contains the functions for the API
from flask import Flask, session, jsonify, request # Imports the Flask module
from flask_session import Session # Imports the session module
#################
### Connexion ###
#################
def API():
def create_app():
app = connexion.FlaskApp(__name__)
app.add_api(CONFIG["api_file"]["name"])
flask_app = app.app
flask_app.config['SECRET_KEY'] = CONFIG["sessions"]["secret_key"]
flask_app.config['SESSION_TYPE'] = 'filesystem'
Session(flask_app)
return app
def API():
app = create_app()
app.run(host=CONFIG["server"]["listen_ip"], port=CONFIG["server"]["port"], debug=CONFIG["server"]["debug"]) # Runs the API using the configuration file
################

51
api.yml
View File

@@ -24,42 +24,49 @@ paths:
- client
summary: Log in to the system
description: Log in to the system
operationId: manager.login_user
requestBody:
description: Credentials for logging in
content:
application/json:
schema:
type: object
properties:
username:
type: string
password:
type: string
operationId: manager.login
parameters:
- name: client_id
in: query
description: Client Name
required: true
schema:
type: string
- name: password
in: query
description: Password
required: true
schema:
type: string
responses:
'200':
description: Successful operation
content:
application/json:
schema:
$ref: '#/components/schemas/Client'
'400':
description: Invalid username/password supplied
'401':
description: Unauthorized
description: Invalid Client ID/password supplied
/Client/Logout:
post:
tags:
- client
summary: Log out from the system
description: Log out from the system
operationId: manager.logout_user
operationId: manager.logout
responses:
'200':
description: Successful operation
'401':
description: Unauthorized
'404':
description: Already logged out
/Client/Status:
get:
tags:
- client
summary: Get client status
description: Get client status
operationId: manager.status
responses:
'200':
description: Logged in
'400':
description: Not logged in
/Client/Password:
put:
tags:

View File

@@ -17,3 +17,6 @@ debug=True
[api]
url=http://0.0.0.0:81/
[sessions]
secret_key=57d7dfef5a519fe73d3ba1a9ced6477f

View File

@@ -4,8 +4,6 @@
from sqlalchemy import ForeignKey, Column, String, Integer, Boolean
from sqlalchemy.orm import relationship
from class_base import Base
class Account(Base):

View File

@@ -1,10 +1,9 @@
# Lucas Mathews - Fontys Student ID: 5023572
# Banking System Client Class
from sqlalchemy import Column, String, Boolean, ForeignKey
from sqlalchemy import Column, String, Boolean
from sqlalchemy.orm import relationship
from class_base import Base
class Client(Base):

View File

@@ -6,7 +6,7 @@ import os.path
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
#Import Config
# Import Config
from config import CONFIG
# Check if the database exists
@@ -22,7 +22,7 @@ print(f"Database file set to: {db_url}")
# Creates the database engine (does not create the database file if it already exists)
engine = create_engine(db_url, echo=True)
#Import base class
# Import base class
from class_base import Base # Imports the base class required by SQLAlchemy
# Create the tables in the database

7
generate_session_key.py Normal file
View File

@@ -0,0 +1,7 @@
# Lucas Mathews - Fontys Student ID: 5023572
# Banking System Secret Key Generator
# Generates a secret key for the banking system API to manage user sessions
import secrets
secret_key = secrets.token_hex(16) # Generates a 32-character hex string
print(secret_key)

View File

@@ -4,7 +4,7 @@
from class_client import Client
from class_account import Account
from class_transaction import Transaction
from flask import jsonify
from flask import jsonify, session, request # Imports the Flask modules
import hashlib # hashlib for password hashing
import datetime # datetime for timestamps
import uuid # uuid for unique identifiers
@@ -32,6 +32,30 @@ def generate_uuid_short(): # Generates a short uuid
### Client ###
##############
def login(client_id:str, password:str): # Logs in a user
password_hash = password_hash(password)
for client in session.query(Client).all():
if client.client_id == client_id and client.hash == password_hash:
session['client_id'] = client_id
return jsonify({"message": f"{session['username']} logged in succsessfully."}), 200
return "Invalid client_id or password.", 401
def logout():
if 'client_id' in session:
session.pop('client_id', None)
return jsonify({"message": "Logged out"}), 200
return jsonify({"message": "Not logged in"}), 404
def status():
if 'client_id' in session:
return jsonify({"message": f"Logged in as {session['username']}"}), 200
else:
return jsonify({"message": "Not logged in"}), 400
##############
### Client ###
##############
def get_client(client_id:str): # Returns a specific client in the database
client = session.query(Client).filter_by(client_id=client_id).one_or_none()
for client in session.query(Client).all():
@@ -96,16 +120,6 @@ def change_password(client_id:str, password:str, new_password:str): # Changes th
return f"client_id: {client_id} is not found.", 404
def login_user(email:str, password:str):
for client in session.query(Client).all():
if client.email == email and client.password == password:
return f"Welcome {client.name}."
return "Invalid email or password."
def logout_user():
return "You have been logged out."
###############
### Account ###
###############

View File

@@ -2,3 +2,4 @@ flask
connexion[swagger-ui]==2.14.2
requests
sqlalchemy
flask-session