Skip to content
Permalink
Browse files

Users that already have an account can sign-in. Guards using roles(fo…

…nt-end)
  • Loading branch information...
elvis
elvis committed Oct 4, 2019
1 parent f4d6f7c commit e6405d8db718759e450f5d468f0d4955d231f744
@@ -0,0 +1,16 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceFolder}\\start:gauzy",
"preLaunchTask": "tsc: build - tsconfig.json",
"outFiles": ["${workspaceFolder}/dist/out-tsc/**/*.js"]
}
]
}
@@ -1,14 +1,14 @@
import {
Controller,
Post,
HttpStatus,
HttpCode,
Body,
Get,
Res,
Req,
Query,
UseGuards
Controller,
Post,
HttpStatus,
HttpCode,
Body,
Get,
Res,
Req,
Query,
UseGuards
} from '@nestjs/common';
import { ApiUseTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { AuthService } from './auth.service';
@@ -23,101 +23,108 @@ import { AuthGuard } from '@nestjs/passport';
@ApiUseTags('Auth')
@Controller()
export class AuthController {
constructor(
private readonly authService: AuthService,
private readonly commandBus: CommandBus
) {}
constructor(
private readonly authService: AuthService,
private readonly commandBus: CommandBus
) {}

@ApiOperation({ title: 'Is authenticated' })
@ApiResponse({ status: HttpStatus.OK })
@ApiResponse({ status: HttpStatus.BAD_REQUEST })
@Get('/authenticated')
async authenticated(): Promise<boolean> {
const token = RequestContext.currentToken();
@ApiOperation({ title: 'Is authenticated' })
@ApiResponse({ status: HttpStatus.OK })
@ApiResponse({ status: HttpStatus.BAD_REQUEST })
@Get('/authenticated')
async authenticated(): Promise<boolean> {
const token = RequestContext.currentToken();

return this.authService.isAuthenticated(token);
}
return this.authService.isAuthenticated(token);
}

@ApiOperation({ title: 'Has role?' })
@ApiResponse({ status: HttpStatus.OK })
@ApiResponse({ status: HttpStatus.BAD_REQUEST })
@Get('/role')
async hasRole(@Query('roles') roles: string[]): Promise<boolean> {
const token = RequestContext.currentToken();
@ApiOperation({ title: 'Has role?' })
@ApiResponse({ status: HttpStatus.OK })
@ApiResponse({ status: HttpStatus.BAD_REQUEST })
@Get('/role')
async hasRole(@Query('roles') roles: string[]): Promise<boolean> {
const token = RequestContext.currentToken();
return this.authService.hasRole(token, roles);
}

return this.authService.hasRole(token, roles);
}
@ApiOperation({ title: 'Create new record' })
@ApiResponse({
status: HttpStatus.CREATED,
description: 'The record has been successfully created.' /*, type: T*/
})
@ApiResponse({
status: HttpStatus.BAD_REQUEST,
description:
'Invalid input, The response body may contain clues as to what went wrong'
})
@Post('/register')
async create(
@Body() entity: IUserRegistrationInput,
...options: any[]
): Promise<IUser> {
if (!entity.user.imageUrl) {
entity.user.imageUrl = getUserDummyImage(entity.user);
}
return this.commandBus.execute(new AuthRegisterCommand(entity));
}

@ApiOperation({ title: 'Create new record' })
@ApiResponse({
status: HttpStatus.CREATED,
description: 'The record has been successfully created.' /*, type: T*/
})
@ApiResponse({
status: HttpStatus.BAD_REQUEST,
description:
'Invalid input, The response body may contain clues as to what went wrong'
})
@Post('/register')
async create(
@Body() entity: IUserRegistrationInput,
...options: any[]
): Promise<IUser> {
if (!entity.user.imageUrl) {
entity.user.imageUrl = getUserDummyImage(entity.user);
}
return this.commandBus.execute(new AuthRegisterCommand(entity));
}
@HttpCode(HttpStatus.OK)
@Post('/login')
async login(
@Body() { findObj, password },
...options: any[]
): Promise<{ user: IUser; token: string } | null> {
return this.authService.login(findObj, password);
}

@HttpCode(HttpStatus.OK)
@Post('/login')
async login(
@Body() { findObj, password },
...options: any[]
): Promise<{ user: IUser; token: string } | null> {
return this.authService.login(findObj, password);
}
@Get('google')
@UseGuards(AuthGuard('google'))
googleLogin() {}

@Get('google')
@UseGuards(AuthGuard('google'))
googleLogin() {}
@Get('google/callback')
@UseGuards(AuthGuard('google'))
googleLoginCallback(@Req() req, @Res() res) {
const {
success,
authData: { jwt, userId }
} = req.user;

@Get('google/callback')
@UseGuards(AuthGuard('google'))
googleLoginCallback(@Req() req, @Res() res) {
const { jwt, userId } = req.user;
if (success) {
return res.redirect(
`http://localhost:4200/#/sign-in/success?jwt=${jwt}&userId=${userId}`
);
} else {
return res.redirect('http://localhost:4200/#/auth/register');
}
}

if (jwt) {
return res.redirect(
`http://localhost:4200/#/google/success?jwt=${jwt}&userId=${userId}`
);
} else {
return res.redirect('http://localhost:4200');
}
}
@Get('facebook')
async requestFacebookRedirectUrl(@Res() res) {
const {
redirectUri
} = await this.authService.requestFacebookRedirectUri();
return res.redirect(redirectUri);
}

@Get('facebook')
async requestFacebookRedirectUrl(@Res() res) {
const { redirectUri } = await this.authService.requestFacebookRedirectUri();
return res.redirect(redirectUri);
}
@Get('facebook/callback')
async facebookCallback(@Req() req, @Res() res): Promise<any> {
const { code } = req.query;
return await this.authService.facebookSignIn(code, res);
}

@Get('facebook/callback')
async facebookCallback(@Req() req, @Res() res): Promise<any> {
const { code } = req.query;
return await this.authService.facebookSignIn(code, res);
}
@Post('facebook/token')
requestJsonWebTokenAfterFacebookSignIn(@Req() req, @Res() res) {
const {
success,
authData: { jwt, userId }
} = req.user;

@Post('facebook/token')
requestJsonWebTokenAfterFacebookSignIn(@Req() req, @Res() res) {
const { jwt, userId } = req.user;

if (jwt) {
return res.redirect(
`http://localhost:4200/#/google/success?jwt=${jwt}&userId=${userId}`
);
} else {
return res.redirect('http://localhost:4200');
}
}
if (success) {
return res.redirect(
`http://localhost:4200/#/sign-in/success?jwt=${jwt}&userId=${userId}`
);
} else {
return res.redirect('http://localhost:4200/#/auth/register');
}
}
}
@@ -11,29 +11,27 @@ import { authenticate } from 'passport';
import { FacebookStrategy } from './facebook.strategy';

@Module({
imports: [TypeOrmModule.forFeature([User, Role]), CqrsModule],
controllers: [AuthController],
providers: [
AuthService,
UserService,
RoleService,
...CommandHandlers,
GoogleStrategy,
FacebookStrategy
],
exports: [AuthService]
imports: [TypeOrmModule.forFeature([User, Role]), CqrsModule],
controllers: [AuthController],
providers: [
AuthService,
UserService,
RoleService,
...CommandHandlers,
GoogleStrategy,
FacebookStrategy
],
exports: [AuthService]
})
export class AuthModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(
authenticate('facebook', {
session: false
})
)
.forRoutes('auth/facebook/token');
}
configure(consumer: MiddlewareConsumer) {
consumer
.apply(
authenticate('facebook', {
session: false,
scope: ['email']
})
)
.forRoutes('auth/facebook/token');
}
}



0 comments on commit e6405d8

Please sign in to comment.
You can’t perform that action at this time.