40 lines
1.1 KiB
TypeScript
40 lines
1.1 KiB
TypeScript
import express from 'express';
|
|
import mongoose from 'mongoose';
|
|
import bcrypt from 'bcryptjs';
|
|
import UserValidate from './validate/user';
|
|
import UserModel from '../models/user';
|
|
|
|
const router = express.Router();
|
|
|
|
router.get('/users', (req, res) => {
|
|
res.json({message: 'users up and running!'});
|
|
});
|
|
|
|
router.post('/user/new', (req, res, next) => {
|
|
// 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()));
|
|
});
|
|
});
|
|
});
|
|
});
|
|
|
|
module.exports = router; |