Skip to content

Correction m #63

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 28 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
c74e9b7
wiki added
Abdullah12has Jan 26, 2025
19b0432
wiki removed
Abdullah12has Jan 26, 2025
6eb8774
name updated
Abdullah12has Jan 26, 2025
775601f
Update README.md
Abdullah12has Jan 26, 2025
a94c056
Update README.md
uswah-batool Jan 26, 2025
42eee10
Create README.md
uswah-batool Jan 27, 2025
930150e
Add files via upload
uswah-batool Jan 27, 2025
6516f6f
Update README.md
Abdullah12has Feb 9, 2025
3db8284
Update README.md
Abdullah12has Feb 9, 2025
2c8c377
Database instance on docker + settings added
Abdullah12has Feb 9, 2025
ede6abb
python models added + test function flask app added to test it
Abdullah12has Feb 9, 2025
da5c15a
correction task2
Matheoleharicot Feb 27, 2025
49a0e4a
taskROUTE
Matheoleharicot Mar 1, 2025
072ed60
Add .gitignore and remove cached files
Matheoleharicot Mar 1, 2025
b41ffd0
Merge remote-tracking branch 'origin/correctionTask2'
Abdullah12has Mar 2, 2025
73754b1
Merge remote-tracking branch 'origin/localupdateM'
Abdullah12has Mar 2, 2025
47d4dc0
initial commit -login working
hsn07pk Mar 19, 2025
803b6d6
setup fixed with hashed passwords
Abdullah12has Mar 20, 2025
b3a5a82
API postman collection added
Abdullah12has Mar 20, 2025
41529b0
new conf
Abdullah12has Mar 20, 2025
f540ab0
6 tests passed in config with postgres
Abdullah12has Mar 20, 2025
2728d5a
app testing passed
Abdullah12has Mar 20, 2025
a6acb77
auth tests passed
Abdullah12has Mar 20, 2025
51a9209
users tests
Abdullah12has Mar 20, 2025
b15b4f1
routes 2 tests passed
Abdullah12has Mar 20, 2025
73960d8
test report, not all cases passed but report generated
Abdullah12has Mar 20, 2025
9bc3f0c
comment in readme added
Abdullah12has Mar 20, 2025
b453e02
fix issue Task_Route
Matheoleharicot Mar 29, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg

# Virtual Environment
venv/
env/
ENV/
.env

# IDE
.idea/
.vscode/
*.swp
*.swo
.DS_Store

# Testing
.coverage
htmlcov/
.pytest_cache/
.tox/

# Database
*.sqlite
*.db

# Logs
*.log
logs/
80 changes: 76 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,84 @@
# PWP SPRING 2025
# PROJECT NAME
# Group information
* Student 1. Name and email
* Student 2. Name and email
* Student 3. Name and email
* Student 4. Name and email
* Syed Abdullah Hassan [email protected]
* Muhammad Hassan Sohail. [email protected]
* Uswah Batool. [email protected]
* Mathéo Morin. [email protected]




__Remember to include all required documentation and HOWTOs, including how to create and populate the database, how to run and test the API, the url to the entrypoint, instructions on how to setup and run the client, instructions on how to setup and run the axiliary service and instructions on how to deploy the api in a production environment__


# PostgreSQL Docker Setup

## Prerequisites
Ensure you have Docker installed on your system. You can check by running:

```sh
docker --version
```

## Step 1: Run PostgreSQL Container
Start a PostgreSQL container using the official PostgreSQL image:

```sh
docker-compose up -d
```
This will download a PostSQL instance and run the docker container, also copy the setup database script and run that script inside that container and create the db & populate it with data.

## Step 2: Verify the Database and check it's data

```sh
docker exec -it my_postgres_db bash
```
You will be inside the docker instance, now you need to go inside the DB

```sh
psql -U admin -d task_management_db
```
Running this command inside the docker container will take you inside the DB: task_management_db

Now you can run to see all the tables
```sh
\dt
```

You can run any of these commands to see the data inside those tables.
```sh
SELECT * FROM "USER";
SELECT * FROM TEAM;
SELECT * FROM PROJECT;
SELECT * FROM TASK;
SELECT * FROM CATEGORY;
SELECT * FROM TEAM_MEMBERSHIP;
```

You can run to stop the db instance

```sh
docker stop my_postgres_db
```


You can run to remove the db container instance

```sh
docker rm my_postgres_db
```


# The Models and Flask App

The models in python are in the file models.py with all the classes present in the db and their helper functions and a app.py that calls the functions when you run the app.py flask app and call the http://127.0.0.1:5000/test. When the test endpoint is called it tried to add some users and then update and also delete that user just to show that the helper functions are working. And it returns the remaining users.


To run the test cases we need to run


```sh
pytest -v tests/ --html=reports/test_report.html --self-contained-html

```
97 changes: 97 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
# app.py
from flask import Flask, request, jsonify
from flask_jwt_extended import JWTManager, jwt_required, create_access_token, get_jwt_identity
from flask_caching import Cache
from werkzeug.security import check_password_hash
from models import (
db, init_db, create_user, get_all_users, update_user, delete_user,
PriorityEnum, StatusEnum, User
)
from routes.task_routes import task_bp
from routes.team_routes import team_bp
from routes.project_routes import project_bp
from routes.user_routes import user_bp
from datetime import timedelta
from werkzeug.security import check_password_hash
from extentions.extensions import cache # Import from extensions

def create_app():
app = Flask(__name__)
app.config['JWT_SECRET_KEY'] = 'super-secret' # Change this in production
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(hours=1) # Token expiration time
app.config['CACHE_DEFAULT_TIMEOUT'] = 300 # Cache expiry time (5 minutes)

jwt = JWTManager(app)
cache.init_app(app) # Initialize caching with the app
init_db(app)

# Register blueprints
app.register_blueprint(task_bp)
app.register_blueprint(team_bp)
app.register_blueprint(project_bp)
app.register_blueprint(user_bp)

# ---------------- AUTHENTICATION ROUTES ----------------

@app.route('/login', methods=['POST'])
def login():
data = request.get_json()
if not data or 'email' not in data or 'password' not in data:
return jsonify({'error': 'Missing email or password'}), 400

user = User.query.filter_by(email=data['email']).first()

if not user or not check_password_hash(user.password_hash, data['password']): # Correct password check
return jsonify({'error': 'Invalid credentials'}), 401

access_token = create_access_token(identity=str(user.user_id))
return jsonify({'access_token': access_token}), 200

# ---------------- ERROR HANDLERS ----------------

@app.errorhandler(400)
def bad_request(error):
return jsonify({'error': 'Bad Request', 'message': str(error)}), 400

@app.errorhandler(404)
def not_found(error):
return jsonify({'error': 'Not Found', 'message': str(error)}), 404

@app.errorhandler(500)
def internal_error(error):
return jsonify({'error': 'Internal Server Error', 'message': str(error)}), 500

# ---------------- TEST ROUTE ----------------

@app.route('/test', methods=['GET'])
@jwt_required()
@cache.cached(timeout=600, key_prefix=lambda: f"test_operations_{get_jwt_identity()}") # Cache per user
def test_operations():
"""Test endpoint to check authentication & caching."""
current_user_id = get_jwt_identity()
user = User.query.get(current_user_id)

if not user:
return jsonify({'error': 'User not found'}), 404

return jsonify({
'message': f'Hello {user.username}, you are authenticated!',
'user_id': current_user_id
})

# ---------------- CACHED USER FETCH ----------------

@app.route('/users', methods=['GET'])
@cache.cached(timeout=300, key_prefix='all_users') # Cache results for 5 minutes
def fetch_users():
"""Fetch all users with caching."""
users = get_all_users()
# Convert the list of User objects to a list of dictionaries using to_dict
users_list = [user.to_dict() for user in users]
return jsonify(users_list), 200

return app

if __name__ == '__main__':
app = create_app()
app.run(debug=True)
17 changes: 17 additions & 0 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
services:
postgres:
image: postgres:latest
container_name: my_postgres_db
restart: always
environment:
POSTGRES_USER: admin
POSTGRES_PASSWORD: helloworld123
POSTGRES_DB: task_management_db
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
- ./setup.sql:/docker-entrypoint-initdb.d/setup.sql

volumes:
postgres_data:
Empty file added docs/requests.md
Empty file.
4 changes: 4 additions & 0 deletions extentions/extensions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# extensions.py
from flask_caching import Cache

cache = Cache(config={'CACHE_TYPE': 'SimpleCache'}) # Simple in-memory caching
Loading