All files / src/controllers BaseUserController.ts

80.37% Statements 86/107
64.76% Branches 68/105
85.71% Functions 12/14
80.37% Lines 86/107

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240  8x                   8x   8x 8x 8x 8x 8x   8x   8x 1x     7x 3x 3x 3x   3x         3x       3x   3x 1x     2x                   1x     1x 1x       2x 2x     2x 1x   1x       3x 3x     3x     3x     3x 2x   2x 2x   2x   1x         1x     1x 1x       1x 1x 1x     1x   1x 1x         1x       2x     2x 2x       2x 1x 1x 1x 1x   1x                 1x                                             4x 4x 4x     4x 3x 3x 1x   2x   2x 1x       1x 1x     1x             1x   1x 1x     2x                   6x           5x 5x 5x 5x             4x 4x 4x 4x     4x 4x        
import { NextFunction, Request, Response } from 'express'
import {
  BadRequestError,
  Commun,
  EntityController,
  getModelAttribute,
  NotFoundError,
  SecurityUtils,
  ServerError,
  UnauthorizedError
} from '@commun/core'
import { AuthProvider, BaseUserModel, UserModule } from '..'
import { AccessToken, UserTokens } from '../types/UserTokens'
import { AccessTokenSecurity } from '../security/AccessTokenSecurity'
import { EmailClient } from '@commun/emails'
import passport from 'passport'
import { ExternalAuth } from '../security/ExternalAuth'
import ms from 'ms'
 
export class BaseUserController<MODEL extends BaseUserModel> extends EntityController<MODEL> {
  async create (req: Request): Promise<{ item: MODEL }> {
    if (!req.body.password) {
      throw new BadRequestError('Password cannot be blank')
    }
 
    const { item } = await super.create(req)
    const plainVerificationCode = await SecurityUtils.generateRandomString(48)
    const verificationCode = await SecurityUtils.hashWithBcrypt(plainVerificationCode, 12)
    const user = await this.dao.updateOne(item.id!, { verificationCode, verified: false })
 
    EmailClient.sendEmail('emailVerification', user.email, {
      verificationCode: plainVerificationCode,
      ...item
    })
 
    return { item }
  }
 
  async loginWithPassword (req: Request): Promise<{ user: MODEL, tokens: UserTokens }> {
    const user = await this.findUserByEmailOrUsername(req.body.username || '')
 
    if (!user || !user.password || !await SecurityUtils.bcryptHashIsValid(req.body.password, user.password)) {
      throw new UnauthorizedError('Invalid username or password')
    }
 
    return {
      user: await this.prepareModelResponse(req, user),
      tokens: {
        ...(await this.generateAccessToken(user)),
        refreshToken: await this.generateRefreshToken(user),
      },
    }
  }
 
  async logout (req: Request): Promise<{ result: boolean }> {
    Iif (!req.auth?.id) {
      return { result: false }
    }
    await this.dao.updateOne(req.auth.id, { refreshTokenHash: undefined })
    return { result: true }
  }
 
  async getAccessToken (req: Request): Promise<AccessToken> {
    const user = await this.dao.findOne({ username: req.body.username })
    Iif (!user) {
      throw new NotFoundError()
    }
    if (!user.refreshTokenHash || !await SecurityUtils.bcryptHashIsValid(req.body.refreshToken, user.refreshTokenHash)) {
      throw new UnauthorizedError('Refresh token is invalid or expired')
    }
    return this.generateAccessToken(user)
  }
 
  async verify (req: Request) {
    const user = await this.dao.findOne({ username: req.body.username })
    Iif (!user) {
      throw new NotFoundError()
    }
    Iif (user.verified) {
      return { result: true }
    }
    Iif (!user.verificationCode) {
      throw new BadRequestError('Missing verification code')
    }
    if (await SecurityUtils.bcryptHashIsValid(req.body.code, user.verificationCode)) {
      await this.dao.updateOne(user.id!, { verified: true, verificationCode: undefined })
 
      const userData = await this.prepareModelResponse(req, user, {})
      EmailClient.sendEmail('welcomeEmail', user.email, userData)
 
      return { result: true }
    } else {
      throw new BadRequestError('Invalid verification code')
    }
  }
 
  async forgotPassword (req: Request) {
    Iif (!req.body.username) {
      throw new BadRequestError('Missing email or username')
    }
    const user = await this.findUserByEmailOrUsername(req.body.username)
    Iif (!user) {
      throw new NotFoundError()
    }
 
    const resetPasswordAttr = Commun.getEntityConfig<MODEL>(UserModule.entityName).attributes.resetPasswordCodeHash
    const plainResetPasswordCode = await SecurityUtils.generateRandomString(48)
    const resetPasswordCodeHash = await getModelAttribute(resetPasswordAttr!, 'resetPasswordCodeHash', {
      resetPasswordCodeHash: plainResetPasswordCode
    })
    await this.dao.updateOne(user.id!, { resetPasswordCodeHash })
 
    const userData = await this.prepareModelResponse(req, user, {})
    EmailClient.sendEmail('resetPassword', user.email, {
      resetPasswordCode: plainResetPasswordCode,
      ...userData,
    })
 
    return { result: true }
  }
 
  async resetPassword (req: Request) {
    Iif (!req.body.username) {
      throw new BadRequestError('Missing email or username')
    }
    const user = await this.findUserByEmailOrUsername(req.body.username)
    Iif (!user) {
      throw new NotFoundError()
    }
 
    if (user.resetPasswordCodeHash && await SecurityUtils.bcryptHashIsValid(req.body.code, user.resetPasswordCodeHash)) {
      const passwordAttr = Commun.getEntityConfig<MODEL>(UserModule.entityName).attributes.password
      const password = await getModelAttribute<MODEL>(passwordAttr!, 'password', { password: req.body.password })
      await this.dao.updateOne(user.id!, { password, resetPasswordCodeHash: undefined })
      return { result: true }
    }
    throw new UnauthorizedError()
  }
 
  startAuthWithProvider (req: Request, res: Response, next: NextFunction) {
    const provider = req.params.provider as AuthProvider
    passport.authenticate(provider, ExternalAuth.getProviderStrategy(provider).authOptions)(req, res, next)
  }
 
  authenticateWithProvider (req: Request, res: Response, next: NextFunction) {
    passport.authenticate(req.params.provider, {})(req, res, next)
  }
 
  async completeAuthWithProvider (req: Request, res: Response) {
    const callbackUrl = UserModule.getOptions().externalAuth?.callbackUrl
    if (!callbackUrl) {
      console.error('External authentication callback url is not set')
      throw new ServerError()
    }
    const userReq = req.user as { user: MODEL, userCreated: boolean, newUser: boolean }
    const provider = req.params.provider as AuthProvider
    const code = await ExternalAuth.sign({
      user: userReq.user,
      provider: {
        key: provider,
        id: userReq.user.providers?.[provider]?.id!,
      },
      userCreated: userReq.userCreated,
    })
    res.redirect(`${callbackUrl}?provider=${provider}&newUser=${userReq.newUser}&code=${code}`)
  }
 
  async generateAccessTokenForAuthWithProvider (req: Request) {
    const provider = req.params.provider as AuthProvider
    const token = req.body.code
    const payload = await ExternalAuth.verify(token)
    let user
 
    if (payload.userCreated) {
      user = await this.dao.findOne({ email: payload.user.email })
      if (!user) {
        throw new NotFoundError('User not found')
      }
      const validProvider = payload.provider?.key === provider && payload.provider?.id && payload.provider?.id &&
        payload.provider?.id === user.providers?.[provider]?.id
      if (!validProvider) {
        throw new BadRequestError('Invalid authentication code')
      }
    } else {
      let userData
      Eif (!payload.user.username) {
        Iif (!req.body.username) {
          throw new BadRequestError('Username is required')
        }
        userData = {
          ...payload.user,
          username: req.body.username,
        }
      } else {
        userData = payload.user
      }
      user = await this.dao.insertOne(userData as MODEL)
 
      userData = await this.prepareModelResponse(req, user, {})
      EmailClient.sendEmail('welcomeEmail', user.email, userData)
    }
 
    return {
      user: await this.prepareModelResponse(req, user),
      tokens: {
        ...(await this.generateAccessToken(user)),
        refreshToken: await this.generateRefreshToken(user),
      },
    }
  }
 
  private findUserByEmailOrUsername (emailOrUsername: string) {
    return emailOrUsername.includes('@') ?
      this.dao.findOne({ email: emailOrUsername }) :
      this.dao.findOne({ username: emailOrUsername })
  }
 
  protected async generateAccessToken (user: MODEL) {
    const accessToken = await AccessTokenSecurity.sign({ id: user.id! })
    let expiresIn = UserModule.getOptions().accessToken?.expiresIn || 0
    const expirationMilliseconds = typeof expiresIn === 'number' ? expiresIn : ms(expiresIn)
    return {
      accessToken,
      accessTokenExpiration: new Date().getTime() + expirationMilliseconds
    }
  }
 
  protected async generateRefreshToken (user: MODEL): Promise<string | undefined> {
    Eif (UserModule.getOptions().refreshToken.enabled) {
      const refreshTokenAttr = Commun.getEntityConfig<MODEL>(UserModule.entityName).attributes.refreshTokenHash
      const plainRefreshToken = await SecurityUtils.generateRandomString(48)
      const refreshTokenHash = await getModelAttribute(refreshTokenAttr!, 'refreshTokenHash', {
        refreshTokenHash: plainRefreshToken
      })
      await this.dao.updateOne(user.id!, { refreshTokenHash })
      return plainRefreshToken
    }
  }
}