All files / src/controllers auth.controller.ts

53.06% Statements 173/326
36.8% Branches 60/163
40.62% Functions 13/32
53.1% Lines 171/322

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 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578  1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x   1x   50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x           1x                   1x                                                 1x 1x 1x 1x                       1x           1x                                                 1x                                                         1x                                                                                                                   1x     4x 4x 4x 4x 3x 3x 3x 1x       1x   1x 1x 1x     1x     1x       3x           1x 2x 2x 2x 2x     2x                             2x           1x 1x 1x 1x       1x 1x             1x           1x           1x                                               1x 8x 8x 8x 8x 4x 3x     3x 3x 1x   2x 2x 2x 2x 2x   6x             1x 8x 8x 8x 8x 6x     5x 5x 4x 2x       2x 2x 2x     2x     6x     50x 6x 6x 6x 2x   4x 2x 2x   4x 3x   3x 3x 3x           3x   1x   1x     5x 5x 5x         3x               3x     3x                                                                                                                                                     3x   3x     3x 1x 1x 2x 2x   3x 2x 2x   3x           9x   9x 5x 4x 1x 3x 3x       9x 9x 8x 3x   5x     1x       1x 1x 1x 1x 1x         1x 1x 1x               19x 19x            
"use strict";
import { inject } from '@loopback/core';
import { repository } from '@loopback/repository';
import { get, param, patch, post, Request, requestBody, Response, RestBindings } from '@loopback/rest';
import * as _ from 'lodash';
import { isString, reject } from 'lodash';
import moment from 'moment';
import { roles } from "../config";
import { ControllerKey, PasswordHasherBindings, TokenServiceBindings, UserServiceBindings } from '../keys';
import { User } from '../models';
import { AccountsRepository, ConsultantDetailsRepository, ContactUsUserDetailsRepository, LeadsRepository, OpportunitiesRepository, PaymentsRepository, PromoCodesRepository, RolesRepository, UserDetailsRepository, UserRepository } from '../repositories';
import { checkValidEmail, checkValidPhone, validateCredentials, validatePasswordAndConfirmPassword, validImageURL } from '../services';
import { sendContactUsMail, sendOTP, sendPromoCodeMail, welcomeEmail } from '../services/email';
import { BcryptHasher } from '../services/hash.password';
import { JWTService } from '../services/jwt-service';
import { MyUserService } from '../services/user-service';
import { agentBadgeDetails } from '../utils/agentBadgeDetails';
import errorMessages from '../utils/errorMessages';
import { log } from "../utils/logMethod";
import successMessages from '../utils/successMessages';
import { failureHandler, genOTP, getUID, promoCode, successHandler, validatePayload } from './components';
import { CloseIntegration, leadOwnerCustomFieldId } from "./components/closeIntegration";
import { validateEmailAddressZeroBounce } from './components/zeroBounceIntegration';
import { baseResponse, createCustomLeadReq, forgotPasswordReq, loginReq, resetPasswordReq, sendQuestionReq, signUpReq } from "./requestSpecs";
import { closeEvent, createCustomLeadType, emailRoleType, forgotPasswordPayload, loginType, promoCodeType, resetPasswordType, sendQuestion, signupUserForm, stripePayload, updatePayload } from "./types";
import { agentInfo } from './types/lead.controller.types';
let { invalidUserCredentials, notAuthorizedMsg, OTPExpired, registrarUIDNotFound, requiredFieldIsMissing, userAlreadyExist, userNotFound } = errorMessages
const otpExpiresIn: any = process.env.OTP_EXPIRES_IN
const closeIntegrations = new CloseIntegration()
 
export class AuthController {
  constructor(
    @repository(UserRepository) public userRepository: UserRepository,
    @inject(PasswordHasherBindings.PASSWORD_HASHER) public hasher: BcryptHasher,
    @inject(UserServiceBindings.USER_SERVICE) public userService: MyUserService,
    @inject(TokenServiceBindings.TOKEN_SERVICE) public jwtService: JWTService,
    @inject(RestBindings.Http.RESPONSE) protected res: Response,
    @inject(RestBindings.Http.REQUEST) protected req: Request,
    @repository(RolesRepository) public rolesRepository: RolesRepository,
    @repository(UserDetailsRepository) public userDetailsRepository: UserDetailsRepository,
    @repository(LeadsRepository) public leadsRepository: LeadsRepository,
    @repository(OpportunitiesRepository) public opportunitiesRepository: OpportunitiesRepository,
    @repository(PaymentsRepository) public paymentsRepository: PaymentsRepository,
    @inject(ControllerKey.CLOSE_COMPONENT) public closeIntegration: CloseIntegration,
    @repository(AccountsRepository) public accountsRepository: AccountsRepository,
    @repository(PromoCodesRepository) public promoCodesRepository: PromoCodesRepository,
    @repository(ContactUsUserDetailsRepository) public contactUsUserDetailsRepository: ContactUsUserDetailsRepository,
    @repository(ConsultantDetailsRepository) public consultantDetailsRepository: ConsultantDetailsRepository,
 
  ) { }
 
  @get('/updateCloseUser')
  @log()
  async updateCloseUser(): Promise<Response> {
    try {
      await this.loadCloseUser()
      return successHandler(this.res, 200, closeIntegrations.closeAgents)
    } catch (error) {
      return this.failureHandler(this.res, 403, error)
    }
  }
  @post('/createCloseLead')
  @log()
  async createCloseLead(@requestBody(createCustomLeadReq) body: createCustomLeadType): Promise<Response> {
    try {
      checkValidEmail(body.email)
      checkValidPhone(body.phone)
      validatePayload(body, createCustomLeadReq)
      await validateEmailAddressZeroBounce(body.email)
      let closeObj = {
        comments: body.comments,
        user: { email: body.email, name: body.name, phone: body.phone },
        systemIp: this.req.clientIp,
        leadSource: "saw.com",
        formName: body.formName
      }
      // create contact us details in Database
 
      const leadObj = await this.closeIntegration.createLead(closeObj)
      await this.contactUsUserDetailsRepository.create({ ...body, UID: getUID(), closeID: leadObj.id })
 
      return successHandler(this.res, 200, successMessages.formSubmitted)
    } catch (error) {
      return this.failureHandler(this.res, 403, error)
    }
  }
  @post('/sendQuestion')
  @log()
  async sendQuestion(@requestBody(sendQuestionReq) body: sendQuestion): Promise<Response> {
    try {
      validatePayload(body, sendQuestionReq)
      checkValidEmail(body.email)
      if (body.comments === "") {
        return this.failureHandler(this.res, 422, errorMessages.commentFieldIsEmpty)
      } else {
        await this.contactUsUserDetailsRepository.create({ ...body, UID: getUID() })
        return await sendContactUsMail(body).then(res => {
          return successHandler(this.res, 200, successMessages.formSubmitted)
        }).catch(e => {
          return this.failureHandler(this.res, 403, e)
        })
      }
    } catch (error) {
      return this.failureHandler(this.res, 403, error)
    }
  }
 
  @get('/verifyUser/{userUID}', baseResponse)
  @log()
  async verifyUser(
    @param.path.string('userUID') userUID: string,
  ): Promise<Response> {
    let methodName = "verifyUser"
    try {
      if (!userUID) {
        throw { code: 422, message: requiredFieldIsMissing, methodName }
 
      } else {
        const user = await this.userRepository.findOne({ where: { UID: userUID } })
        if (user) {
          await this.userRepository.updateAll({ isVerified: true }, { UID: userUID });
          return successHandler(this.res, 200, { name: user.name, UID: user.UID })
        } else {
          throw { code: 400, message: userNotFound, methodName }
 
        }
      }
    } catch (error) {
      return this.failureHandler(this.res, 403, error)
    }
  }
  // webhooks
  @post('/stripPaymentUpdate')
  @log()
  async paymentUpdate(@requestBody() body: stripePayload): Promise<Response> {
 
    try {
      validatePayload(body, loginReq)
      const stripeObj: typeof body.data.object = body.data.object
      const previous_attributes = body.data.previous_attributes
      if (body.type === 'charge.refunded') {
        const payload: updatePayload = {
          refund: (stripeObj.amount_refunded / 100).toString(),
          refundDate: new Date()
        }
        const payment = await this.paymentsRepository.findOne({ where: { paymentID: stripeObj.payment_intent } })
        if (payment) {
          // refund update account table
          const leadUID = payment?.leadUID
          const refunds = ((stripeObj.amount_refunded - previous_attributes.amount_refunded) / 100)
          this.createRegistrarAccounts({ refunds, leadUID })
        }
        await this.paymentsRepository.updateAll(payload, { paymentID: stripeObj.payment_intent })
      }
      return successHandler(this.res, 200, baseResponse)
    } catch (error) {
      return this.failureHandler(this.res, 202, error)
    }
  }
 
  // webhooks
  @post('/closeStatusUpdate/', baseResponse)
  @log()
  async closeStatusUpdate(@requestBody() closeStatus: { event: closeEvent }): Promise<Response> {
    let methodName = "closeStatusUpdate"
    const event = closeStatus.event
    try {
      if (!event)
        throw { code: 422, message: requiredFieldIsMissing, methodName }
 
      const data = event.data
 
      const payload: { status: string, soldAmount?: any, soldDate?: any, consultantUID?: string } = {
        status: data.status_label
      }
      const currentLeadAgentID = data[leadOwnerCustomFieldId]
      if (event.object_type === "lead") {
        const lead = await this.leadsRepository.findOne({ where: { closeUID: data.id } });
        if (lead && lead.closeUID === data.id && currentLeadAgentID && lead.consultantUID !== currentLeadAgentID) {
          const closeAgent = await this.userRepository.findOne({ where: { closeAgentUID: currentLeadAgentID } })
          // update close agent for the lead
          if (closeAgent) {
            await this.userRepository.updateAll({ leadAssigned: true }, { UID: closeAgent?.UID });
            payload.consultantUID = closeAgent.UID
            await this.leadsRepository.updateAll(payload, { UID: lead.UID });
          }
        }
      } else if (event.object_type === "opportunity") {
        const opportunity = await this.opportunitiesRepository.findOne({ where: { closeOpportunityID: data.id } });
        if (opportunity && opportunity.closeOpportunityID) {
          const accountsDetails = await this.accountsRepository.findOne({ where: { oppUID: opportunity.UID, leadUID: opportunity.leadUID } })
 
          if (isString(payload.status) && payload.status.toLocaleLowerCase().includes("sold")) {
            payload.soldDate = new Date()
            if (data.value) {
              payload.soldAmount = (data.value / 100)
              // domain Sold amount update in account table
              // if record already exist then update with createdAt  column
              if (accountsDetails) {
                this.accountsRepository.updateAll({ soldAmount: payload.soldAmount, createdAt: new Date().toString() }, { UID: accountsDetails.UID })
              } else {
                this.createRegistrarAccounts({ oppUID: opportunity.UID, leadUID: opportunity.leadUID, soldAmount: payload.soldAmount })
              }
            }
          } else {
            payload.soldDate = null
            if (accountsDetails) {
              await this.accountsRepository.deleteAll({ UID: accountsDetails.UID });
            }
          }
          await this.opportunitiesRepository.updateAll(payload, { UID: opportunity.UID });
        }
      }
    } catch (error) {
      console.error(error)
    }
    return successHandler(this.res, 200, baseResponse)
  }
 
  @patch('/forgotPassword', baseResponse)
  @log()
  async forgotPassword(
    @requestBody(forgotPasswordReq) body: forgotPasswordPayload,
  ): Promise<Response> {
    let methodName = "methodName"
    try {
      validatePayload(body, forgotPasswordReq)
      if (body.email) {
        const whereClause: emailRoleType = { email: body.email }
        checkValidEmail(body.email)
        const userResponse: User | string = await this.getUserWithRole(whereClause, body.isUser)
        Iif (isString(userResponse)) {
          throw { code: 422, message: userResponse, methodName }
 
        } else {
          const OTP = parseInt(genOTP())
          // send Email
          sendOTP(userResponse, OTP)
          await this.userRepository.updateById(userResponse.UID, { OTP });
          setTimeout(() => {
            this.userRepository.updateById(userResponse.UID, { OTP: undefined });
          }, otpExpiresIn);//mille seconds
          return successHandler(this.res, 200, successMessages.OTPExpires + otpExpiresIn / 60000 + " minutes.")
        }
      } else {
        throw { code: 422, message: requiredFieldIsMissing, methodName }
 
      }
    } catch (error) {
      return this.failureHandler(this.res, 403, error);
    }
  }
 
  @patch('/resetPassword', baseResponse)
  @log()
  async resetPassword(@requestBody(resetPasswordReq) body: resetPasswordType): Promise<Response> {
    let methodName = "resetPassword"
    try {
      validatePayload(body, resetPasswordReq)
      Iif (!body.OTP) {
        throw { code: 422, message: requiredFieldIsMissing, methodName }
      }
      await validatePasswordAndConfirmPassword(body)
      // Need to Hash OTP
      const foundUser = await this.userRepository.findOne({ where: { OTP: body.OTP } });
      if (!foundUser) {
        throw { code: 422, message: OTPExpired, methodName }
      }
 
      // Update OTP as undefined once used
      const updateObj = {
        OTP: undefined,
        password: await this.hasher.hashPassword(body.password)
      }
      await this.userRepository.updateById(foundUser.UID, updateObj);
      return successHandler(this.res, 200, successMessages.passwordChanged)
    } catch (error) {
      return this.failureHandler(this.res, 403, error);
    }
  }
 
  @post('/updateClicks/{registrarUID}')
  @log()
  async updateClicks(@param.path.string('registrarUID') registrarUID: string): Promise<Response> {
    let methodName = "updateClicks"
    try {
      Iif (!registrarUID) {
        throw { code: 422, message: requiredFieldIsMissing, methodName }
 
      } else {
        const foundRegistrar = await this.userRepository.findOne({ where: { UID: registrarUID } });
        Iif (foundRegistrar) {
          const accountsDetails = await this.accountsRepository.findOne({ where: { IP: this.req.clientIp, registrarUID } })
          if (!accountsDetails) {
            await this.accountsRepository.create({ UID: getUID(), registrarUID, IP: this.req.clientIp, click: 1 })
          }
          return successHandler(this.res, 200, successMessages.success)
        } else {
          throw { code: 422, message: registrarUIDNotFound, methodName }
        }
      }
 
 
    } catch (error) {
      return this.failureHandler(this.res, 403, error)
    }
  }
 
  @post('/registrarSignup')
  @log()
  async registrarSignup(@requestBody(signUpReq) userData: any): Promise<Response> {
    let methodName = "registrarSignup"
    try {
      validatePayload(userData, signUpReq)
      await validateCredentials(_.pick(userData, ['email', 'password']));
      await validatePasswordAndConfirmPassword(userData)
      if (userData.image) {
        await validImageURL(userData.image)
      }
      const foundUser = await this.userRepository.findOne({ where: { email: userData.email } });
      if (foundUser)
        throw { code: 409, message: errorMessages.registrarAlreadyExist, methodName }
 
      delete userData.confirmPassword
      userData.name = userData.name || userData.email.split('@')[0]
      const { token, userDetails }: any = await this.registerUser(userData, roles.registrar)
      return successHandler(this.res, 200, token)
    } catch (error) {
      return this.failureHandler(this.res, 403, error);
    }
  }
 
  @post('/signup')
  @log()
  async signup(@requestBody(signUpReq) userData: any): Promise<Response> {
    let methodName = "signup"
    try {
      validatePayload(userData, signUpReq)
      await validateCredentials(_.pick(userData, ['email', 'password']));
      await validatePasswordAndConfirmPassword(userData)
      Iif (userData.image) {
        await validImageURL(userData.image)
      }
      const foundUser = await this.userRepository.findOne({ where: { email: userData.email } });
      if (foundUser)
        throw { code: 409, message: userAlreadyExist, methodName }
 
      delete userData.confirmPassword
      userData.name = userData.name || userData.email.split('@')[0]
      userData.isUser = (userData.isUser === undefined || userData.isUser === true) ? true : false
      const { token }: any = await this.registerUser(userData)
      return successHandler(this.res, 200, token)
    } catch (error) {
      return this.failureHandler(this.res, 403, error);
    }
  }
 
 
  @post('/login', baseResponse)
  @log()
  async login(@requestBody(loginReq) body: loginType): Promise<any> {
    let methodName = "login"
    try {
      validatePayload(body, loginReq)
      if (body.email && body.password) {
        checkValidEmail(body.email);
        const whereClause: {
          email: string, roleId?: string
        } = { email: body.email }
        const user = await this.userService.verifyCredentials(body);
        const userResponse: string | User = await this.getUserWithRole(whereClause, body.isUser)
        Iif (isString(userResponse)) {
          throw { code: 422, message: userResponse, methodName }
 
        } else {
          const userProfile = this.userService.convertToUserProfile(user);
          const token = await this.jwtService.generateToken(userProfile);
          return successHandler(this.res, 200, token)
        }
      } else {
        throw { code: 422, message: requiredFieldIsMissing, methodName }
      }
    } catch (error) {
      return this.failureHandler(this.res, 422, error);
    }
  }
  registerUser = async (userData: any, roleType: string = roles.customer) => {
    let userDetails: any = {}
    const foundUser = await this.userRepository.findOne({ where: { email: userData.email } });
    if (foundUser && userData.email && userData.email === foundUser.email) {
      userDetails = foundUser
    } else {
      if (!userData.password || userData.providerId) {
        userData.password = "Saw@1234"
        userData.name = userData.name || userData.email.split("@")[0]
      }
      await validateCredentials(_.pick(userData, ['email', 'password']));
      await validateEmailAddressZeroBounce(userData.email)
 
      const user: signupUserForm = await this.getUserObject(userData, roleType)
      userDetails = await this.userRepository.create(user)
      Iif (!_.isEmpty(userData.userDetails)) {
        userDetails = userData.userDetails
        userDetails.userUID = user.UID
        userDetails.UID = getUID()
        await this.userDetailsRepository.create(userDetails);
      }
      if (roleType === roles.customer && userData.isUser === true) {
        // send welcome email to all customer type users
        welcomeEmail(userDetails)
        // Create promo code to skip the payment
        await this.generatePromoCode(userDetails)
      }
    }
    const userProfile = this.userService.convertToUserProfile(userDetails);
    const token = await this.jwtService.generateToken(userProfile);
    return { token, userDetails }
 
  }
 
  public async getUserObject(userData: signupUserForm, roleType: string) {
    const user: signupUserForm = {
      UID: getUID(),
      password: await this.hasher.hashPassword(userData.password || "Saw@1234"),
      name: userData.name,
      roleId: await this.getRoleUID(userData, roleType),
      email: userData.email,
      image: userData.image || ""
    }
    Iif (userData.closeAgentUID) {
      user.closeAgentUID = userData.closeAgentUID
    }
    return user
  }
 
  public async createRegistrarAccounts(accObj: { refunds?: any, oppUID?: string, soldAmount?: string, initialFee?: string, leadUID?: string }) {
    if (accObj.leadUID) {
      const leadDetails = await this.leadsRepository.findOne({ where: { UID: accObj.leadUID } })
      if (leadDetails?.registrarUID) {
        const payload = {
          UID: getUID(),
          registrarUID: leadDetails?.registrarUID,
          ...accObj
        }
        await this.accountsRepository.create(payload);
      }
    }
  }
 
  public async loadCloseUser() {
    const agents: agentInfo[] = closeIntegrations.closeAgents
    if (agents.length === 0) {
      await closeIntegrations.getusers()
    }
    await Promise.all(
      closeIntegrations.closeAgents.map(async (user) => {
        if (user) {
          let yogiCloseID = "user_PXm2K7Whj5vnCsOicUoFvUVjO0uGKySoyxQRhL4YPLv"
          if (user.id !== yogiCloseID) {
            const userObject: signupUserForm = {
              ...user,
              name: user.first_name + ' ' + user.last_name,
              image: "/assets/" + user.email + ".jpg",
              closeAgentUID: user.id
            }
            return new Promise(async (resolve, rejec) => {
              let { userDetails } = await this.registerUser(userObject, roles.consultant)
              if (userDetails) {
                this.loadConsultantBadge(userDetails)
                resolve(userDetails)
              } else {
                reject(userDetails)
              }
            })
          }
        }
      })).catch(e => {
        console.log(e)
        return false
      });
    return true
  }
  public loadConsultantBadge(consultantDetails: User) {
    let consultantBadge = _.find(agentBadgeDetails, (badge) => badge.email === consultantDetails.email)
    if (consultantBadge) {
      Promise.all(consultantBadge?.badges.map(async (badgeName: string) => {
        return new Promise(async (resolve, reject) => {
          let badge = {
            UID: getUID(),
            badgeName: "/assets/" + badgeName + ".png",
            consultantUID: consultantDetails.UID
          }
          let BadgeExisting = await this.consultantDetailsRepository.find({ where: { consultantUID: consultantDetails.UID } })
          let alreadyExistBadge = false
          if (BadgeExisting) {
            if (_.find(BadgeExisting, (dbBadge) => dbBadge.badgeName === badge.badgeName)) {
              alreadyExistBadge = true
            }
          }
          if (!alreadyExistBadge) {
            resolve(await this.consultantDetailsRepository.create(badge))
          }
        })
      }))
    }
  }
  public async getRoleUID(user: signupUserForm, roleType: any = roles.customer) {
    let methodName = "getRoleUID"
    let role;
    Iif (user.roleId) {
      role = await this.rolesRepository.findOne({ where: { UID: user.roleId } });
      throw { message: errorMessages.invalidRoleID, methodName }
    } else if (user.isUser === false) {
      roleType = roles.registrar
      role = await this.rolesRepository.findOne({ where: { roleType: roles.registrar } })
    } else Eif (roleType) {
      role = await this.rolesRepository.findOne({ where: { roleType: roleType } });
    }
    if (!role) {
      const obj = { roleType, UID: getUID() }
      role = await this.rolesRepository.create(obj);
    }
    return role.UID
  }
 
 
 
  public async getUserWithRole(whereClause: { email: string }, isUser?: boolean) {
    let methodName = "getUserWithRole"
    let role: string
    if (isUser) {
      role = roles.customer;
    } else if (isUser === false) {
      role = roles.registrar;
    } else Eif (!isUser) {
      role = roles.admin;
    } else {
      role = ""
    }
    const foundUser: any = await this.userRepository.findOne({ where: whereClause, include: ['role'] });
    if (foundUser) {
      if (foundUser.role && foundUser.role.roleType !== role) {
        throw { code: 401, message: notAuthorizedMsg, methodName }
      } else {
        return foundUser
      }
    } else {
      throw { code: 401, message: invalidUserCredentials, methodName }
    }
  }
  private async generatePromoCode(userDetails: User): Promise<void> {
    let methodName = "generatePromoCode"
    try {
      var date = moment().utc().add(1, 'M').endOf('day').format();
      let couponCode: string = await promoCode()
      let payload: promoCodeType = {
        UID: getUID(),
        code: couponCode,
        validThru: date
      }
      let result = await this.promoCodesRepository.create(payload)
      Eif (result) {
        sendPromoCodeMail(userDetails, { promoCode: couponCode, validThru: moment(date).format("ll") })
      }
    } catch (error) {
      throw { message: error, methodName }
    }
  }
 
  private failureHandler(res: Response, code: number, error: any): Promise<Response> {
    let className = error.className || AuthController.name
    return failureHandler(res, code, error, className)
  }
 
}