Skip to content

Commit

Permalink
Merge pull request #54 from grant-baer/login-with-jwt
Browse files Browse the repository at this point in the history
Login with jwt
  • Loading branch information
caseyavila authored Dec 4, 2023
2 parents 71d119e + 182bbeb commit d22e7d8
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 6 deletions.
15 changes: 11 additions & 4 deletions Backend/backend.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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"
)
Expand Down Expand Up @@ -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

Expand All @@ -95,7 +101,7 @@ def login():
jsonify(
{
"message": "Logged in successfully!",
"session_key": session_key,
"access_token": access_token,
}
),
200,
Expand Down Expand Up @@ -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


Expand Down
21 changes: 21 additions & 0 deletions Frontend/src/pages/auth.js
Original file line number Diff line number Diff line change
@@ -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;
}
}
4 changes: 4 additions & 0 deletions Frontend/src/pages/login.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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) {
Expand Down
23 changes: 21 additions & 2 deletions Frontend/src/pages/portfolio.js
Original file line number Diff line number Diff line change
@@ -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 (
Expand All @@ -20,3 +19,23 @@ export default function Portfolio() {
</div>
);
}

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
};
}

0 comments on commit d22e7d8

Please sign in to comment.