All files / src/security/userAndConnexion userLockService.ts

28% Statements 14/50
100% Branches 0/0
0% Functions 0/2
28% Lines 14/50

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 501x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                     1x 1x 1x                                    
 
 
 
import { db } from '../../db'
import { ModelTypes } from '../../cache/dbs/index.generated'
 
import { getId, addMinutes } from 'topkat-utils'
import { UserLockReasonsDefault } from './userAdditionalFields'
 
 
export async function ensureUserIsNotLocked(ctx: Ctx, userOrId: ModelTypes['user'] | string) {

  const user = typeof userOrId === 'string' ? await db.user.getById(ctx.GM, userOrId, { triggerErrorIfNotSet: true }) : userOrId

  if (user.isLocked) {
    if (user.lockUntil && (new Date(user.lockUntil)).getTime() < Date.now()) {
      // UNLOCK
      user.isLocked = false
      delete user.lockUntil
      await db.user.update(ctx.GM, getId(user), {
        isLocked: false,
        lockUntil: null,
      })
    } else {
      // IS LOCKED ERROR
      throw ctx.error.userLocked({ lockUntil: user.lockUntil, lockedReason: user.lockedReason, userId: getId(user) })
    }
  }
}
 
 
export async function lockUserAndThrow(ctx: Ctx, userId: string, reason: UserLockReasonsDefault | (string & {}), conf: {
  errExtraInfos?: Record<string, any>,
  lockDurationMinutes?: number
} = {}) {
  const lockUntil = addMinutes(new Date(), conf.lockDurationMinutes || 15, 'date')
  await db.user.update(ctx.GM, userId, {
    isLocked: true,
    lockedReason: reason as any,
    lockUntil,
    refreshTokens: [],
  })

  throw ctx.error.userLocked({
    lockedReason: reason,
    lockUntil: addMinutes(new Date(), conf.lockDurationMinutes || 15),
    userId,
    ...(conf.errExtraInfos || {})
  })
}