Advertisement
Guest User

Untitled

a guest
Jan 24th, 2019
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.84 KB | None | 0 0
  1. import { Injectable, UnauthorizedException } from '@nestjs/common';
  2. import { JwtService } from '@nestjs/jwt';
  3. import bcrypt from 'bcrypt';
  4. import moment from 'moment';
  5. import { User } from '../user/entity/user.entity';
  6. import { UserService } from '../user/user.service';
  7.  
  8. export interface ISignIn {
  9. email: string;
  10. password: string;
  11. }
  12.  
  13. export interface ISignUp {
  14. email: string;
  15. firstName: string;
  16. lastName: string;
  17. mobilePhone: string;
  18. password: string;
  19. }
  20.  
  21. export interface ITokenPayloadUnsigned {
  22. uid: string; // user id
  23. }
  24.  
  25. export interface ITokenPayload extends ITokenPayloadUnsigned {
  26. exp: number; // inserted by jwt
  27. iat: number; // inserted by jwt
  28. }
  29.  
  30. @Injectable()
  31. export class AuthService {
  32. /**
  33. * Determine whether a given `password` matches with a password
  34. * hash.
  35. *
  36. * @param password Input password.
  37. * @param hash Target user's password hash.
  38. *
  39. * @return `true` if the password matches with the hash, or `false`.
  40. */
  41. private static async comparePassword(
  42. password: string,
  43. hash: string,
  44. ): Promise<boolean> {
  45. try {
  46. return await bcrypt.compare(password, hash);
  47. } catch (err) {
  48. return false;
  49. }
  50. }
  51.  
  52. /**
  53. * Compute and return the hash of the given `password`.
  54. *
  55. * @param password Password to be hashed.
  56. * @returns Resolves with hashed password
  57. */
  58. static async hashPassword(password: string): Promise<string> {
  59. const salt = await bcrypt.genSalt(10);
  60. return bcrypt.hash(password, salt);
  61. }
  62. constructor(
  63. private readonly userService: UserService,
  64. private readonly jwtService: JwtService,
  65. ) {}
  66.  
  67. /**
  68. * Create new User account and log in it
  69. *
  70. * @param data
  71. * @returns Resolves with JWT auth token
  72. */
  73. public async signIn(data: ISignIn): Promise<{ token: string }> {
  74. const user = await this.userService.getByEmail(data.email);
  75.  
  76. if (!user) {
  77. throw new UnauthorizedException('Cannot find any user');
  78. }
  79.  
  80. const isPasswordMatch = await AuthService.comparePassword(
  81. data.password,
  82. user.password,
  83. );
  84. if (!isPasswordMatch) {
  85. throw new UnauthorizedException('Cannot find any user');
  86. }
  87.  
  88. return { token: this.createToken(user) };
  89. }
  90.  
  91. /**
  92. * Log in a user with its email and password
  93. *
  94. * @param data
  95. * @returns Resolves with JWT auth token
  96. */
  97. public async signUp(data: ISignUp): Promise<{ token: string }> {
  98. const user = await this.userService.create({
  99. ...data,
  100. password: await AuthService.hashPassword(data.password),
  101. });
  102.  
  103. return { token: this.createToken(user) };
  104. }
  105.  
  106. /**
  107. * Make sure the token is both valid:
  108. * - structurally (payload has all expected fields)
  109. * - in the database (must exist)
  110. *
  111. * @param payload Token payload.
  112. *
  113. * @return `true` if the token is valid and exists, or `false`.
  114. */
  115. async validateTokenPayload(
  116. payload: ITokenPayload,
  117. ): Promise<User | undefined> {
  118. if (!payload) {
  119. return;
  120. }
  121.  
  122. const user = await this.userService.getById(payload.uid);
  123.  
  124. if (!user) {
  125. return;
  126. }
  127.  
  128. return moment(user.tokenBoundary).isBefore(1000 * payload.iat)
  129. ? user
  130. : undefined;
  131. }
  132.  
  133. /**
  134. * Generate a JWT token.
  135. *
  136. * @param user User for whom the token is created.
  137. */
  138. private createToken(user: User): string {
  139. const payload: ITokenPayloadUnsigned = {
  140. uid: user.userId,
  141. };
  142. return this.jwtService.sign(payload);
  143. }
  144. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement