import { Application , Request , Response } from "express" ; import logger from "../../utilities/Logger" ; import { DatabaseResultSet , query } from "../../db/database-query" ; import { CreateAccount , CreateAccountCallBack , CreateAccountResponseTypes , } from "../../../../cshub-shared/src/api-calls" ; import { validateMultipleInputs } from "../../utilities/StringUtils" ; import { hashPassword } from "../../auth/HashPassword" ; import { sendVerificationEmail } from "../../utilities/MailConnection" ; export function registerCreateAccountEndpoint ( app ) { app . post ( CreateAccount . getURL , ( req , res ) => { const createAccountRequest = req . body as CreateAccount ; const inputsValidation = validateMultipleInputs ( { input : createAccountRequest . password , validationObject : { minlength : 8 , } , } , { input : createAccountRequest . email , validationObject : { tuemail : true , } , } , { input : createAccountRequest . firstname , validationObject : { minlength : 2 , maxlength : 127 , } , } , { input : createAccountRequest . lastname , validationObject : { minlength : 2 , maxlength : 127 , } , } ) ; if ( inputsValidation . valid ) { query ( `
            SELECT id
            FROM users
            WHERE email = ? AND domainId = ?
            ` , createAccountRequest . email , createAccountRequest . domain . id ) . then ( ( result ) => { if ( result . getRows ( ) . length === 0 ) { hashPassword ( createAccountRequest . password ) . then ( ( hashedValue ) => { query ( `
                            INSERT INTO users
                            SET email = ?, password = ?, firstname = ?, lastname = ?, domainId = ?
                            ` , createAccountRequest . email , hashedValue , createAccountRequest . firstname , createAccountRequest . lastname , createAccountRequest . domain . id ) . then ( ( result ) => { sendVerificationEmail ( createAccountRequest . email , createAccountRequest . firstname , result . getInsertId ( ) ) ; res . status ( 201 ) . json ( new CreateAccountCallBack ( CreateAccountResponseTypes . SUCCESS ) ) ; } ) . catch ( ( err ) => { logger . error ( `Inserting into users table failed` ) ; logger . error ( err ) ; res . status ( 500 ) . send ( ) ; } ) ; } ) . catch ( ( err ) => { logger . error ( `Hashing password for creating account failed` ) ; logger . error ( err ) ; res . status ( 500 ) . send ( ) ; } ) ; } else { res . json ( new CreateAccountCallBack ( CreateAccountResponseTypes . ALREADYEXISTS ) ) ; } } ) . catch ( ( err ) => { logger . error ( `Selecting from users failed` ) ; logger . error ( err ) ; res . status ( 500 ) . send ( ) ; } ) ; } else { res . status ( 400 ) . json ( new CreateAccountCallBack ( CreateAccountResponseTypes . INVALIDINPUT ) ) ; } } ) ; }