3 var User = require('./user.model');
4 var passport = require('passport');
5 var config = require('../../config/environment');
6 var jwt = require('jsonwebtoken');
8 function validationError(res, statusCode) {
9 statusCode = statusCode || 422;
10 return function(err) {
11 res.status(statusCode).json(err);
15 function handleError(res, statusCode) {
16 statusCode = statusCode || 500;
17 return function(err) {
18 res.status(statusCode).send(err);
22 function respondWith(res, statusCode) {
23 statusCode = statusCode || 200;
25 res.status(statusCode).end();
31 * restriction: 'admin'
33 exports.index = function(req, res) {
34 User.findAsync({}, '-salt -hashedPassword')
35 .then(function(users) {
36 res.status(200).json(users);
38 .catch(handleError(res));
44 exports.create = function(req, res, next) {
45 var newUser = new User(req.body);
46 newUser.provider = 'local';
47 newUser.role = 'user';
49 .spread(function(user) {
50 var token = jwt.sign({ _id: user._id }, config.secrets.session, {
51 expiresInMinutes: 60 * 5
54 res.json({ token: token });
56 .catch(validationError(res));
62 exports.show = function(req, res, next) {
63 var userId = req.params.id;
65 User.findByIdAsync(userId)
66 .then(function(user) {
68 return res.status(404).end();
70 res.json(user.profile);
72 .catch(function(err) {
79 * restriction: 'admin'
81 exports.destroy = function(req, res) {
82 User.findByIdAndRemoveAsync(req.params.id)
84 res.status(204).end();
86 .catch(handleError(res));
90 * Change a users password
92 exports.changePassword = function(req, res, next) {
93 var userId = req.user._id;
94 var oldPass = String(req.body.oldPassword);
95 var newPass = String(req.body.newPassword);
97 User.findByIdAsync(userId)
98 .then(function(user) {
99 if (user.authenticate(oldPass)) {
100 user.password = newPass;
101 return user.saveAsync()
103 res.status(204).end();
105 .catch(validationError(res));
107 return res.status(403).end();
115 exports.me = function(req, res, next) {
116 var userId = req.user._id;
118 User.findOneAsync({ _id: userId }, '-salt -hashedPassword')
119 .then(function(user) { // don't ever give out the password or salt
121 return res.status(401).end();
125 .catch(function(err) {
131 * Authentication callback
133 exports.authCallback = function(req, res, next) {