file module import { Injectable } from '@nestjs/common' ; import { JwtService } from '@nestjs/jwt' ; import { InjectConnection } from '@nestjs/typeorm' ; import { Connection } from 'typeorm' ; import * as APP_CONFIG from '../../app.config' ; import { HttpUnauthorizedError } from '../../common/errors/unauthorized.error' ; import { ID } from '../../common/shared-types' ; import { ITokenResult } from '../../common/types/common-types' ; import { formatOneMeta } from '../../common/utils' ; import { User } from '../../entity' ; import { PasswordCiper } from '../helpers/password-cipher/password-ciper' ; @ Injectable ( ) export class AuthService { constructor ( @ InjectConnection ( ) private connection , private passwordCipher , private readonly jwtService ) { } async validateAuthData ( payload ) { if ( payload . type === 'wechat' || payload . type === 'member' ) { const user = await this . connection . getRepository ( User ) . findOne ( { identifier : payload . identifier , } ) ; if ( user ) { return payload ; } return null ; } } /**
     * Authenticates a user's credentials and if okay, creates a new session.
     * 验证用户的凭据，如果正确，则创建一个新会话。
     */ async authenticate ( identifier , password ) { const user = await this . getUserFromIdentifier ( identifier ) ; await this . verifyUserPassword ( user . id , password ) ; const userObj = formatOneMeta ( user , { cleanMeta : true } ) ; const token = this . jwtService . sign ( { type : userObj . type , identifier , id : user . id , } ) ; return Promise . resolve ( { token , expiresIn : APP_CONFIG . AUTH . expiresIn as number , } ) ; } param userId param password async verifyUserPassword ( userId , password ) { const user = await this . connection . getRepository ( User ) . findOne ( { loadEagerRelations : false , where : { id : userId , } , select : [ 'passwordHash' ] , } ) as User ; if ( ! user ) { throw new HttpUnauthorizedError ( ) ; } const passwordMathces = await this . passwordCipher . check ( password , user . passwordHash ? user . passwordHash : '' ) ; if ( ! passwordMathces ) { throw new HttpUnauthorizedError ( ) ; } return true ; } param identifier async getUserFromIdentifier ( identifier ) { const user = await this . connection . getRepository ( User ) . findOne ( { where : { identifier , } , } ) ; if ( ! user ) { throw new HttpUnauthorizedError ( ) ; } const me = formatOneMeta ( user ) ; return user ; } }