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

Adds auth provider to frontend #51

Merged
merged 17 commits into from
Sep 27, 2023
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
2 changes: 1 addition & 1 deletion .devcontainer/postCreateCommand.sh
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@ npm run prisma:generate
npx prisma migrate dev --name init

# Docker daemon setup
chown node:node /var/run/docker.sock
sudo chown node:node /var/run/docker.sock
2 changes: 1 addition & 1 deletion backend/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { LobbyModule } from './lobby/lobby.module';
}),
UsersModule,
PrismaModule,
// AuthModule,
AuthModule,
ChatModule,
GameModule,
FriendsModule,
Expand Down
1 change: 0 additions & 1 deletion backend/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ export class AuthController {
async logout(@Req() req: Request, @Res({ passthrough: true }) res: Response) {
try {
const user = req.user as User;
console.log(user);
await this.jwtAuthService.removeTokensFromCookie(res);
return await this.authService.logout(user, res);
} catch (error) {
Expand Down
2 changes: 1 addition & 1 deletion backend/src/auth/intra/intra.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export class IntraController {

await this.jwtAuthService.storeTokensInCookie(res, tokens);

res.redirect(`${this.configService.get('FRONTEND_URL')}/login/redirect`);
res.redirect(`${this.configService.get('FRONTEND_URL')}/auth/redirect`);
} catch (error) {
return error;
}
Expand Down
8 changes: 7 additions & 1 deletion backend/src/auth/jwt/jwt.controller.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
import { Controller, Get, Req, Res, UseGuards } from '@nestjs/common';
import { JwtAuthService } from './jwt.service';
import { Request, Response } from 'express';
import { RefreshTokenGuard } from './jwt.guard';
import { AccessTokenGuard, RefreshTokenGuard } from './jwt.guard';
import { User } from '@prisma/client';

@Controller('auth/jwt')
export class JwtAuthController {
constructor(private jwtAuthService: JwtAuthService) {}

@UseGuards(AccessTokenGuard)
@Get('validate')
async validateToken() {
return { msg: 'Valid token' };
}

@UseGuards(RefreshTokenGuard)
@Get('refresh')
async refreshToken(
Expand Down
8 changes: 4 additions & 4 deletions backend/src/auth/jwt/jwt.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ForbiddenException, Injectable } from '@nestjs/common';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { CookieOptions, Response } from 'express';
Expand Down Expand Up @@ -68,7 +68,7 @@ export class JwtAuthService {
const domain = this.configService.get('DOMAIN', 'localhost');
const cookieOptions = {
domain: domain,
httpOnly: true,
httpOnly: false,
sameSite: 'lax',
secure: domain !== 'localhost',
} as CookieOptions;
Expand Down Expand Up @@ -96,10 +96,10 @@ export class JwtAuthService {
async refreshJwt(login: string) {
const user = await this.usersService.findOne(login);
if (!user) {
throw new ForbiddenException('User not found');
throw new UnauthorizedException('User not found');
}
if (!user.refreshToken) {
throw new ForbiddenException('Session expired, please log in again.');
throw new UnauthorizedException('Session expired');
}
return await this.generateJwt(user);
}
Expand Down
15 changes: 10 additions & 5 deletions backend/src/auth/jwt/jwt.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { ExtractJwt } from 'passport-jwt';
import { Strategy } from 'passport-jwt';
import { UsersService } from 'src/users/users.service';
import { JwtPayload } from '../dto/jwt.dto';
import argon2 from 'argon2';

@Injectable()
export class JwtAuthStrategy extends PassportStrategy(Strategy, 'jwt') {
Expand All @@ -30,7 +31,7 @@ export class JwtAuthStrategy extends PassportStrategy(Strategy, 'jwt') {
async validate(payload: JwtPayload) {
const user = await this.userService.findOne(payload.sub);
if (!user) {
throw new UnauthorizedException('Please log in to continue');
throw new UnauthorizedException('User not found');
}
return user;
}
Expand Down Expand Up @@ -60,14 +61,18 @@ export class RefreshJwtStrategy extends PassportStrategy(
const refreshToken =
RefreshJwtStrategy.extractRefreshJwtFromBearer(req) ??
RefreshJwtStrategy.getRefreshTokenFromCookie(req);

if (!refreshToken) {
throw new UnauthorizedException('JWT refresh token not found');
throw new UnauthorizedException('Session expired');
}

const user = await this.usersService.findOne(payload.sub);
if (!user) {
throw new UnauthorizedException('Please log in to continue');
throw new UnauthorizedException('User not found');
}
const isValid = await argon2.verify(user.refreshToken, refreshToken, {
secret: Buffer.from(this.configService.get('HASH_PEPPER')),
});
if (!isValid) {
throw new UnauthorizedException('Session expired');
}
return user;
}
Expand Down
8 changes: 8 additions & 0 deletions backend/src/auth/mfa/mfa.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,18 @@ export class MultiFactorAuthController {
@Post('disable')
async disableMfa(
@Req() req: Request,
@Body() mfaPayload: MfaPayload,
@Res({ passthrough: true }) res: Response,
) {
const user = req.user as User;

const isCodeValid = await this.mfaService.isCodeValid(
user,
mfaPayload.code,
);
if (!isCodeValid) {
throw new UnauthorizedException('Invalid 2FA code');
}
try {
return await this.mfaService.disableMfa(user, res);
} catch (error) {
Expand Down
18 changes: 2 additions & 16 deletions backend/src/auth/mfa/mfa.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,63 +16,49 @@ export class MultiFactorAuthService {
) {}

async generateQRCode(user: User) {
console.log('generateQRCode');
console.log(user);
const login = user.login;
const secret = authenticator.generateSecret();
console.log('secret', secret);
const appName = this.configService.get('APP_NAME');
console.log('appName', appName);
const otpauthUrl = authenticator.keyuri(login, appName, secret);
console.log('otpauthUrl', otpauthUrl);
const updated_user = await this.usersService.update(login, {
await this.usersService.update(login, {
mfaSecret: secret,
});
console.log(updated_user);
return otpauthUrl;
}

async streamQRCode(res: Response, otpauthUrl: string) {
console.log('streamQRCode');
return toFileStream(res, otpauthUrl);
}

async isCodeValid(user: User, code: string): Promise<boolean> {
console.log('isCodeValid');
return authenticator.verify({
token: code,
secret: user.mfaSecret,
});
}

async disableMfa(user: User, res: Response) {
console.log('disableMfa');
const updated_user = await this.usersService.update(user.login, {
mfaEnabled: false,
mfaSecret: null,
});
const tokens = await this.jwtAuthService.generateJwt(updated_user, false);
await this.jwtAuthService.storeTokensInCookie(res, tokens);
console.log('post-disable tokens', tokens);
return tokens;
return { msg: '2FA disabled' };
}

async enableMfa(user: User, res: Response) {
console.log('enableMfa');
const updated_user = await this.usersService.update(user.login, {
mfaEnabled: true,
});
const tokens = await this.jwtAuthService.generateJwt(updated_user, true);
await this.jwtAuthService.storeTokensInCookie(res, tokens);
console.log('post-enable tokens', tokens);
return tokens;
}

async authenticate(user: User, res: Response) {
console.log('authenticate');
const tokens = await this.jwtAuthService.generateJwt(user, true);
await this.jwtAuthService.storeTokensInCookie(res, tokens);
console.log('post-authenticate tokens', tokens);
return tokens;
}
}
2 changes: 1 addition & 1 deletion backend/src/auth/mfa/mfa.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export class MultiFactorAuthStrategy extends PassportStrategy(Strategy, '2fa') {
async validate(payload: JwtPayload): Promise<User> {
const user = await this.usersService.findOne(payload.sub);
if (!user) {
throw new UnauthorizedException();
throw new UnauthorizedException('User not found');
}

if (!user.mfaEnabled) {
Expand Down
4 changes: 4 additions & 0 deletions backend/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ async function bootstrap() {
// Set up cookie parser
app.use(cookieParser());
app.useGlobalPipes(new ValidationPipe());
app.enableCors({
origin: process.env.FRONTEND_URL,
credentials: true,
});

await app.listen(3000);
}
Expand Down
51 changes: 47 additions & 4 deletions backend/src/users/users.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,28 +6,71 @@ import {
Param,
Patch,
Post,
UseGuards,
Req,
} from '@nestjs/common';
import { UsersService } from './users.service';
import { UpdateUserDto } from './dto/updateUser.dto';
import { CreateUserDto } from './dto/createUser.dto';
import { AccessTokenGuard } from 'src/auth/jwt/jwt.guard';
import { User } from '@prisma/client';
import { Request } from 'express';

@Controller('user*')
export class UsersController {
constructor(private service: UsersService) {}

@UseGuards(AccessTokenGuard)
@Get('me')
findMe(@Body() dto: any) {
return this.service.findMe(dto);
findMe(@Req() req: Request) {
try {
const user = req.user as User;
return this.service.findOne(user.login, {
login: true,
displayName: true,
email: true,
avatar: true,
status: true,
victory: true,
mfaEnabled: true,
createdAt: true,
updatedAt: true,
});
} catch (error) {
return error;
}
}

@Get()
findAll() {
return this.service.findAll();
return this.service.findAll({
select: {
login: true,
displayName: true,
email: true,
avatar: true,
status: true,
victory: true,
mfaEnabled: true,
createdAt: true,
updatedAt: true,
},
});
}

@Get(':login')
findOne(@Param('login') login: string) {
return this.service.findOne(login);
return this.service.findOne(login, {
login: true,
displayName: true,
email: true,
avatar: true,
status: true,
victory: true,
mfaEnabled: true,
createdAt: true,
updatedAt: true,
});
}

@Post()
Expand Down
33 changes: 21 additions & 12 deletions backend/src/users/users.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,34 @@ import { Injectable } from '@nestjs/common';
import { PrismaService } from 'src/prisma/prisma.service';
import { CreateUserDto } from './dto/createUser.dto';
import { UpdateUserDto } from './dto/updateUser.dto';
import { User } from '@prisma/client';

@Injectable()
export class UsersService {
constructor(private prisma: PrismaService) {}

async findAll() {
return await this.prisma.user.findMany();
async findAll(args: any = {}) {
return await this.prisma.user.findMany(args);
}

async findOne(login: string) {
return await this.prisma.user.findUnique({
where: {
login: login,
},
});
async findOne(login: string, select: any = null): Promise<User | null> {
let args = {} as any;
if (select != null) {
args = {
where: {
login: login,
},
select: select,
};
} else {
args = {
where: {
login: login,
},
};
}
const user: User = await this.prisma.user.findUnique(args);
return user;
}

async create(createUserDto: CreateUserDto) {
Expand Down Expand Up @@ -53,8 +66,4 @@ export class UsersService {
},
});
}

async findMe(dto: any) {
return 'null';
}
}
2 changes: 1 addition & 1 deletion frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
"dev": "next dev --port 9090",
"build": "next build",
"start": "next start",
"lint": "next lint"
"lint": "next lint",
"format": "prettier --write src"
},
"dependencies": {
"@headlessui/react": "^1.7.15",
Expand All @@ -19,12 +20,14 @@
"axios": "^1.4.0",
"eslint": "8.38.0",
"eslint-config-next": "13.3.0",
"jwt-decode": "^3.1.2",
"konva": "^9.2.0",
"next": "^13.4.6",
"nookies": "^2.5.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-hook-form": "^7.44.3",
"react-hot-toast": "^2.4.1",
"react-konva": "^18.2.9",
"react-popper": "^2.3.0",
"socket.io-client": "^4.6.2",
Expand All @@ -33,6 +36,7 @@
"devDependencies": {
"autoprefixer": "^10.4.14",
"postcss": "^8.4.24",
"prettier": "^2.8.8",
"tailwind-scrollbar": "^3.0.4",
"tailwindcss": "^3.3.2"
}
Expand Down
Loading
Loading