Skip to content

Commit

Permalink
Add discord login logic
Browse files Browse the repository at this point in the history
  • Loading branch information
violet-dev committed Sep 8, 2024
1 parent 9b8b708 commit 423a31c
Show file tree
Hide file tree
Showing 7 changed files with 79 additions and 1 deletion.
20 changes: 20 additions & 0 deletions violet-server/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { Request, Response } from 'express';
import { ResLoginUser } from './dtos/res-login-user.dto';
import { plainToClass } from 'class-transformer';
import { HmacAuthGuard } from './guards/hmac.guard';
import { DiscordAuthGuard } from './guards/discord.guard';

@ApiTags('auth')
@Controller('auth')
Expand Down Expand Up @@ -104,4 +105,23 @@ export class AuthController {
res.clearCookie('refresh-expires');
res.send();
}

@Get('discord')
@Post('discord')
@UseGuards(DiscordAuthGuard)
@ApiOperation({ summary: 'Login From Discord' })
logInDiscord() {
return { ok: true };
}

@Get('discord/redirect')
@UseGuards(DiscordAuthGuard)
@UseGuards(AccessTokenGuard)
@ApiOperation({ summary: 'Redirect discord oauth2' })
redirect(
@CurrentUser('userAppId') userAppId: string,
@CurrentUser('discordId') discordId: string,
) {
return { userAppId: userAppId, discordId: discordId };
}
}
2 changes: 2 additions & 0 deletions violet-server/src/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { AccessTokenStrategy } from './jwt/access-token.strategy';
import { RefreshTokenStrategy } from './jwt/refresh-token.strategy';
import { UserModule } from 'src/user/user.module';
import { JwtModule } from '@nestjs/jwt';
import { DiscordStrategy } from './discord/discord.strategy';

@Module({
imports: [JwtModule.register({}), UserModule],
Expand All @@ -14,6 +15,7 @@ import { JwtModule } from '@nestjs/jwt';
UserRepository,
AccessTokenStrategy,
RefreshTokenStrategy,
DiscordStrategy,
],
controllers: [AuthController],
})
Expand Down
28 changes: 28 additions & 0 deletions violet-server/src/auth/discord/discord.strategy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { Profile, Strategy } from 'passport-discord';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';

@Injectable()
export class DiscordStrategy extends PassportStrategy(Strategy, 'discord') {
constructor(private readonly configService: ConfigService) {
super({
clientID: configService.get<string>('DISCORD_CLIENT_ID'),
clientSecret: configService.get<string>('DISCORD_CLIENT_SECRET'),
callbackURL: 'http://localhost:3000/api/v2/auth/discord/redirect',
scope: ['identify'],
});
}

async validate(accessToken: string, refreshToken: string, profile: Profile) {
try {
const { id: discordId, avatar } = profile;
return {
discordId: discordId,
avatar: avatar,
};
} catch (error) {
throw new UnauthorizedException(error);
}
}
}
26 changes: 26 additions & 0 deletions violet-server/src/auth/guards/discord.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import {
ExecutionContext,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class DiscordAuthGuard extends AuthGuard('discord') {
constructor() {
super({
property: 'discord',
});
}

async canActivate(context: ExecutionContext) {
return (await super.canActivate(context)) as boolean;
}

handleRequest(err: any, user: any) {
if (err || !user) {
throw err || new UnauthorizedException('Retry login');
}
return user;
}
}
1 change: 0 additions & 1 deletion violet-server/src/auth/jwt/access-token.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ export class AccessTokenStrategy extends PassportStrategy(

async validate(req: Request, payload: JwtPayload) {
try {
console.log('validate');
const user = await this.userRepository.findOneBy({
userAppId: payload.userAppId,
});
Expand Down
1 change: 1 addition & 0 deletions violet-server/src/auth/jwt/jwt.payload.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export class JwtPayload {
userAppId: string;
discordId?: string;
id: string;
refreshToken?: string;
}
2 changes: 2 additions & 0 deletions violet-server/src/common/decorators/current-user.decorator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ export const CurrentUser = createParamDecorator(
(data: keyof JwtPayload | undefined, ctx: ExecutionContext) => {
const request = ctx.switchToHttp().getRequest();

request.user = { ...request.user, ...request.discord };

const { refreshToken, ...responUser } = request.user;

if (!data) return responUser;
Expand Down

0 comments on commit 423a31c

Please sign in to comment.