· 6 years ago · Jul 01, 2019, 01:18 PM
1import { Controller, Post, HttpStatus, HttpCode, Get, Response, Body, Param, Req, Res } from '@nestjs/common';
2import { AuthService } from './auth.service';
3import { UserService } from '../user/user.service';
4import { User } from 'user/user.entity';
5
6@Controller('auth')
7export class AuthController {
8 constructor(private readonly authService: AuthService,
9 private readonly userService: UserService) {}
10 @Post('login')
11 async loginUser(@Response() res: any, @Body() body: User) {
12
13 if (!(body && body.email && body.password)) {
14 return res.status(HttpStatus.FORBIDDEN).json({ message: 'Email and password are required!' });
15 }
16
17 const user = await this.userService.findOneByEmail(body.email);
18
19 if (user) {
20 if (await this.userService.compareHash(body.password, user.password)) {
21
22 return res.status(HttpStatus.OK).json(await this.authService.createToken(user.email));
23 }
24 }
25
26 return res.status(HttpStatus.FORBIDDEN).json({ message: 'Email or password wrong!' });
27 }
28}
29
30import { Module, MiddlewareConsumer, forwardRef } from '@nestjs/common';
31import { JwtModule } from '@nestjs/jwt';
32import { AuthService } from './auth.service';
33import { JwtStrategy } from './jwt.strategy';
34import { UserModule } from '../user/user.module';
35import { PassportModule } from '@nestjs/passport';
36import { AuthController } from '../auth/auth.controller';
37import { PatientModule } from '../patient/patient.module'
38
39@Module({
40 imports: [
41 PassportModule.register({ defaultStrategy: 'jwt' }),
42 JwtModule.register({
43 secret: 'secretKey',
44 signOptions: {
45 expiresIn: 3600,
46 },
47 }),
48 UserModule,
49 PatientModule
50 ],
51 controllers: [AuthController],
52 providers: [AuthService, JwtStrategy],
53 exports: [AuthService],
54})
55export class AuthModule {}
56
57import { Injectable } from '@nestjs/common';
58import { JwtService } from '@nestjs/jwt';
59import { JwtPayload } from './jwt-payload.interface';
60import { UserService } from '../user/user.service';
61
62@Injectable()
63export class AuthService {
64 constructor(private readonly jwtService: JwtService, private readonly userService: UserService,) {}
65 async createToken(email) {
66 const expiresIn = 3600
67
68 const user: JwtPayload = { email:email};
69 const token = await this.jwtService.sign(user);
70 return {
71 token,
72 expiresIn: expiresIn
73 };
74 }
75
76 async validateUser(payload: JwtPayload): Promise<any> {
77 return await this.userService.findOneByEmail(payload.email);
78 }
79}
80
81import { Injectable, UnauthorizedException } from '@nestjs/common';
82import { PassportStrategy } from '@nestjs/passport';
83import { ExtractJwt, Strategy } from 'passport-jwt';
84import { AuthService } from './auth.service';
85import { JwtPayload } from './jwt-payload.interface';
86
87@Injectable()
88export class JwtStrategy extends PassportStrategy(Strategy) {
89 constructor(private readonly authService: AuthService) {
90 super({
91 jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
92 secretOrKey: 'secretKey',
93 });
94 }
95
96 async validate(payload: JwtPayload): Promise<boolean> {
97 const user = await this.authService.validateUser(payload);
98 if (!user) {
99 throw new UnauthorizedException();
100 }
101 return user;
102 }
103}