Skip to content

Commit

Permalink
Add jose library and update authentication middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
Arejula11 committed Apr 4, 2024
1 parent ec30464 commit d72d174
Show file tree
Hide file tree
Showing 7 changed files with 91 additions and 4 deletions.
9 changes: 9 additions & 0 deletions playbeat/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions playbeat/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"axios": "^1.6.8",
"clsx": "^2.1.0",
"framer-motion": "^11.0.5",
"jose": "^5.2.3",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"svelte": "^4.2.12",
Expand Down
2 changes: 2 additions & 0 deletions playbeat/src/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const PUBLIC_ROUTES = ["/", "/login", "/register"];
export const TOKEN = "token";
73 changes: 73 additions & 0 deletions playbeat/src/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { errors, jwtVerify } from "jose";
import { defineMiddleware } from "astro/middleware";
import { TOKEN, PUBLIC_ROUTES } from "./constants";

// The JWT secret
const secret = new TextEncoder().encode(import.meta.env.JWT_SECRET_KEY);

/**
* Verify if the client token is valid.
*/
const verifyAuth = async (token?: string) => {
if (!token) {
return {
status: "unauthorized",
msg: "Please pass a request token",
} as const;
}

try {
const jwtVerifyResult = await jwtVerify(token, secret);

return {
status: "authorized",
payload: jwtVerifyResult.payload,
msg: "successfully verified auth token",
} as const;
} catch (err) {
if (err instanceof errors.JOSEError) {
return { status: "error", msg: err.message } as const;
}

console.debug(err);
return { status: "error", msg: "could not validate auth token" } as const;
}
};

export const onRequest = defineMiddleware(async (context, next) => {
// Ignore auth validation for public routes
if (PUBLIC_ROUTES.includes(context.url.pathname)) {
// Respond as usual
return next();
}

// Get the token from cookies
const token = context.cookies.get(TOKEN)?.value;
// Verify the token
const validationResult = await verifyAuth(token);

console.log(validationResult);

// Handle the validation result
switch (validationResult.status) {
case "authorized":
// Respond as usual if the user is authorised
return next();

case "error":
case "unauthorized":
// If an API endpoint, return a JSON response
if (context.url.pathname.startsWith("/api/")) {
return new Response(JSON.stringify({ message: validationResult.msg }), {
status: 401,
});
}
// Otherwise, this is a standard page. Redirect to the root page for the user to login
else {
return Response.redirect(new URL("/", context.url));
}

default:
return Response.redirect(new URL("/", context.url));
}
});
3 changes: 2 additions & 1 deletion playbeat/src/pages/login.astro
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import Logo from '@/icons/Logo.astro'
import NormalLayout from '../layouts/NormalLayout.astro'
import LogoBlanco from '@/icons/LogoBlanco.astro'
import {TOKEN} from '@/constants.ts'
import { loginUser } from '@/utils/login.ts'
Expand Down Expand Up @@ -41,7 +42,7 @@ if (Astro.request.method ==="POST" ) {
const response = await loginUser({email: values.email, contrasegna: values.contrasegna});
if (response && response.status === 200) {
Astro.cookies.set("token", response.data);
Astro.cookies.set(TOKEN, response.data);
return Astro.redirect("/");
} else {
errors.peticion = "Error al registrar, intentelo de nuevo";
Expand Down
4 changes: 2 additions & 2 deletions playbeat/src/pages/logout.astro
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
import {TOKEN} from '@/constants.ts'
//Para usar astro.cookies.delete no pude usarse en una funcion, por lo tanto se puede solucionar con el siguiente codigo
Astro.cookies.delete('token');
Astro.cookies.delete(TOKEN);
return Astro.redirect('/login');
---
3 changes: 2 additions & 1 deletion playbeat/src/pages/register.astro
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
---
import NormalLayout from '../layouts/NormalLayout.astro'
import {registerUser} from '@/utils/register.ts'
import {TOKEN} from '@/constants.ts'
const errors = { username: "", email: "", password: "", peticion:"" };
const values = { username: "", email: "", password: "", password2:"" };
Expand Down Expand Up @@ -47,7 +48,7 @@ if (Astro.request.method === "POST") {
if (!hasErrors) {
const response = await registerUser({nombreUsuario: name, email, contrasegna: password});
if (response && response.status === 201) {
Astro.cookies.set("token", response.data);
Astro.cookies.set(TOKEN, response.data);
return Astro.redirect("/");
} else {
errors.peticion = "Error al registrar, intentelo de nuevo";
Expand Down

0 comments on commit d72d174

Please sign in to comment.