All files / server/api/users users.policy.js

100% Statements 14/14
90% Branches 9/10
100% Functions 2/2
100% Lines 14/14
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 541x   1x 1x 1x                 1x 6x                               1x 7x   7x       7x 7x   7x 7x                   7x    
const _ = require('lodash');
 
const User = require('../../models/user');
const { ensureRequest } = require('../../utils/express');
const { hasRole, sameRecord } = require('../utils/policy');
 
/**
 * An authenticated user can retrieve himself. Administrators can retrieve anyone.
 *
 * @function
 * @name canRetrieve
 * @memberof module:server/api/users
 */
exports.canRetrieve = function(req) {
  return hasRole(req, 'admin') || sameRecord(req.currentUser, req.user);
};
 
/**
 * Serializes a user for API responses.
 *
 * Detailed properties of a user can only be seen by the user itself or an administrator.
 *
 * @function
 * @name serialize
 * @memberof module:server/api/users
 *
 * @param {Request} req - The Express request object.
 * @param {User} user - A user record.
 * @returns {object} A serialized user.
 */
exports.serialize = function(req, user) {
  ensureRequest(req);
 
  const serialized = {
    email: user.get('email')
  };
 
  const admin = req.currentUser && req.currentUser.hasRole('admin');
  const sameUser = req.currentUser && req.currentUser.get('api_id') == user.get('api_id');
 
  Eif (admin || sameUser) {
    _.extend(serialized, {
      id: user.get('api_id'),
      href: user.get('href'),
      active: user.get('active'),
      roles: user.get('roles'),
      createdAt: user.get('created_at'),
      updatedAt: user.get('updated_at')
    });
  }
 
  return serialized;
};