Page 416 - MDP2022-2
P. 416

import  {  LocalStrategy  }  from  './strategies/local.strategy';


            @Module({
                imports:  [
                    UsersModule,
                    PassportModule,
                    JwtModule.register({
                        secret:  jwtConstants.secret,
                        signOptions:  {  expiresIn:  '60s'  },
                    }),
                ],
                providers:  [AuthService,  LocalStrategy],
                exports:  [AuthService],
            })
            export  class  AuthModule  {}




            src/auth/auth.service.ts
            import  {
                HttpException,
                Injectable,
                UnauthorizedException,
            }  from  '@nestjs/common';
            import  {  JwtService  }  from  '@nestjs/jwt';
            import  {  UsersService  }  from  '../users/users.service';
            import  {  PostSignupDTO  }  from  './dto/post-signupDTO';
            import  *  as  bcrypt  from  'bcrypt';


            @Injectable()
            export  class  AuthService  {
                constructor(
                    private  readonly  usersService:  UsersService,
                    private  readonly  jwtService:  JwtService,
                )  {}


                async  validateUser(username:  string,  password:  string):  Promise<any>  {
                    const  user  =  await  this.usersService.findOne(username);
                    if  (!user)  throw  new  UnauthorizedException();
                    const  valid  =  await  bcrypt.compare(password,  user.password);
                    if  (!valid)  throw  new  UnauthorizedException();
                    return  true;
                }


                async  login(user:  any)  {
                    const  payload  =  {  username:  user.username,  sub:  user.userId  };
   411   412   413   414   415   416   417   418   419   420   421