All files / services/user auth.service.ts

93.18% Statements 41/44
83.33% Branches 15/18
80% Functions 4/5
93.18% Lines 41/44

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 1191x                       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x   1x 1x 1x       4x 4x           4x 4x 2x   4x 1x   4x 1x   4x         4x 1x     3x               3x     3x           2x   2x 2x           2x               2x 2x         2x 2x 1x               1x               2x      
import "../../../configEnv";
import { IAuthService } from "@schemas/services/auth/auth.v1.service";
import {
  AuthByPasswordReq,
  AuthByPasswordRsp,
  CreateReq,
  CreateRsp,
  UpdatePasswordReq,
  UpdatePasswordRsp,
  UpdateReq,
  UpdateRsp,
} from "@schemas/services/auth/auth.v1.schemas";
import AuthMethod from "@services/user/models/authMethod.model";
import Knex from "knex";
import knexfile from "@services/user/knexfile";
import { loadModels } from "@lib/objection-utils/objection-utils.lib";
import path from "path";
import User from "@services/user/models/user.model";
import { UserNotFound } from "@services/user/errors/user.errors";
import { IncorrectCredential, UnsupportedAuth } from "@services/user/errors/auth.errors";
import { comparePassword, hashPassword } from "@lib/encryption/encryption.lib";
import { BadRequestError } from "@mod/errors/base-errors";
 
export default class AuthService implements IAuthService {
  async init(): Promise<void> {
    const masterKnex = Knex(knexfile.production);
    const slaveKnex = Knex(knexfile.slave);
    loadModels(masterKnex, slaveKnex, path.join(__dirname, "models"));
  }
 
  async AuthByPassword(ctx, req: AuthByPasswordReq): Promise<AuthByPasswordRsp> {
    const { username, email, phone, password } = req;
    Iif (!username && !email && !phone) {
      throw new BadRequestError({
        message: "either `username` or `email` or `phone` is required",
      });
    }
 
    let whereQuery = {};
    if (username) {
      whereQuery = { username };
    }
    if (email) {
      whereQuery = { email };
    }
    if (phone) {
      whereQuery = { phone };
    }
    const user = await User.query()
      .where(whereQuery)
      .select("id")
      .limit(1)
      .first();
    if (!user) {
      throw new UserNotFound(whereQuery);
    }
 
    const authMethod = await AuthMethod.query()
      .where({
        userId: user.id,
        method: "password",
      })
      .select("data")
      .limit(1)
      .first();
    Iif (!(await comparePassword(password, authMethod.data.secret))) {
      throw new IncorrectCredential();
    }
    return {
      userId: user.id,
    };
  }
 
  async Create(ctx, req: CreateReq): Promise<CreateRsp> {
    const { userId, method, data = {} } = req;
    // set dataKey base on method...
    const dataKey = null;
    const authMethod = await AuthMethod.queryOnMaster().insert({
      userId,
      method,
      dataKey,
      data: JSON.stringify(data),
    });
    return authMethod;
  }
 
  Update(ctx, req: UpdateReq): Promise<UpdateRsp> {
    return undefined;
  }
 
  async UpdatePassword(ctx, req: UpdatePasswordReq): Promise<UpdatePasswordRsp> {
    const { userId, password } = req;
    const authMethod = await AuthMethod.query()
      .where({ userId, method: "password" })
      .select("id")
      .limit(1)
      .first();
    const secret = await hashPassword(password);
    if (authMethod) {
      await AuthMethod.queryOnMaster()
        .where({
          id: authMethod.id,
        })
        .patch({
          data: JSON.stringify({ secret }),
        });
    } else {
      await this.Create(ctx, {
        userId,
        method: "password",
        data: {
          secret,
        },
      });
    }
    return {};
  }
}