Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
8 changes: 4 additions & 4 deletions backend/app/routes/authorization.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from functools import wraps

import jwt
from flask import request, jsonify, Blueprint, current_app
from flask import request, jsonify, Blueprint, current_app, g
from werkzeug.security import check_password_hash, generate_password_hash

from app import db
Expand All @@ -15,7 +15,7 @@ def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
if request.method == 'OPTIONS':
return f(*args, **kwargs)
return '', 204
token = None
if 'Authorization' in request.headers:
auth_header = request.headers['Authorization']
Expand All @@ -27,14 +27,14 @@ def decorated(*args, **kwargs):

try:
data = jwt.decode(token, current_app.config['SECRET_KEY'], algorithms=["HS256"])
current_user = data['username']
g.current_user = data['username']

except jwt.ExpiredSignatureError:
return jsonify({"message": "Token wygasl, zaloguj się ponownie"}), 401
except jwt.InvalidTokenError:
return jsonify({"message": "Token jest nieprawidlowy!"}), 401

return f(current_user, *args, **kwargs)
return f(*args, **kwargs)

return decorated

Expand Down
6 changes: 3 additions & 3 deletions backend/app/routes/dashboard.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
from flask import Blueprint, jsonify, request
from flask import Blueprint, jsonify, request, g
from app.services.dashboard_service import DashboardService
from app.routes.authorization import token_required

dashboard_bp = Blueprint('dashboard', __name__)

@dashboard_bp.route('/api/dashboard', methods=['GET'])
@token_required
def get_dashboard(current_user):
def get_dashboard():
"""
Endpoint to retrieve user dashboard data.

Expand All @@ -25,7 +25,7 @@ def get_dashboard(current_user):
timezone = request.headers.get('X-Timezone', 'Europe/Warsaw')

# Get dashboard data
dashboard_dto = DashboardService.get_user_dashboard_data(current_user, timezone)
dashboard_dto = DashboardService.get_user_dashboard_data(g.current_user, timezone)
serialized_data = DashboardService.serialize_dashboard_response(dashboard_dto)

return jsonify(serialized_data), 200
Expand Down
16 changes: 8 additions & 8 deletions backend/app/routes/settings.py
Original file line number Diff line number Diff line change
@@ -1,37 +1,37 @@
from flask import Blueprint, jsonify, request
from flask import Blueprint, jsonify, request, g

from app.routes.authorization import token_required
from app.services.settings_service import SettingsService

settings_bp = Blueprint('settings', __name__)

@settings_bp.route('/api/settings/<string:username>', methods=['GET', 'PATCH'])
@settings_bp.route('/api/settings', methods=['GET', 'PATCH'])
@token_required
def handle_settings(username):
def handle_settings():
if request.method == 'GET':
try:
settings_dto = SettingsService._get_user_settings(username)
settings_dto = SettingsService.get_user_settings(g.current_user)
return jsonify(settings_dto), 200
except Exception as e:
return jsonify({'error': str(e)}), 500

if request.method == 'PATCH':
try:
data = request.get_json()
updated_settings = SettingsService.update_user_settings(username, data)
updated_settings = SettingsService.update_user_settings(g.current_user, data)
return jsonify(updated_settings), 200
except Exception as e:
return jsonify({'error': str(e)}), 400
return None

@settings_bp.route('/api/settings/reset/<string:username>', methods=['DELETE'])
@settings_bp.route('/api/settings/reset', methods=['DELETE'])
@token_required
def reset_settings(username):
def reset_settings():
"""
Endpoint to remove user addiction settings.
"""
try:
success = SettingsService.reset_user_settings(username)
success = SettingsService.reset_user_settings(g.current_user)
if success:
return jsonify({'message': 'Ustawienia zostały zresetowane'}), 200
else:
Expand Down
2 changes: 1 addition & 1 deletion backend/app/services/settings_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
class SettingsService:

@staticmethod
def _get_user_settings(username):
def get_user_settings(username):
try:
user = User.query.filter_by(name=username).first()
if not user:
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/api/sendRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ export function fetchHabits() {
return apiGet<HabitOption[]>(`${API_BASE_URL}/api/addictions`)
}

export function fetchSettingsState(username: string){
return apiGet<UserSettings>(`${API_BASE_URL}/api/settings/${username}`)
export function fetchSettingsState(){
return apiFetch<UserSettings>(`${API_BASE_URL}/api/settings`)
}

export async function setHabit<TBody, TResponse>(body: TBody): Promise<TResponse> {
Expand Down
14 changes: 4 additions & 10 deletions frontend/src/stores/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,10 @@ export async function fetchSettingsFromAPI() {
const token = localStorage.getItem('token')
if (token === null) return;

const user_name = parseJwt(token).username;
username.value = user_name;
username.value = parseJwt(token).username;

// 2. Fetch user-specific settings
const data = await fetchSettingsState(user_name)
const data = await fetchSettingsState()
if (data) {
habitName.value = data.habitName
habitCost.value = data.habitCost
Expand All @@ -48,8 +47,7 @@ export async function fetchSettingsFromAPI() {
export async function updateSettingsAPI(settings: UserSettings) {
try {
const oldUsername = username.value;

const res = await fetch(`${API_BASE_URL}/api/settings/${oldUsername}`, {
const res = await fetch(`${API_BASE_URL}/api/settings`, {
method: 'PATCH',
headers: {
'Authorization': `Bearer ${localStorage.getItem('token') as string}`,
Expand All @@ -76,11 +74,7 @@ export async function updateSettingsAPI(settings: UserSettings) {

export async function resetSettingsAPI() {
try {
const token = localStorage.getItem('token')
if (token === null) return;

const user_name = parseJwt(token).username;
const res = await fetch(`${API_BASE_URL}/api/settings/reset/${user_name}`, {
const res = await fetch(`${API_BASE_URL}/api/settings/reset`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${localStorage.getItem('token') as string}`,
Expand Down
Loading