You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
70 lines
2.2 KiB
TypeScript
70 lines
2.2 KiB
TypeScript
import express, { Express, Router, Request, Response } from "express";
|
|
import Joi from "joi"
|
|
import Bcrypt from "bcrypt"
|
|
|
|
import { client } from "../db";
|
|
import { RegisterBody } from "../interfaces/registerBody";
|
|
import jsonwebtoken, { JsonWebTokenError } from "jsonwebtoken";
|
|
import { DatabaseError } from "pg";
|
|
import { UserTokenData } from "../interfaces/auth";
|
|
import { private_key } from "../environment"
|
|
|
|
const router: Router = express.Router();
|
|
|
|
const registerSchema = Joi.object({
|
|
firstname: Joi.string().min(2).required(),
|
|
lastname: Joi.string().min(1).required(),
|
|
email: Joi.string().email().required(),
|
|
password: Joi.string().min(8).required()
|
|
});
|
|
|
|
router.post("/register", async (req: Request, res: Response) => {
|
|
const validation = registerSchema.validate(req.body, { abortEarly: false });
|
|
if (validation.error !== undefined) {
|
|
return res.status(400).send(validation.error.details);
|
|
}
|
|
|
|
const userData: RegisterBody = validation.value;
|
|
|
|
const password_hash: String = await Bcrypt.hash(userData.password, 10);
|
|
|
|
try {
|
|
const insertResult = await client.query(`
|
|
INSERT INTO users (first_name, last_name, email, password_hash)
|
|
VALUES ($1, $2, $3, $4)
|
|
RETURNING id;
|
|
`, [
|
|
userData.firstname,
|
|
userData.lastname,
|
|
userData.email,
|
|
password_hash
|
|
]);
|
|
|
|
const user = insertResult.rows[0];
|
|
|
|
const jwtData: UserTokenData = {
|
|
tokenType: "User",
|
|
userId: user.id
|
|
};
|
|
|
|
const jwt: string = jsonwebtoken.sign(jwtData, private_key, { algorithm: "RS256", expiresIn: "4h" });
|
|
|
|
res.cookie("auth-token", jwt, { httpOnly: true, maxAge: 60 * 60 * 4 });
|
|
|
|
return res.status(200).send({ ...userData, password: undefined });
|
|
} catch (error: DatabaseError | Error | any) {
|
|
if (error.constraint == "users_email_key") {
|
|
return res.status(400).send([{
|
|
message: "\"email\" already exists",
|
|
path: [
|
|
"email"
|
|
],
|
|
type: "email.unique"
|
|
}]);
|
|
}
|
|
console.error(error);
|
|
return res.sendStatus(500);
|
|
}
|
|
})
|
|
|
|
export default router; |