Added function for retrieve user by cookie

This commit is contained in:
Sianida26 2024-01-22 11:30:00 +07:00
parent c27305dc0f
commit a5090d2cc3
7 changed files with 70 additions and 7 deletions

View File

@ -30,6 +30,7 @@
"react-dom": "^18.2.0",
"react-icons": "^5.0.1",
"sass": "^1.70.0",
"server-only": "^0.0.1",
"superjson": "^2.2.1",
"zod": "^3.22.4"
},

View File

@ -68,6 +68,9 @@ dependencies:
sass:
specifier: ^1.70.0
version: 1.70.0
server-only:
specifier: ^0.0.1
version: 0.0.1
superjson:
specifier: ^2.2.1
version: 2.2.1
@ -3084,6 +3087,10 @@ packages:
dependencies:
lru-cache: 6.0.0
/server-only@0.0.1:
resolution: {integrity: sha512-qepMx2JxAa5jjfzxG79yPPq+8BuFToHd1hm7kI+Z4zAq1ftQiP7HcxMhDDItrbtwVeLg/cY2JnKnrcFkmiswNA==}
dev: false
/set-blocking@2.0.0:
resolution: {integrity: sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==}
dev: false

View File

@ -1,5 +1,6 @@
module.exports = {
plugins: {
'tailwindcss/nesting': {},
tailwindcss: {},
autoprefixer: {},
'postcss-preset-mantine': {},

View File

@ -6,6 +6,8 @@ import logo from "@/assets/logos/logo.png"
import AppHeader from '../../components/AppHeader'
import AppNavbar from '../../components/AppNavbar'
import DashboardLayout from '@/components/DashboardLayout'
import getUser from '@/features/auth/actions/getUser'
import { redirect } from 'next/navigation'
interface Props {
children: React.ReactNode
@ -13,6 +15,12 @@ interface Props {
export default function Layout(props: Props) {
const user = getUser()
if (!user){
redirect("/login")
}
return (
<DashboardLayout>
{props.children}

View File

@ -4,6 +4,7 @@ export enum AuthErrorCode {
EMAIL_NOT_FOUND = "EMAIL_NOT_FOUND",
EMPTY_USER_HASH = "EMPTY_USER_HASH",
INVALID_CREDENTIALS = "INVALID_CREDENTIALS",
INVALID_JWT_TOKEN = "INVALID_JWT_TOKEN",
JWT_SECRET_EMPTY = "JWT_SECRET_NOT_EMPTY",
USER_ALREADY_EXISTS = "USER_ALREADY_EXISTS",
}

View File

@ -0,0 +1,22 @@
"use server"
import { cookies } from "next/headers"
import "server-only"
import { decodeJwtToken } from "../authUtils";
import prisma from "@/db";
export default async function getUser(){
const token = cookies().get('token');
if (!token) return null;
const decodedToken = decodeJwtToken(token.value) as {id: string, iat: number};
const user = await prisma.user.findFirst({
where: {
id: decodedToken.id
}
});
return user;
}

View File

@ -1,9 +1,9 @@
import prisma from "@/db";
import bcrypt from "bcrypt";
import jwt, { SignOptions, JwtPayload } from "jsonwebtoken";
import { User } from "@prisma/client";
import * as bcrypt from "bcrypt";
import prisma from "@/db";
import AuthError, { AuthErrorCode } from "./AuthError";
import authConfig from "@/config/auth";
import jwt from "jsonwebtoken"
import UserClaims from "./types/UserClaims";
/**
@ -27,9 +27,32 @@ export async function comparePassword(password: string, hash: string): Promise<b
return bcrypt.compare(password, hash);
}
export function createJwtToken(userclaims: UserClaims, options?: jwt.SignOptions){
/**
* Creates a JWT token based on user claims.
*
* @param userClaims - The user claims to encode in the JWT.
* @param options - Optional signing options.
* @returns The generated JWT token.
*/
export function createJwtToken(userClaims: UserClaims, options?: SignOptions): string {
const secret = process.env.JWT_SECRET;
if (!secret) throw new AuthError(AuthErrorCode.JWT_SECRET_EMPTY);
const token = jwt.sign(userclaims, secret, options);
return token;
}
return jwt.sign(userClaims, secret, options);
}
/**
* Decodes a JWT token and retrieves the payload.
*
* @param token - The JWT token to decode.
* @returns The decoded payload.
*/
export function decodeJwtToken(token: string): JwtPayload | string {
const secret = process.env.JWT_SECRET;
if (!secret) throw new AuthError(AuthErrorCode.JWT_SECRET_EMPTY);
try {
return jwt.verify(token, secret) as JwtPayload;
} catch (error) {
throw new AuthError(AuthErrorCode.INVALID_JWT_TOKEN);
}
}