salix/back/models/account.js

89 lines
2.4 KiB
JavaScript
Raw Normal View History

2018-02-15 13:35:04 +00:00
const md5 = require('md5');
module.exports = Self => {
2019-01-04 12:32:04 +00:00
require('../methods/account/login')(Self);
require('../methods/account/logout')(Self);
require('../methods/account/acl')(Self);
require('../methods/account/validate-token')(Self);
2019-01-04 12:32:04 +00:00
2017-10-13 14:22:45 +00:00
// Validations
Self.validatesUniquenessOf('name', {
message: `A client with that Web User name already exists`
2017-10-13 14:22:45 +00:00
});
2018-02-15 13:35:04 +00:00
Self.observe('before save', (ctx, next) => {
2018-11-12 10:17:47 +00:00
if (ctx.currentInstance && ctx.currentInstance.id && ctx.data && ctx.data.password)
2018-02-15 13:35:04 +00:00
ctx.data.password = md5(ctx.data.password);
2018-11-12 10:17:47 +00:00
2018-02-15 13:35:04 +00:00
next();
});
2019-08-19 05:56:20 +00:00
Self.remoteMethod('getCurrentUserData', {
description: 'Gets the current user data',
accepts: [
{
2019-10-04 14:55:54 +00:00
arg: 'ctx',
type: 'Object',
http: {source: 'context'}
}
],
returns: {
2019-10-04 14:55:54 +00:00
type: 'Object',
root: true
},
http: {
verb: 'GET',
2019-08-19 05:56:20 +00:00
path: '/getCurrentUserData'
}
});
2019-08-19 05:56:20 +00:00
Self.getCurrentUserData = async function(ctx) {
let userId = ctx.req.accessToken.userId;
2019-10-04 14:55:54 +00:00
let account = await Self.findById(userId, {
fields: ['id', 'name', 'nickname']
});
let worker = await Self.app.models.Worker.findOne({
fields: ['id'],
where: {userFk: userId}
});
return Object.assign(account, {workerId: worker.id});
};
2018-05-08 07:32:30 +00:00
/**
* Checks if user has a role.
*
* @param {Integer} userId The user id
* @param {String} name The role name
2018-05-08 07:32:30 +00:00
* @return {Boolean} %true if user has the role, %false otherwise
*/
Self.hasRole = async function(userId, name) {
let roles = await Self.getRoles(userId);
2019-11-18 10:00:09 +00:00
return roles.some(role => role == name);
};
/**
* Get all user roles.
*
* @param {Integer} userId The user id
* @return {Object} User role list
*/
2018-11-12 10:17:47 +00:00
Self.getRoles = async userId => {
2018-05-08 07:32:30 +00:00
let result = await Self.rawSql(
`SELECT r.name
2018-05-08 07:32:30 +00:00
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 = [];
2018-11-12 10:17:47 +00:00
for (role of result)
roles.push(role.name);
2018-11-12 10:17:47 +00:00
return roles;
2018-05-08 07:32:30 +00:00
};
2017-10-13 14:22:45 +00:00
};