diff --git a/Backend/backend.py b/Backend/backend.py index b9888d4..4c6ae1c 100644 --- a/Backend/backend.py +++ b/Backend/backend.py @@ -1,11 +1,13 @@ import os from flask import Flask, request, jsonify +from flask_jwt_extended import JWTManager, \ + create_access_token, jwt_required, get_jwt_identity + import requests from flask_cors import CORS, cross_origin from mongoengine import connect, Document, StringField, DoesNotExist -from werkzeug.security import generate_password_hash -from werkzeug.security import check_password_hash +from werkzeug.security import generate_password_hash, check_password_hash import secrets # For generating a session key from datetime import datetime @@ -18,6 +20,9 @@ cors = CORS(app) app.config["CORS_HEADERS"] = "Content-Type" +app.config['JWT_SECRET_KEY'] = "CHANGE_TO_SECURE_KEY" +jwt = JWTManager(app) + DB_ACCESS_URL = ( # This is where db_access.py is running. "http://127.0.0.1:5001" ) @@ -86,7 +91,8 @@ def login(): if check_password_hash(user.encrypted_password, data["password"]): # Generate session key/token # This is just a placeholder for an actual session key/token - session_key = secrets.token_hex(16) + # session_key = secrets.token_hex(16) + access_token = create_access_token(identity=str(user.username)) # You would store this session key in a session store or database # with a reference to the user and a valid time period @@ -95,7 +101,7 @@ def login(): jsonify( { "message": "Logged in successfully!", - "session_key": session_key, + "access_token": access_token, } ), 200, @@ -126,6 +132,7 @@ def login(): ) except Exception as e: # Catch any other errors + print(f"Error during login: {str(e)}") return jsonify({"message": str(e)}), 500 diff --git a/Frontend/src/pages/auth.js b/Frontend/src/pages/auth.js new file mode 100644 index 0000000..6554214 --- /dev/null +++ b/Frontend/src/pages/auth.js @@ -0,0 +1,21 @@ +// auth.js (utility file) + +// Import the required libraries +import jwt from 'jsonwebtoken'; + +// Secret key used to sign the JWT tokens (should match the key used in your backend) +const JWT_SECRET = 'CHANGE_TO_SECURE_KEY'; + +// Function to check if the user is authenticated based on the JWT token +export function isAuthenticated(token) { + try { + // Verify and decode the JWT token + const decodedToken = jwt.verify(token, JWT_SECRET); + + // If the verification is successful, the user is authenticated + return true; + } catch (error) { + // If there's an error, such as an expired or invalid token, the user is not authenticated + return false; + } +} \ No newline at end of file diff --git a/Frontend/src/pages/login.js b/Frontend/src/pages/login.js index a1ba731..a11f165 100644 --- a/Frontend/src/pages/login.js +++ b/Frontend/src/pages/login.js @@ -5,6 +5,7 @@ import axios from "axios"; import "tailwindcss/tailwind.css"; // Import Tailwind CSS import { useRouter } from "next/router"; import Link from "next/link"; +import Cookies from "js-cookie"; const Login = () => { const router = useRouter(); @@ -35,6 +36,9 @@ const Login = () => { formData ); console.log("response", response); + + // Store the token in cookie + Cookies.set("token", response.data.access_token, { expires: 7, path: "/" }); router.push("/portfolio"); return response; } catch (error) { diff --git a/Frontend/src/pages/portfolio.js b/Frontend/src/pages/portfolio.js index 8003f28..5fd9c1c 100644 --- a/Frontend/src/pages/portfolio.js +++ b/Frontend/src/pages/portfolio.js @@ -1,6 +1,5 @@ -// src/pages/portfolio.js - import Link from "next/link"; +import { isAuthenticated } from "./auth"; // Make sure to use the correct path export default function Portfolio() { return ( @@ -20,3 +19,23 @@ export default function Portfolio() { ); } + +export async function getServerSideProps(context) { + const { req } = context; + const token = req.cookies["token"]; // Replace "your_cookie_name" with your actual cookie name + + if (!isAuthenticated(token)) { + // If the user is not authenticated, redirect them to the login page + return { + redirect: { + destination: "/login", + permanent: false, + }, + }; + } + + // If the user is authenticated, render the Portfolio page + return { + props: {}, // Will be passed to the page component as props + }; +}