84 lines
2.2 KiB
JavaScript
84 lines
2.2 KiB
JavaScript
const md5 = require('md5');
|
|
|
|
module.exports = Self => {
|
|
require('../methods/account/login')(Self);
|
|
require('../methods/account/logout')(Self);
|
|
require('../methods/account/acl')(Self);
|
|
require('../methods/account/validate-token')(Self);
|
|
|
|
// Validations
|
|
|
|
Self.validatesUniquenessOf('name', {
|
|
message: `A client with that Web User name already exists`
|
|
});
|
|
|
|
Self.observe('before save', (ctx, next) => {
|
|
if (ctx.currentInstance && ctx.currentInstance.id && ctx.data && ctx.data.password)
|
|
ctx.data.password = md5(ctx.data.password);
|
|
|
|
next();
|
|
});
|
|
|
|
Self.remoteMethod('getCurrentUserName', {
|
|
description: 'Gets the current user name',
|
|
accepts: [
|
|
{
|
|
arg: 'context',
|
|
type: 'object',
|
|
http: function(ctx) {
|
|
return ctx;
|
|
}
|
|
}
|
|
],
|
|
returns: {
|
|
type: 'string',
|
|
root: true
|
|
},
|
|
http: {
|
|
verb: 'GET',
|
|
path: '/getCurrentUserName'
|
|
}
|
|
});
|
|
|
|
Self.getCurrentUserName = async function(ctx) {
|
|
let filter = {fields: ['name']};
|
|
let userId = ctx.req.accessToken.userId;
|
|
let account = await Self.findById(userId, filter);
|
|
|
|
return account.name;
|
|
};
|
|
|
|
/**
|
|
* Checks if user has a role.
|
|
*
|
|
* @param {Integer} userId The user id
|
|
* @param {String} name The role name
|
|
* @return {Boolean} %true if user has the role, %false otherwise
|
|
*/
|
|
Self.hasRole = async function(userId, name) {
|
|
let roles = await Self.getRoles(userId);
|
|
return roles.find(role => role == name);
|
|
};
|
|
|
|
/**
|
|
* Get all user roles.
|
|
*
|
|
* @param {Integer} userId The user id
|
|
* @return {Object} User role list
|
|
*/
|
|
Self.getRoles = async userId => {
|
|
let result = await Self.rawSql(
|
|
`SELECT r.name
|
|
FROM account.user u
|
|
JOIN account.roleRole rr ON rr.role = u.role
|
|
JOIN account.role r ON r.id = rr.inheritsFrom
|
|
WHERE u.id = ?`, [userId]);
|
|
|
|
let roles = [];
|
|
for (role of result)
|
|
roles.push(role.name);
|
|
|
|
return roles;
|
|
};
|
|
};
|