Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- static async CreateUser(req: Request, res: Response, next: NextFunction) {
- interface CreateUserRequest {
- firstname: string,
- lastname: string,
- username: string,
- email: string,
- password: string
- };
- /** Input validation */
- req.checkBody("firstname").isLength({ min: 0, max: 35 });
- req.checkBody("lastname").isLength({ min: 0, max: 35 });
- req.checkBody("username").isLength({ min: 0, max: 35 });
- req.checkBody("email").isLength({ min: 0, max: 255 }).isEmail();
- req.checkBody("password").isLength({ min: 1, max: 30 });
- let request: CreateUserRequest = {
- firstname: req.body.firstname,
- lastname: req.body.lastname,
- username: req.body.username,
- email: req.body.email,
- password: req.body.password
- };
- try {
- await req.asyncValidationErrors();
- let findAndCount = await Database.userSchema.findAndCount({
- where: {
- $or: [
- {
- email: request.email
- },
- {
- username: request.username
- }
- ]
- }
- });
- let users: User.UserInstance[] = findAndCount.rows;
- let count: number = findAndCount.count;
- if (count > 0) {
- let duplicateEmails = users.filter((user) => {
- return user.email == request.email;
- }).length;
- if (duplicateEmails > 0) {
- throw new Error("EMAIL_EXISTS");
- }
- let duplicateUsernames = users.filter((user) => {
- return user.username.toLowerCase() == request.username.toLowerCase();
- }).length;
- if (duplicateEmails > 0) {
- throw new Error("USERNAME_EXISTS");
- }
- }
- let hashedPassword: string = bcrypt.genSaltAsync(10).then(function (result) {
- return bcrypt.hashAsync(request.password, result, null);
- });
- let createdUser: User.UserInstance = <any>Database.userSchema.create({
- firstname: request.firstname,
- lastname: request.lastname,
- username: request.username,
- permissions: {},
- email: request.email,
- signupdate: new Date(),
- settings: {},
- setup: false,
- password: hashedPassword
- });
- res.json({
- id: createdUser.id
- });
- }
- catch (err) {
- res.status(500).json({ error: err.message });
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement