Skip to content

Commit

Permalink
feat: added an additional layer of verification to check if the user …
Browse files Browse the repository at this point in the history
…token is still active
  • Loading branch information
Kauacnok committed Jul 3, 2024
1 parent 455f8f5 commit 3241568
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
36 changes: 36 additions & 0 deletions src/api/generics/verifyToken.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
'use server'

import { ITokenUserInitialValues } from "@/interfaces/Generics"
import { GetUserToken } from "@/utils/GetUserToken"

export async function verifyUserToken() {

try {
const userParse: ITokenUserInitialValues = GetUserToken()

const resp = await fetch(`${process.env.BACKEND_DOMAIN}/verify-token`, {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: "Bearer " + userParse.accessToken,
}
})
.then(async (value) => {

if (value.status != 200) {
return false
}

return true
})
.catch((error) => {
return false
})

return resp
} catch(err) {
return false
}

}
9 changes: 8 additions & 1 deletion src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ import { parseJWT } from "./utils/ParseJWT";
import { ITokenUserValues } from "./interfaces/Generics";
import { secondRoutes, actionRoutes } from "@/api/routes"
import { ActionRoutes, SecondRoutes } from "./interfaces/IRoutes";
import { verifyUserToken } from "./api/generics/verifyToken";

export function middleware(request: NextRequest) {
export async function middleware(request: NextRequest) {
const token = request.cookies.get('user')?.value

let validRoute = false
Expand All @@ -14,6 +15,12 @@ export function middleware(request: NextRequest) {
return NextResponse.redirect(`${process.env.FRONTEND_DOMAIN}/login`)
}

const isValidToken = await verifyUserToken()

if (!isValidToken) {
return NextResponse.redirect(`${process.env.FRONTEND_DOMAIN}/login`)
}

const tokenUserValues: ITokenUserValues | null = parseJWT(token)

if (tokenUserValues == null) {
Expand Down

0 comments on commit 3241568

Please sign in to comment.