You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
49 lines
1.5 KiB
49 lines
1.5 KiB
import * as api from '../../client/src/api'; |
|
import { EndpointError, EndpointHandler, catchUnhandledErrors } from './types'; |
|
import Knex from 'knex'; |
|
|
|
import { sha512 } from 'js-sha512'; |
|
|
|
export const RegisterUserEndpointHandler: EndpointHandler = async (req: any, res: any, knex: Knex) => { |
|
if (!api.checkRegisterUserRequest(req)) { |
|
const e: EndpointError = { |
|
internalMessage: 'Invalid RegisterUser request: ' + JSON.stringify(req.body), |
|
httpStatus: 400 |
|
}; |
|
throw e; |
|
} |
|
const reqObject: api.RegisterUserRequest = req.body; |
|
|
|
console.log("Register User: ", reqObject); |
|
|
|
await knex.transaction(async (trx) => { |
|
try { |
|
// check if the user already exists |
|
const user = (await trx |
|
.select('id') |
|
.from('users') |
|
.where({ email: reqObject.email }))[0]; |
|
if(user) { |
|
res.status(400).send(); |
|
return; |
|
} |
|
|
|
// Create the new user. |
|
const passwordHash = sha512(reqObject.password); |
|
const userId = (await trx('users') |
|
.insert({ |
|
email: reqObject.email, |
|
passwordHash: passwordHash, |
|
}) |
|
.returning('id') // Needed for Postgres |
|
)[0]; |
|
|
|
// Respond to the request. |
|
res.status(200).send(); |
|
|
|
} catch (e) { |
|
catchUnhandledErrors(e); |
|
trx.rollback(); |
|
} |
|
}) |
|
} |