Skip to content

Commit

Permalink
Merge pull request #64 from grant-baer/protect-pages
Browse files Browse the repository at this point in the history
protected pages and passed cookie when creating img
  • Loading branch information
caseyavila authored Dec 7, 2023
2 parents 6b8ae19 + 0d7c224 commit 0ba6bb2
Show file tree
Hide file tree
Showing 6 changed files with 126 additions and 12 deletions.
22 changes: 22 additions & 0 deletions Backend/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,28 @@ def register():
return jsonify({"message": "Failed to create user!!"}), 500


@app.route("/api/verify_user", methods=["GET"])
@jwt_required()
def verify_user():
try:
# Retrieve the user by username
user = get_jwt_identity()
temp = User.objects.get(pk=user).username
return jsonify({'authenticated': True}), 200

except DoesNotExist:
# If the user is not found
return jsonify({"error": "User not found"}), 404
except jwt.ExpiredSignatureError:
# Token has expired
return jsonify({'authenticated': False}), 200
except jwt.InvalidTokenError:
# Invalid token
return jsonify({'authenticated': False}), 200
except Exception as e:
# Handle any other exceptions
return jsonify({"error": str(e)}), 500

if __name__ == "__main__":
db_connect()
try:
Expand Down
22 changes: 11 additions & 11 deletions Frontend/src/pages/auth.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
// auth.js (utility file)

// Import the required libraries
import jwt from "jsonwebtoken";
import axios from 'axios';

// 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) {
// Function to check if the user is authenticated based on the backend verification
export async function isAuthenticated(token) {
try {
// Verify and decode the JWT token
const decodedToken = jwt.verify(token, JWT_SECRET);
// make axios get request sending cookie.
const response = await axios.get('http://localhost:5000/api/verify_user', {
headers: {
Authorization: `Bearer ${token}`, // Send the JWT token in the Authorization header
},
});

// If the verification is successful, the user is authenticated
return true;
return response.data.authenticated;
} catch (error) {
// If there's an error, such as an expired or invalid token, the user is not authenticated
// console.error('Error during user verification:', error);
return false;
}
}
28 changes: 28 additions & 0 deletions Frontend/src/pages/create.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import React, { useState } from "react";
import axios from "axios";
import Image from "next/image";
import Cookie from "js-cookie";
import { isAuthenticated } from "./auth";


export default function Create() {
const [text, setText] = useState("");
Expand All @@ -19,6 +21,11 @@ export default function Create() {
await axios.post(
"http://localhost:5000/generate_image",
{ prompt: text },
{
headers: {
"Authorization": `Bearer ${Cookie.get("token")}`
}
},
).then(response => {
if (response.data.output) {
setUrl(response.data.output);
Expand Down Expand Up @@ -114,3 +121,24 @@ export default function Create() {
</div>
);
}


export async function getServerSideProps(context) {
const { req } = context;
const token = req.cookies["token"];

if (!await 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 Create page
return {
props: {}, // Will be passed to the page component as props
};
}
22 changes: 22 additions & 0 deletions Frontend/src/pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import Link from "next/link";
import Image from "next/image";
import { isAuthenticated } from "./auth";


export default function InitialLanding() {
return (
Expand Down Expand Up @@ -32,3 +34,23 @@ export default function InitialLanding() {
</div>
);
}

export async function getServerSideProps(context) {
const { req } = context;
const token = req.cookies["token"]; // Replace "your_cookie_name" with your actual cookie name

if (await isAuthenticated(token)) {
// If the user is authenticated, redirect them to the Create page
return {
redirect: {
destination: "/create",
permanent: false,
},
};
}

// If the user is authenticated, render the Index page
return {
props: {}, // Will be passed to the page component as props
};
}
22 changes: 21 additions & 1 deletion Frontend/src/pages/portfolio.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import Link from "next/link";
import { isAuthenticated } from "./auth"; // Make sure to use the correct path
import { isAuthenticated } from "./auth";
import Cookie from "js-cookie";
import React, { useEffect, useState } from "react";
import Image from "next/image";
Expand Down Expand Up @@ -42,3 +42,23 @@ export default function Portfolio() {
</div>
);
}

export async function getServerSideProps(context) {
const { req } = context;
const token = req.cookies["token"];

if (!await 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
};
}
22 changes: 22 additions & 0 deletions Frontend/src/pages/vote.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// src/pages/vote.js
import React, { useState } from 'react';
import Image from 'next/image';
import { isAuthenticated } from "./auth";

import styles from './vote.module.css';

Expand Down Expand Up @@ -46,6 +47,27 @@ export default function Vote() {
}


export async function getServerSideProps(context) {
const { req } = context;
const token = req.cookies["token"];

if (!await 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 Vote page
return {
props: {}, // Will be passed to the page component as props
};
}


// import Image from "next/image";
// import { useState, useEffect } from "react";
// import eloRating from "elo-rating";
Expand Down

0 comments on commit 0ba6bb2

Please sign in to comment.