-
Notifications
You must be signed in to change notification settings - Fork 0
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
Feat/12 auth #13
Changes from 3 commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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 |
This file was deleted.
This file was deleted.
This file was deleted.
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; | ||
} | ||
} |
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 {} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
import { AuthSchProfile } 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.lastName} ${userProfile.firstName}`, //this is kinda cring... | ||
nickName: userProfile.firstName, | ||
email: userProfile.email, | ||
isSchResident: true, | ||
//TODO: Find a solution for only dorm residents. The userProfile.bmeStatus is undefined. Is it an admin enabled info? | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. And this seems to not work here. Until we find a solution this seems useful for development purposes There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. you need to add the BME_STATUS scope in the constructor to access that field. Still, that won't help with dorm residency. |
||
}, | ||
}); | ||
} | ||
|
||
login(user: User): string { | ||
return this.jwtService.sign(user, { | ||
secret: process.env.JWT_SECRET, | ||
expiresIn: '7 days', | ||
}); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
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.LAST_NAME, AuthSchScope.EMAIL], | ||
}); | ||
} | ||
|
||
async validate(userProfile: AuthSchProfile): Promise<User> { | ||
return await this.authService.findOrCreateUser(userProfile); | ||
} | ||
} |
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); |
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; | ||
} | ||
} |
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); | ||
} | ||
} |
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, 'http://localhost:3000'], | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. maybe only put localhost here if we're not in production? |
||
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(); |
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) {} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
import { Module } from '@nestjs/common'; | ||
|
||
import { UserController } from './user.controller'; | ||
import { UserService } from './user.service'; | ||
|
||
@Module({ | ||
controllers: [UserController], | ||
providers: [UserService], | ||
}) | ||
export class UserModule {} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
import { Injectable } from '@nestjs/common'; | ||
|
||
@Injectable() | ||
export class UserService {} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Im not sure, how this handles third names here...
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
the displayName scope and property from authSch is actually the full name. I thought it was the authsch username, but no. Might be worth renaming it in the package