Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Auth #11

Merged
merged 4 commits into from
May 16, 2024
Merged

Auth #11

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion backend-nest/src/api/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export class AuthService {
if (user?.password !== pass) {
throw new UnauthorizedException('Invalid credentials');
}
const payload = { sub: user.id, email: user.email };
const payload = { sub: user.id, email: user.email, userId: user.id };
return {
access_token: await this.jwtService.signAsync(payload),
};
Expand Down
12 changes: 11 additions & 1 deletion backend-nest/src/api/classgroups/classgroups.controller.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,18 @@
import { Body, Controller, Delete, Get, Param, Post } from '@nestjs/common';
import {
Body,
Controller,
Delete,
Get,
Param,
Post,
UseGuards,
} from '@nestjs/common';
import { ClassgroupsService } from './classgroups.service';
import { CreateClassgroupDto } from './dto/create-classgroup.dto';
import { AuthGuard } from '../auth/auth.guard';

@Controller('api/classgroups')
@UseGuards(AuthGuard)
export class ClassgroupsController {
constructor(private readonly classgroupsService: ClassgroupsService) {}

Expand Down
6 changes: 3 additions & 3 deletions backend-nest/src/api/classgroups/classgroups.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export class ClassgroupsService {
throw new NotFoundException('Classgroup not found');
}
return this.prisma.classgroup.findUnique({
where: { id },
where: { id: id },
});
}

Expand All @@ -49,7 +49,7 @@ export class ClassgroupsService {
throw new NotFoundException('Classgroup not found');
}
return this.prisma.classgroup.findFirst({
where: { file },
where: { file: file },
});
}

Expand All @@ -58,7 +58,7 @@ export class ClassgroupsService {
throw new Error('The class does not exist');
}
return this.prisma.classgroup.delete({
where: { id },
where: { id: id },
});
}

Expand Down
37 changes: 22 additions & 15 deletions backend-nest/src/api/persist/persist.service.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,37 @@
import { Injectable } from '@nestjs/common';
import { ApiService } from '../api.service';
import { ClassgroupsService } from '../classgroups/classgroups.service';
import { TimetableService } from '../timetable/timetable.service';
import { Cron } from '@nestjs/schedule';
import { AxiosResponse } from 'axios';
import {Injectable, OnModuleInit} from '@nestjs/common';
import {ApiService} from '../api.service';
import {ClassgroupsService} from '../classgroups/classgroups.service';
import {TimetableService} from '../timetable/timetable.service';
import {Cron} from '@nestjs/schedule';
import {AxiosResponse} from 'axios';
import * as console from 'node:console';

@Injectable()
export class PersistService {
export class PersistService implements OnModuleInit {
constructor(
private readonly apiService: ApiService,
private readonly classGroupService: ClassgroupsService,
private readonly timetableService: TimetableService,
) {}

async onModuleInit() {
this.persistClasses();
setTimeout(() => {
this.persistEvents();
}, 120000);
}

/**
* Cron job to persist classes every 5 minutes.
* Cron job to persist classes every 3 hours.
*/
@Cron('* * * * *')
@Cron('0 */3 * * *')
persistClasses() {
this.apiService.getClasses().subscribe((response) => {
response.data.forEach((item) => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { id, ...data } = item; // ignore id from response
const {id, ...data} = item;
this.classGroupService
.upsert({
where: { file: data.file }, // use a unique field to identify the record
where: {file: data.file},
create: data, // data to create if the record does not exist
update: data, // data to update if the record exists
})
Expand All @@ -33,9 +40,9 @@ export class PersistService {
});
}
/**
* Cron job to persist events every 10 seconds.
* Cron job to persist events every 1 hour.
*/
@Cron('* * * * *')
@Cron('0 */1 * * *')
persistEvents() {
this.classGroupService.findAll().then((classGroups) => {
classGroups.forEach((classGroup: { name: string; id: any }) => {
Expand Down Expand Up @@ -122,7 +129,7 @@ export class PersistService {
endAt: event.horaire.endAt,
classGroupId: classGroup.id,
};
this.timetableService.upsert(data);
this.timetableService.upsert(data).then((r) => console.log(r));
},
);
}
Expand Down
1 change: 1 addition & 0 deletions backend-nest/src/api/timetable/timetable.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { TimetableService } from './timetable.service';
* Controller for handling timetable related requests.
*/
@Controller('api/timetable')
@UseGuards(AuthGuard)
export class TimetableController {
/**
* @param {TimetableService} TimeTableService - The timetable service.
Expand Down
3 changes: 3 additions & 0 deletions backend-nest/src/api/users/users.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,15 @@ import {
Param,
Patch,
Post,
UseGuards,
} from '@nestjs/common';
import { UsersService } from './users.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { AuthGuard } from '../auth/auth.guard';

@Controller('api/users')
@UseGuards(AuthGuard)
export class UsersController {
constructor(private readonly usersService: UsersService) {}

Expand Down
1 change: 1 addition & 0 deletions frontend-react/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
SESSION_SECRET=97b98665ea4d4672f793b70fed1c71fc23dff48e92fca2137254f9acb259c280
8 changes: 8 additions & 0 deletions frontend-react/src/app/actions/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { deleteSession } from '@/app/lib/session'
import {redirect} from "next/navigation";

export async function logout() {
deleteSession()
redirect('/login')
}

6 changes: 5 additions & 1 deletion frontend-react/src/app/api/apiService.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// src/app/api/apiService.ts
import {API_BASE_URL} from './apiConfig';
import {verifySession} from "@/app/lib/dal";

export interface ApiResponse {
ok: boolean;
Expand All @@ -8,11 +9,14 @@ export interface ApiResponse {

}

export async function apiRequest(endpoint: string, method: string, body?: any) {
export async function apiRequest(endpoint: string, method: string, body?: any): Promise<ApiResponse> {
const session = await verifySession()
const bearer = session.session
const response = await fetch(`${API_BASE_URL}/${endpoint}`, {
method,
headers: {
'Content-Type': 'application/json',
Authorization: bearer ? `Bearer ${bearer}` : '',
},
body: body ? JSON.stringify(body) : null,
});
Expand Down
3 changes: 2 additions & 1 deletion frontend-react/src/app/api/services/classgroupService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ export async function getClassGroups() {
}
}

export async function getClassGroupById(id: number): Promise<Classgroup>{
export async function getClassGroupById(id: number | undefined): Promise<Classgroup>{
console.log(id);

try {
let response = await apiRequest(`classgroups/${id}`, 'GET');
return response.data;
Expand Down
32 changes: 0 additions & 32 deletions frontend-react/src/app/auth/useCurrentUser.ts

This file was deleted.

35 changes: 35 additions & 0 deletions frontend-react/src/app/lib/dal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"use server";

import {cookies} from 'next/headers'
import {decrypt} from '@/app/lib/session'
import {redirect} from "next/navigation";
import {cache} from 'react';
import {apiRequest} from "@/app/api/apiService";

export const verifySession = cache(async () => {

const cookie = cookies().get('session')?.value
const session = await decrypt(cookie)

if (!session?.userId) {

redirect('/login')
}

return { isAuth: true, userId: session.userId, session: cookie }
})

export const getUser = cache(async () => {
const session = await verifySession()
if (!session) return null

try {
const data = await apiRequest(`users/${session.userId}`, 'GET')
console.log(data.data)
return data.data

} catch (error) {
console.log('Failed to fetch user')
return null
}
})
34 changes: 22 additions & 12 deletions frontend-react/src/app/lib/session.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,12 @@
import 'server-only'
import { SignJWT, jwtVerify } from 'jose'
import { SessionPayload } from '@/app/lib/definitions'
"use server";

import {jwtVerify} from 'jose'
import {cookies} from 'next/headers'


const secretKey = process.env.SESSION_SECRET
const encodedKey = new TextEncoder().encode(secretKey)

export async function encrypt(payload: SessionPayload) {
return new SignJWT(payload)
.setProtectedHeader({ alg: 'HS256' })
.setIssuedAt()
.setExpirationTime('7d')
.sign(encodedKey)
}

export async function decrypt(session: string | undefined = '') {
try {
const { payload } = await jwtVerify(session, encodedKey, {
Expand All @@ -22,4 +16,20 @@ export async function decrypt(session: string | undefined = '') {
} catch (error) {
console.log('Failed to verify session')
}
}
}

export async function createSession(jwt: string) {
const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
cookies().set('session', jwt, {
httpOnly: true,
secure: true,
expires: expiresAt,
sameSite: 'lax',
path: '/',
})
}

export async function deleteSession() {
cookies().delete('session')
}

3 changes: 2 additions & 1 deletion frontend-react/src/app/login/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import LoginForm from './form/LoginForm';
import {Credentials, InvalidCredentialsError, login} from './services/loginService';
import Toast from '../../app/components/toasts';
import {useRouter} from 'next/navigation';
import {createSession} from "@/app/lib/session";

const LoginPage = () => {
const router = useRouter();
Expand All @@ -19,7 +20,7 @@ const LoginPage = () => {
try {
const token = await login(credentials);

document.cookie = `jwt=${token}; path=/`;
await createSession(token);


setToastMessage('Connexion réussie !');
Expand Down
39 changes: 39 additions & 0 deletions frontend-react/src/app/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { NextRequest, NextResponse } from 'next/server'
import { decrypt } from '@/app/lib/session'
import { cookies } from 'next/headers'

// 1. Specify protected and public routes
const protectedRoutes = ['/timetable', '/users']
const publicRoutes = ['/login', '/register', '/']

export default async function middleware(req: NextRequest) {
// 2. Check if the current route is protected or public
const path = req.nextUrl.pathname
const isProtectedRoute = protectedRoutes.includes(path)
const isPublicRoute = publicRoutes.includes(path)

// 3. Decrypt the session from the cookie
const cookie = cookies().get('session')?.value
const session = await decrypt(cookie)

// 5. Redirect to /login if the user is not authenticated
if (isProtectedRoute && !session?.userId) {
return NextResponse.redirect(new URL('/login', req.nextUrl))
}

// 6. Redirect to /dashboard if the user is authenticated
if (
isPublicRoute &&
session?.userId &&
!req.nextUrl.pathname.startsWith('/timetable')
) {
return NextResponse.redirect(new URL('/timetable', req.nextUrl))
}

return NextResponse.next()
}

// Routes Middleware should not run on
export const config = {
matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)'],
}
Loading
Loading