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

Feat/12 auth #13

Merged
merged 5 commits into from
Jul 16, 2024
Merged
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
7 changes: 6 additions & 1 deletion apps/backend/.env.example
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
DATABASE_URL="postgresql://postgres:postgres@localhost:5432/mydb?schema=public"
DATABASE_URL="postgresql://postgres:postgres@localhost:5432/schbody?schema=public"
AUTHSCH_CLIENT_ID="16873903969434023692"
AUTHSCH_CLIENT_SECRET="5KhIlDHGhxzLx3FK7L81FJ5CQSuyJTLVrW0hZnbzv4jbdOHU255HuOtBgGZS38V3pHGd4SE78aq4Njze"
JWT_SECRET="this is a secret"
FRONTEND_URL="http://localhost:3000"
BACKEND_PORT=3300
5 changes: 5 additions & 0 deletions apps/backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,16 @@
"start:prod": "node dist/main"
},
"dependencies": {
"@kir-dev/passport-authsch": "^1.0.0",
"@nestjs/common": "^10.3.8",
"@nestjs/core": "^10.3.8",
"@nestjs/jwt": "^10.2.0",
"@nestjs/passport": "^10.0.3",
"@nestjs/platform-express": "^10.3.8",
"@prisma/client": "^5.13.0",
"nestjs-prisma": "^0.23.0",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
"reflect-metadata": "^0.2.2",
"rimraf": "^5.0.5",
"rxjs": "^7.8.1"
Expand Down
94 changes: 0 additions & 94 deletions apps/backend/prisma/migrations/20240712170207_/migration.sql

This file was deleted.

2 changes: 0 additions & 2 deletions apps/backend/prisma/migrations/20240712170556_/migration.sql

This file was deleted.

3 changes: 0 additions & 3 deletions apps/backend/prisma/migrations/migration_lock.toml

This file was deleted.

16 changes: 8 additions & 8 deletions apps/backend/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,14 @@ enum ApplicationStatus {
}

model User {
id Int @id @default(autoincrement())
authSchId String @unique
authSchId String @id
fullName String
nickName String
role Role @default(USER)
neptun String? @unique
email String?
isSchResident Boolean
isActiveVikStudent Boolean
roomNumber Int?
profileImage Bytes?
canHelpNoobs Boolean @default(false)
Expand All @@ -56,17 +56,17 @@ model ApplicationPeriod {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
ticketsAreValid Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId Int
author User @relation(fields: [authorId], references: [authSchId])
authorId String
applications Application[]

@@index([authorId])
}

model Application {
id Int @id @default(autoincrement())
user User @relation(fields: [userId], references: [id])
userId Int
user User @relation(fields: [userId], references: [authSchId])
userId String
applicationPeriod ApplicationPeriod @relation(fields: [applicationPeriodId], references: [id])
applicationPeriodId Int
status ApplicationStatus @default(SUBMITTED)
Expand All @@ -82,8 +82,8 @@ model Post {
content String
preview String
visible Boolean @default(true)
author User @relation(fields: [authorId], references: [id])
authorId Int
author User @relation(fields: [authorId], references: [authSchId])
authorId String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt

Expand Down
4 changes: 3 additions & 1 deletion apps/backend/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ import { PrismaModule } from 'nestjs-prisma';

import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AuthModule } from './auth/auth.module';
import { UserModule } from './user/user.module';

@Module({
imports: [PrismaModule.forRoot({ isGlobal: true })],
imports: [PrismaModule.forRoot({ isGlobal: true }), UserModule, AuthModule],
controllers: [AppController],
providers: [AppService],
})
Expand Down
40 changes: 40 additions & 0 deletions apps/backend/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { CurrentUser } from '@kir-dev/passport-authsch';
import { Controller, Get, Redirect, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { User } from '@prisma/client';

import { AuthService } from './auth.service';
@ApiTags('auth')
@Controller('auth')
export class AuthController {
constructor(private authService: AuthService) {}
/**
* Redirects to the authsch login page
*/
@UseGuards(AuthGuard('authsch'))
@Get('login')
login() {
// never called
}

/**
* Endpoint for authsch to call after login
* Redirects to the frontend with the jwt token
*/
@Get('callback')
@UseGuards(AuthGuard('authsch'))
@Redirect()
oauthRedirect(@CurrentUser() user: User) {
const jwt = this.authService.login(user);
return {
url: `${process.env.FRONTEND_URL}?jwt=${jwt}`,
};
}
@Get('me')
@UseGuards(AuthGuard('jwt'))
@ApiBearerAuth()
me(@CurrentUser() user: User): User {
return user;
}
}
15 changes: 15 additions & 0 deletions apps/backend/src/auth/auth.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';

import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { AuthSchStrategy } from './authsch.strategy';
import { JwtStrategy } from './jwt.strategy';

@Module({
controllers: [AuthController],
providers: [AuthService, AuthSchStrategy, JwtStrategy],
imports: [PassportModule, JwtModule],
})
export class AuthModule {}
36 changes: 36 additions & 0 deletions apps/backend/src/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { AuthSchProfile, BmeUnitScope } from '@kir-dev/passport-authsch';
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { User } from '@prisma/client';
import { PrismaService } from 'nestjs-prisma';

@Injectable()
export class AuthService {
constructor(
private prisma: PrismaService,
private jwtService: JwtService
) {}

async findOrCreateUser(userProfile: AuthSchProfile): Promise<User> {
const user = await this.prisma.user.findUnique({ where: { authSchId: userProfile.authSchId } });
if (user) return user;
return await this.prisma.user.create({
data: {
authSchId: userProfile.authSchId,
fullName: userProfile.displayName,
nickName: userProfile.firstName,
email: userProfile.email,
isSchResident: true,
//TODO: Find a solution for only dorm residents.
isActiveVikStudent: userProfile.bmeStatus.includes(BmeUnitScope.BME_VIK_ACTIVE),
},
});
}

login(user: User): string {
return this.jwtService.sign(user, {
secret: process.env.JWT_SECRET,
expiresIn: '7 days',
});
}
}
27 changes: 27 additions & 0 deletions apps/backend/src/auth/authsch.strategy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { AuthSchProfile, AuthSchScope, Strategy } from '@kir-dev/passport-authsch';
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { User } from '@prisma/client';

import { AuthService } from './auth.service';

@Injectable()
export class AuthSchStrategy extends PassportStrategy(Strategy) {
constructor(private authService: AuthService) {
super({
clientId: process.env.AUTHSCH_CLIENT_ID,
clientSecret: process.env.AUTHSCH_CLIENT_SECRET,
scopes: [
AuthSchScope.BASIC,
AuthSchScope.FIRST_NAME,
AuthSchScope.EMAIL,
AuthSchScope.BME_STATUS,
AuthSchScope.DISPLAY_NAME,
],
});
}

async validate(userProfile: AuthSchProfile): Promise<User> {
return await this.authService.findOrCreateUser(userProfile);
}
}
5 changes: 5 additions & 0 deletions apps/backend/src/auth/decorators/Roles.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { SetMetadata } from '@nestjs/common';
import { Role } from '@prisma/client';

export const ROLES_KEY = 'roles';
export const Roles = (...roles: Role[]) => SetMetadata(ROLES_KEY, roles);
19 changes: 19 additions & 0 deletions apps/backend/src/auth/jwt.strategy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { User } from '@prisma/client';
import { ExtractJwt, Strategy } from 'passport-jwt';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: process.env.JWT_SECRET,
});
}

validate(payload: User): User {
return payload;
}
}
22 changes: 22 additions & 0 deletions apps/backend/src/auth/roles.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Role } from '@prisma/client';

import { ROLES_KEY } from './decorators/Roles.decorator';

@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}

canActivate(context: ExecutionContext): boolean {
const requiredRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [
context.getHandler(),
context.getClass(),
]);
if (!requiredRoles) {
return true;
}
const { user } = context.switchToHttp().getRequest();
return requiredRoles.some((role) => user.role === role);
}
}
11 changes: 10 additions & 1 deletion apps/backend/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
import { NestFactory } from '@nestjs/core';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';

import { AppModule } from './app.module';

async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3001);
app.enableCors({
origin: [process.env.FRONTEND_URL],
methods: ['GET', 'POST', 'PATCH', 'DELETE', 'PUT'],
credentials: true,
});
const config = new DocumentBuilder().setTitle('SCHBody WEB').setVersion('1.0').addBearerAuth().build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document);
await app.listen(process.env.PORT || 3300);
}
bootstrap();
8 changes: 8 additions & 0 deletions apps/backend/src/user/user.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { Controller } from '@nestjs/common';

import { UserService } from './user.service';

@Controller('user')
export class UserController {
constructor(private readonly userService: UserService) {}
}
Loading