66 lines
2.2 KiB
TypeScript
66 lines
2.2 KiB
TypeScript
import express from 'express';
|
|
import mongoose from 'mongoose';
|
|
import bcrypt from 'bcryptjs';
|
|
import UserValidate from './validate/user';
|
|
import UserModel from '../models/user';
|
|
import mail from '../helpers/mail';
|
|
|
|
const router = express.Router();
|
|
|
|
router.get('/users', (req, res) => {
|
|
res.json({message: 'users up and running!'});
|
|
});
|
|
|
|
router.post('/user/new', (req, res, next) => {
|
|
if (!req.auth(res, ['admin'], 'basic')) return;
|
|
|
|
// validate input
|
|
const {error, value: user} = UserValidate.input(req.body);
|
|
if(error !== undefined) {
|
|
res.status(400).json({status: 'Invalid body format'});
|
|
return;
|
|
}
|
|
|
|
// check that user does not already exist
|
|
UserModel.find({name: user.name}).lean().exec( 'find', (err, data) => {
|
|
if (err) next(err);
|
|
if (data.length > 0) {
|
|
res.status(400).json({status: 'Username already taken'});
|
|
return;
|
|
}
|
|
|
|
user.key = mongoose.Types.ObjectId(); // use object id as unique API key
|
|
bcrypt.hash(user.pass, 10, (err, hash) => { // password hashing
|
|
user.pass = hash;
|
|
new UserModel(user).save((err, data) => { // store user
|
|
if (err) next(err);
|
|
res.json(UserValidate.output(data.toObject()));
|
|
});
|
|
});
|
|
});
|
|
});
|
|
|
|
router.post('/user/passreset', (req, res, next) => {
|
|
// check if user/email combo exists
|
|
UserModel.find({name: req.body.name, email: req.body.email}).lean().exec( 'find', (err, data) => {
|
|
if (err) next(err);
|
|
if (data.length === 1) { // it exists
|
|
const newPass = Math.random().toString(36).substring(2);
|
|
bcrypt.hash(newPass, 10, (err, hash) => { // password hashing
|
|
if (err) next(err);
|
|
UserModel.findOneAndUpdate({name: req.body.name, email: req.body.email}, {pass: hash}, err => {
|
|
if (err) next(err);
|
|
mail(data[0].email, 'Your new password for the DFOP database', 'Hi, <br><br> You requested to reset your password.<br>Your new password is:<br><br>' + newPass + '<br><br>If you did not request a password reset, talk to the sysadmin quickly!<br><br>Have a nice day.<br><br>The DFOP team', err => {
|
|
if (err) next(err);
|
|
res.json({status: 'OK'});
|
|
});
|
|
});
|
|
});
|
|
}
|
|
else {
|
|
res.status(404).json({status: 'Not found'});
|
|
}
|
|
});
|
|
});
|
|
|
|
module.exports = router; |