feat: google sso auth added

This commit is contained in:
Balu Babu
2023-01-13 00:52:29 +05:30
parent 6f4c5d7195
commit f4df8873be
8 changed files with 181 additions and 54 deletions

View File

@@ -19,6 +19,7 @@ import { RTJwtAuthGuard } from './guards/rt-jwt-auth.guard';
import { GqlUser } from 'src/decorators/gql-user.decorator';
import { AuthUser } from 'src/types/AuthUser';
import { RTCookie } from 'src/decorators/rt-cookie.decorator';
import { AuthGuard } from '@nestjs/passport';
@Controller('auth')
export class AuthController {
@@ -52,4 +53,16 @@ export class AuthController {
if (E.isLeft(newTokenPair)) throwHTTPErr(newTokenPair.left);
authCookieHandler(res, newTokenPair.right, false);
}
@Get('google')
@UseGuards(AuthGuard('google'))
async googleAuth(@Request() req) {}
@Get('google/callback')
@UseGuards(AuthGuard('google'))
async googleAuthRedirect(@Request() req, @Res() res) {
const authTokens = await this.authService.generateAuthTokens(req.user.id);
if (E.isLeft(authTokens)) throwHTTPErr(authTokens.left);
authCookieHandler(res, authTokens.right, true);
}
}

View File

@@ -8,6 +8,7 @@ import { PassportModule } from '@nestjs/passport';
import { JwtModule } from '@nestjs/jwt/dist';
import { JwtStrategy } from './strategies/jwt.strategy';
import { RTJwtStrategy } from './strategies/rt-jwt.strategy';
import { GoogleStrategy } from './strategies/google.strategy';
@Module({
imports: [
@@ -19,7 +20,7 @@ import { RTJwtStrategy } from './strategies/rt-jwt.strategy';
secret: process.env.JWT_SECRET,
}),
],
providers: [AuthService, JwtStrategy, RTJwtStrategy],
providers: [AuthService, JwtStrategy, RTJwtStrategy, GoogleStrategy],
controllers: [AuthController],
})
export class AuthModule {}

View File

@@ -0,0 +1,35 @@
import { Strategy, VerifyCallback } from 'passport-google-oauth20';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { UserService } from 'src/user/user.service';
import * as O from 'fp-ts/Option';
@Injectable()
export class GoogleStrategy extends PassportStrategy(Strategy) {
constructor(private usersService: UserService) {
super({
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: process.env.GOOGLE_CALLBACK_URL,
scope: process.env.GOOGLE_SCOPE.split(','),
});
}
async validate(accessToken, refreshToken, profile, done: VerifyCallback) {
const user = await this.usersService.findUserByEmail(
profile.emails[0].value,
);
console.log('user log', user);
if (O.isNone(user)) {
const createdUser = await this.usersService.createUserSSO(
accessToken,
refreshToken,
profile,
);
return createdUser;
}
return user.value;
}
}