|
| 1 | +import {NextFunction, Request, Response} from "express"; |
| 2 | +import {logger} from "../logger"; |
| 3 | +import {AppDataSource} from "../data-source"; |
| 4 | +import {User} from "../models/user"; |
| 5 | +import {calculatePasswordHash} from "../utils"; |
| 6 | +const crypto = require("crypto"); |
| 7 | + |
| 8 | +/** |
| 9 | + * |
| 10 | + * curl -X POST http://localhost:9000/api/users -H "Content-Type:application/json" -d '{"email": "new-user@angular-university.io", "pictureUrl":"https://avatars.githubusercontent.com/u/5454709", "password": "test123", "isAdmin": false}' |
| 11 | + * |
| 12 | + */ |
| 13 | +export async function createUser( |
| 14 | + request: Request, response: Response, next:NextFunction) { |
| 15 | + |
| 16 | + try { |
| 17 | + |
| 18 | + logger.debug(`Called createUser()`); |
| 19 | + |
| 20 | + const {email, pictureUrl, password, isAdmin} = request.body; |
| 21 | + |
| 22 | + if (!email) { |
| 23 | + throw "Could not extract the email from the request, aborting."; |
| 24 | + } |
| 25 | + |
| 26 | + if (!password) { |
| 27 | + throw "Could not extract the plain text password from the request, aborting." |
| 28 | + } |
| 29 | + |
| 30 | + const repository = AppDataSource.getRepository(User); |
| 31 | + |
| 32 | + const user = await repository.createQueryBuilder("users") |
| 33 | + .where("email = :email", {email}) |
| 34 | + .getOne(); |
| 35 | + |
| 36 | + if (user) { |
| 37 | + const message = `User with email ${email} already exists, aborting.`; |
| 38 | + logger.error(message); |
| 39 | + response.status(500).json({message}); |
| 40 | + return; |
| 41 | + } |
| 42 | + |
| 43 | + const passwordSalt = crypto.randomBytes(64).toString('hex'); |
| 44 | + |
| 45 | + const passwordHash = await calculatePasswordHash(password, passwordSalt); |
| 46 | + |
| 47 | + const newUser = repository.create({ |
| 48 | + email, |
| 49 | + pictureUrl, |
| 50 | + isAdmin, |
| 51 | + passwordHash, |
| 52 | + passwordSalt |
| 53 | + }); |
| 54 | + |
| 55 | + await AppDataSource.manager.save(newUser); |
| 56 | + |
| 57 | + logger.info(`User ${email} has been created.`); |
| 58 | + |
| 59 | + response.status(200).json({ |
| 60 | + email, |
| 61 | + pictureUrl, |
| 62 | + isAdmin |
| 63 | + }); |
| 64 | + |
| 65 | + } |
| 66 | + catch (error) { |
| 67 | + logger.error(`Error calling createUser()`); |
| 68 | + return next(error); |
| 69 | + } |
| 70 | + |
| 71 | +} |
0 commit comments