const randtoken = require ( 'rand-token' ) ; import bcrypt = require ( 'bcryptjs' ) ; import CONFIG from '../../../config' ; import { OtpService } from './otp.service' ; import { UserRepository } from '../repositories/user.repository' ; import { AccountRepository } from '../repositories/account.repository' ; import { InMemoryAccountRepository } from '../repositories/in-memory/in-memory-account.repository' ; import { InMemoryUserRepository } from '../repositories/in-memory/in-memory-user.repository' ; import { CategoriesRepository } from '../../settings/categories/categories.repository' ; import { InMemoryCategoriesRepository } from '../../settings/categories/in-memory-categories.repository' ; import { AuthRequest } from 'src/models/authRequest' ; import log from './../../../utils/logger' ; const userRepository = new InMemoryUserRepository ( ) ; const accountRepository = new InMemoryAccountRepository ( ) ; const categoriesRepository = new InMemoryCategoriesRepository ( ) ; const otp = new OtpService ( ) ; export class SignupService { signup ( signupRequest ) { const confirmationCode = randtoken . uid ( 256 ) ; return bcrypt . hash ( signupRequest . password , 10 ) . then ( hashedPassword => accountRepository . createAccount ( { } ) . then ( accountId => Promise . all ( [ categoriesRepository . createDefaultCategories ( accountId ) , userRepository . createUser ( { accountId : accountId , email : signupRequest . email , password : hashedPassword , role : 'OWNER' , confirmed : false , confirmationCode , createdWith : 'password' , tfaSecret : otp . generateNewSecret ( ) } ) ] ) ) . then ( ( ) => { log . info ( 'auth.signup_successful' , { email : signupRequest . email } ) ; this . sendConfirmationEmail ( signupRequest . email , confirmationCode ) ; return Promise . resolve ( ) ; } ) . catch ( error => { log . error ( 'auth.signup_failed' , { email : signupRequest . email } ) ; throw error ; } ) ) ; } confirm ( email , confirmationCode ) { return userRepository . getUserByEmail ( email ) . then ( user => { if ( user && ! user . confirmed && user . confirmationCode === confirmationCode ) { user . confirmed = true ; user . confirmationCode = undefined ; log . info ( 'auth.confirmation_successful' , { email } ) ; } else { log . warn ( 'auth.confirmation_failed' , { email } ) ; return Promise . reject ( ) ; } } ) ; } private sendConfirmationEmail ( email , code ) { const link = `${ CONFIG . clientUrl }/confirm?email=${ email }&code=${ code }` ; console . log ( `>>> LINK >>>: ${ link }` ) ; log . info ( 'auth.signup_confirmation_email_sent' , { email } ) ; } }