create, update, remove users

This commit is contained in:
2018-05-30 19:24:48 +03:00
parent 00f71bb78d
commit fd142c8710
11 changed files with 1853 additions and 1413 deletions

7
routes/auth.js Normal file
View File

@@ -0,0 +1,7 @@
const jwt = require('express-jwt');
const { secret } = require('../config');
module.exports = {
required: jwt({ secret }),
optional: jwt({ secret, credentialsRequired: false }),
};

View File

@@ -43,11 +43,7 @@ router.patch(
if (completed !== undefined) {
patch.completed = completed;
}
const todo = await Todo.findByIdAndUpdate(
{ _id: todoId },
{ $set: patch },
{ new: true },
).exec();
const todo = await Todo.findByIdAndUpdate(todoId, { $set: patch }, { new: true }).exec();
if (!todo) {
throw new NotFoundError(`can't find todo with id ${todoId}`);
}

63
routes/users.js Normal file
View File

@@ -0,0 +1,63 @@
const express = require('express');
const mongoose = require('mongoose');
const passport = require('passport');
const User = mongoose.model('User');
const router = express.Router();
const asyncHelper = require('../asyncHelper');
const auth = require('./auth');
const { NotFoundError } = require('../errors');
router.post(
'/',
asyncHelper(async (req, res) => {
const { username, password } = req.body;
const user = new User({ username });
await user.setPassword(password);
await user.save();
res.json({ success: true, data: user.toAuthJson() });
}),
);
router.patch(
'/user',
auth.required,
asyncHelper(async (req, res) => {
const { username, password } = req.body;
const patch = {};
if (username !== undefined) {
patch.username = username;
}
const user = await User.findByIdAndUpdate(req.user.id, { $set: patch }, { new: true }).exec();
if (!user) {
throw new NotFoundError(`can't find user with username ${req.user.username}`);
}
if (password !== undefined) {
await user.setPassword(password);
await user.save();
}
res.json({ success: true, data: user.toAuthJson() });
}),
);
router.delete(
'/user',
auth.required,
asyncHelper(async (req, res) => {
await User.findByIdAndRemove(req.user.id).exec();
res.json({ success: true });
}),
);
router.post(
'/login',
passport.authenticate('local', { session: false }),
asyncHelper(async (req, res) => {
res.json({ success: true, data: req.user.toAuthJson() });
}),
);
module.exports = router;