Account refactor
gitea/salix/pipeline/head There was a failure building this commit Details

This commit is contained in:
Joan Sanchez 2023-01-31 14:57:24 +01:00
parent 9bf4cd5cff
commit e34d64361b
39 changed files with 184 additions and 175 deletions

View File

@ -22,7 +22,7 @@ module.exports = Self => {
let userId = ctx.req.accessToken.userId;
let models = Self.app.models;
let user = await models.VnUser.findById(userId, {
let user = await Self.findById(userId, {
fields: ['id', 'name', 'nickname', 'email', 'lang'],
include: {
relation: 'userConfig',

View File

@ -44,9 +44,9 @@ module.exports = Self => {
if (typeof options == 'object')
Object.assign(myOptions, options);
const user = await models.VnUser.findById(userId, {fields: ['hasGrant']}, myOptions);
const user = await Self.findById(userId, {fields: ['hasGrant']}, myOptions);
const userToUpdate = await models.VnUser.findById(id, {
const userToUpdate = await Self.findById(id, {
fields: ['id', 'name', 'hasGrant', 'roleFk', 'password'],
include: {
relation: 'role',
@ -59,7 +59,7 @@ module.exports = Self => {
if (!user.hasGrant)
throw new UserError(`You don't have grant privilege`);
const hasRoleFromUser = await models.VnUser.hasRole(userId, userToUpdate.role().name, myOptions);
const hasRoleFromUser = await Self.hasRole(userId, userToUpdate.role().name, myOptions);
if (!hasRoleFromUser)
throw new UserError(`You don't own the role and you can't assign it to another user`);
@ -69,7 +69,7 @@ module.exports = Self => {
if (roleFk) {
const role = await models.Role.findById(roleFk, {fields: ['name']}, myOptions);
const hasRole = await models.VnUser.hasRole(userId, role.name, myOptions);
const hasRole = await Self.hasRole(userId, role.name, myOptions);
if (!hasRole)
throw new UserError(`You don't own the role and you can't assign it to another user`);
@ -78,6 +78,6 @@ module.exports = Self => {
}
await userToUpdate.save(userToUpdate);
await models.UserAccount.sync(userToUpdate.name);
await models.Account.sync(userToUpdate.name);
};
};

View File

@ -16,10 +16,8 @@ module.exports = Self => {
});
Self.recoverPassword = async function(email) {
const models = Self.app.models;
try {
await models.user.resetPassword({email, emailTemplate: 'recover-password'});
await Self.resetPassword({email, emailTemplate: 'recover-password'});
} catch (err) {
if (err.code === 'EMAIL_NOT_FOUND')
return;

View File

@ -35,7 +35,7 @@ module.exports = Self => {
let userInfo = usesEmail
? {email: user}
: {username: user};
let instance = await models.User.findOne({
let instance = await Self.findOne({
fields: ['username', 'password'],
where: userInfo
});
@ -58,14 +58,14 @@ module.exports = Self => {
throw new UserError('User disabled');
try {
await models.UserAccount.sync(instance.username, password);
await models.Account.sync(instance.username, password);
} catch (err) {
console.warn(err);
}
}
let loginInfo = Object.assign({password}, userInfo);
token = await models.User.login(loginInfo, 'user');
token = await Self.login(loginInfo, 'user');
return {token: token.id};
};
};

View File

@ -1,27 +0,0 @@
const LoopBackContext = require('loopback-context');
const {Email} = require('vn-print');
module.exports = function(Self) {
Self.on('resetPasswordRequest', async function(info) {
const loopBackContext = LoopBackContext.getCurrentContext();
const httpCtx = {req: loopBackContext.active};
const httpRequest = httpCtx.req.http.req;
const headers = httpRequest.headers;
const origin = headers.origin;
const user = await Self.app.models.VnUser.findById(info.user.id);
const params = {
recipient: info.email,
lang: user.lang,
url: `${origin}/#!/reset-password?access_token=${info.accessToken.id}`
};
const options = Object.assign({}, info.options);
for (const param in options)
params[param] = options[param];
const email = new Email(options.emailTemplate, params);
return email.send();
});
};

View File

@ -1,19 +0,0 @@
{
"name": "user",
"base": "User",
"options": {
"mysql": {
"table": "salix.User"
}
},
"properties": {
"id": {
"id": true,
"type": "number",
"forceId": false
},
"username":{
"type": "string"
}
}
}

View File

@ -1,14 +1,14 @@
const md5 = require('md5');
const vnModel = require('vn-loopback/common/models/vn-model');
const LoopBackContext = require('loopback-context');
const {Email} = require('vn-print');
module.exports = function(Self) {
vnModel(Self);
require('../methods/vn-user/signIn')(Self);
require('../methods/vn-user/signOut')(Self);
require('../methods/vn-user/acl')(Self);
require('../methods/vn-user/change-password')(Self);
require('../methods/vn-user/recover-password')(Self);
require('../methods/vn-user/set-password')(Self);
require('../methods/vn-user/validate-token')(Self);
require('../methods/vn-user/privileges')(Self);
@ -90,4 +90,27 @@ module.exports = function(Self) {
return roles;
};
Self.on('resetPasswordRequest', async function(info) {
const loopBackContext = LoopBackContext.getCurrentContext();
const httpCtx = {req: loopBackContext.active};
const httpRequest = httpCtx.req.http.req;
const headers = httpRequest.headers;
const origin = headers.origin;
const user = await Self.app.models.VnUser.findById(info.user.id);
const params = {
recipient: info.email,
lang: user.lang,
url: `${origin}/#!/reset-password?access_token=${info.accessToken.id}`
};
const options = Object.assign({}, info.options);
for (const param in options)
params[param] = options[param];
const email = new Email(options.emailTemplate, params);
return email.send();
});
};

View File

@ -7,11 +7,6 @@
"table": "account.user"
}
},
"excludeBaseProperties": [
"username",
"password",
"login"
],
"properties": {
"id": {
"type": "number",
@ -21,6 +16,19 @@
"type": "string",
"required": true
},
"username": {
"type": "string",
"mysql": {
"columnName": "name"
}
},
"password": {
"type": "string",
"required": true,
"mysql": {
"columnName": "bcryptPassword"
}
},
"roleFk": {
"type": "number",
"mysql": {
@ -33,10 +41,6 @@
"lang": {
"type": "string"
},
"password": {
"type": "string",
"required": true
},
"bcryptPassword": {
"type": "string"
},
@ -96,13 +100,6 @@
"permission": "ALLOW"
},
{
"property": "signOut",
"accessType": "EXECUTE",
"principalType": "ROLE",
"principalId": "$authenticated",
"permission": "ALLOW"
},
{
"property": "recoverPassword",
"accessType": "EXECUTE",
"principalType": "ROLE",

View File

@ -1,17 +1,18 @@
UPDATE `salix`.`ACL`
SET model='VnUser'
WHERE id=1;
UPDATE `salix`.`ACL`
SET model='VnUser'
WHERE id=219;
UPDATE `salix`.`ACL`
SET model='VnUser'
WHERE id=220;
UPDATE `salix`.`ACL`
SET model='VnUser'
WHERE id=246;
INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
VALUES ('VnUser', '*', '*', 'ALLOW', 'ROLE', 'employee');
UPDATE hedera.imageCollection t
INSERT INTO `salix`.`ACL` (id, model, property, accessType, permission, principalType, principalId)
VALUES ('VnUser', 'acl', 'READ', 'ALLOW', 'ROLE', 'account');
INSERT INTO `salix`.`ACL` (id, model, property, accessType, permission, principalType, principalId)
VALUES ('VnUser', 'getCurrentUserData', 'READ', 'ALLOW', 'ROLE', 'account');
INSERT INTO `salix`.`ACL` (id, model, property, accessType, permission, principalType, principalId)
VALUES ('VnUser', 'changePassword', '*', 'ALLOW', 'ROLE', 'account');
UPDATE `hedera`.`imageCollection` t
SET t.model = 'VnUser'
WHERE t.id = 6;

View File

@ -76,7 +76,7 @@ export default class Auth {
}
logout() {
let promise = this.$http.post('VnUsers/signOut', null, {
let promise = this.$http.post('VnUsers/logout', null, {
headers: {Authorization: this.vnToken.token}
}).catch(() => {});

View File

@ -9,7 +9,7 @@
"relations": {
"user": {
"type": "belongsTo",
"model": "user",
"model": "VnUser",
"foreignKey": "userId"
}
}
@ -41,9 +41,6 @@
}
}
},
"user": {
"dataSource": "vn"
},
"Schema": {
"dataSource": "vn"
},

View File

@ -29,6 +29,6 @@ module.exports = Self => {
Self.changePassword = async function(id, oldPassword, newPassword) {
await Self.rawSql(`CALL account.user_changePassword(?, ?, ?)`,
[id, oldPassword, newPassword]);
await Self.app.models.UserAccount.syncById(id, newPassword);
await Self.app.models.Account.syncById(id, newPassword);
};
};

View File

@ -0,0 +1,27 @@
module.exports = Self => {
Self.remoteMethod('login', {
description: 'Login a user with username/email and password',
accepts: [
{
arg: 'user',
type: 'String',
description: 'The user name or email',
required: true
}, {
arg: 'password',
type: 'String',
description: 'The password'
}
],
returns: {
type: 'object',
root: true
},
http: {
path: `/login`,
verb: 'POST'
}
});
Self.login = async(user, password) => Self.app.models.VnUser.signIn(user, password);
};

View File

@ -1,5 +1,5 @@
module.exports = Self => {
Self.remoteMethod('signOut', {
Self.remoteMethod('logout', {
description: 'Logout a user with access token',
accepts: [
{
@ -13,13 +13,10 @@ module.exports = Self => {
root: true
},
http: {
path: `/signOut`,
path: `/logout`,
verb: 'POST'
}
});
Self.signOut = async function(ctx) {
await Self.app.models.VnUser.logout(ctx.req.accessToken.id);
return true;
};
Self.logout = async ctx => Self.app.models.VnUser.logout(ctx.req.accessToken.id);
};

View File

@ -23,6 +23,6 @@ module.exports = Self => {
Self.setPassword = async function(id, newPassword) {
await Self.rawSql(`CALL account.user_setPassword(?, ?)`,
[id, newPassword]);
await Self.app.models.UserAccount.syncById(id, newPassword);
await Self.app.models.Account.syncById(id, newPassword);
};
};

View File

@ -3,7 +3,7 @@ const {models} = require('vn-loopback/server/server');
describe('account changePassword()', () => {
it('should throw an error when old password is wrong', async() => {
let err;
await models.VnUser.changePassword(1, 'wrongPassword', 'nightmare.9999')
await models.Account.changePassword(1, 'wrongPassword', 'nightmare.9999')
.catch(error => err = error.sqlMessage);
expect(err).toBeDefined();

View File

@ -1,14 +1,14 @@
const {models} = require('vn-loopback/server/server');
describe('VnUser setPassword()', () => {
describe('Account setPassword()', () => {
it('should throw an error when password does not meet requirements', async() => {
let req = models.VnUser.setPassword(1, 'insecurePass');
let req = models.Account.setPassword(1, 'insecurePass');
await expectAsync(req).toBeRejected();
});
it('should update password when it passes requirements', async() => {
let req = models.VnUser.setPassword(1, 'Very$ecurePa22.');
let req = models.Account.setPassword(1, 'Very$ecurePa22.');
await expectAsync(req).toBeResolved();
});

View File

@ -38,7 +38,7 @@
"SipConfig": {
"dataSource": "vn"
},
"UserAccount": {
"Account": {
"dataSource": "vn"
},
"UserPassword": {

View File

@ -138,7 +138,7 @@ module.exports = Self => {
};
if (user) {
let exists = await $.UserAccount.exists(user.id);
let exists = await $.Account.exists(user.id);
Object.assign(info, {
hasAccount: user.active && exists,
corporateMail: `${userName}@${this.domain}`,
@ -177,11 +177,11 @@ module.exports = Self => {
async syncUser(userName, info, password) {
if (info.user && password)
await app.models.user.setPassword(info.user.id, password);
await app.models.VnUser.setPassword(info.user.id, password);
},
async getUsers(usersToSync) {
let accounts = await app.models.UserAccount.find({
let accounts = await app.models.Account.find({
fields: ['id'],
include: {
relation: 'user',

View File

@ -0,0 +1,10 @@
module.exports = Self => {
require('../methods/account/sync')(Self);
require('../methods/account/sync-by-id')(Self);
require('../methods/account/sync-all')(Self);
require('../methods/account/login')(Self);
require('../methods/account/logout')(Self);
require('../methods/account/change-password')(Self);
require('../methods/account/set-password')(Self);
};

View File

@ -0,0 +1,42 @@
{
"name": "Account",
"base": "VnModel",
"options": {
"mysql": {
"table": "account.account"
}
},
"properties": {
"id": {
"id": true
}
},
"relations": {
"user": {
"type": "belongsTo",
"model": "VnUser",
"foreignKey": "id"
},
"aliases": {
"type": "hasMany",
"model": "MailAliasAccount",
"foreignKey": "account"
}
},
"acls": [
{
"property": "login",
"accessType": "EXECUTE",
"principalType": "ROLE",
"principalId": "$everyone",
"permission": "ALLOW"
},
{
"property": "logout",
"accessType": "EXECUTE",
"principalType": "ROLE",
"principalId": "$authenticated",
"permission": "ALLOW"
}
]
}

View File

@ -248,7 +248,7 @@ module.exports = Self => {
return {key: e.inheritsFrom, val: e.role};
});
let accounts = await $.UserAccount.find({
let accounts = await $.Account.find({
fields: ['id'],
include: {
relation: 'user',

View File

@ -1,6 +0,0 @@
module.exports = Self => {
require('../methods/user-account/sync')(Self);
require('../methods/user-account/sync-by-id')(Self);
require('../methods/user-account/sync-all')(Self);
};

View File

@ -1,26 +0,0 @@
{
"name": "UserAccount",
"base": "VnModel",
"options": {
"mysql": {
"table": "account.account"
}
},
"properties": {
"id": {
"id": true
}
},
"relations": {
"user": {
"type": "belongsTo",
"model": "VnUser",
"foreignKey": "id"
},
"aliases": {
"type": "hasMany",
"model": "MailAliasAccount",
"foreignKey": "account"
}
}
}

View File

@ -5,7 +5,7 @@ import UserError from 'core/lib/user-error';
export default class Controller extends Section {
onSynchronizeAll() {
this.vnApp.showSuccess(this.$t('Synchronizing in the background'));
this.$http.patch(`UserAccounts/syncAll`)
this.$http.patch(`Accounts/syncAll`)
.then(() => this.vnApp.showSuccess(this.$t('Users synchronized!')));
}
@ -17,7 +17,7 @@ export default class Controller extends Section {
password: this.syncPassword,
force: true
};
return this.$http.patch(`UserAccounts/${this.syncUser}/sync`, params)
return this.$http.patch(`Accounts/${this.syncUser}/sync`, params)
.then(() => this.vnApp.showSuccess(this.$t('User synchronized!')));
}

View File

@ -16,7 +16,7 @@ class Controller extends ModuleCard {
return Promise.all([
this.$http.get(`VnUsers/${this.$params.id}`, {filter})
.then(res => this.user = res.data),
this.$http.get(`UserAccounts/${this.$params.id}/exists`)
this.$http.get(`Accounts/${this.$params.id}/exists`)
.then(res => this.hasAccount = res.data.exists)
]);
}

View File

@ -16,7 +16,7 @@ describe('component vnUserCard', () => {
controller.$params.id = 1;
$httpBackend.expectGET('VnUsers/1').respond('foo');
$httpBackend.expectGET('UserAccounts/1/exists').respond({exists: true});
$httpBackend.expectGET('Accounts/1/exists').respond({exists: true});
controller.reload();
$httpBackend.flush();

View File

@ -20,7 +20,7 @@ class Controller extends Descriptor {
this.hasAccount = null;
if (!value) return;
this.$http.get(`UserAccounts/${value.id}/exists`)
this.$http.get(`Accounts/${value.id}/exists`)
.then(res => this.hasAccount = res.data.exists);
}
@ -54,7 +54,7 @@ class Controller extends Descriptor {
} else
method = 'setPassword';
return this.$http.patch(`VnUsers/${this.id}/${method}`, params)
return this.$http.patch(`Accounts/${this.id}/${method}`, params)
.then(() => {
this.emit('change');
this.vnApp.showSuccess(this.$t('Password changed succesfully!'));
@ -69,12 +69,12 @@ class Controller extends Descriptor {
}
onEnableAccount() {
return this.$http.post(`UserAccounts`, {id: this.id})
return this.$http.post(`Accounts`, {id: this.id})
.then(() => this.onSwitchAccount(true));
}
onDisableAccount() {
return this.$http.delete(`UserAccounts/${this.id}`)
return this.$http.delete(`Accounts/${this.id}`)
.then(() => this.onSwitchAccount(false));
}

View File

@ -10,7 +10,7 @@ describe('component vnUserDescriptor', () => {
beforeEach(inject(($componentController, _$httpBackend_) => {
$httpBackend = _$httpBackend_;
$httpBackend.whenGET('UserAccounts/1/exists').respond({exists: true});
$httpBackend.whenGET('Accounts/1/exists').respond({exists: true});
controller = $componentController('vnUserDescriptor', {$element: null}, {user});
jest.spyOn(controller, 'emit');
@ -61,7 +61,7 @@ describe('component vnUserDescriptor', () => {
describe('onEnableAccount()', () => {
it('should make request to enable account', () => {
$httpBackend.expectPOST('UserAccounts', {id: 1}).respond();
$httpBackend.expectPOST('Accounts', {id: 1}).respond();
controller.onEnableAccount();
$httpBackend.flush();
@ -73,7 +73,7 @@ describe('component vnUserDescriptor', () => {
describe('onDisableAccount()', () => {
it('should make request to disable account', () => {
$httpBackend.expectDELETE('UserAccounts/1').respond();
$httpBackend.expectDELETE('Accounts/1').respond();
controller.onDisableAccount();
$httpBackend.flush();

View File

@ -33,7 +33,7 @@ module.exports = function(Self) {
const user = {
name: data.userName,
email: firstEmail,
password: parseInt(Math.random() * 100000000000000)
password: String(Math.random() * 100000000000000)
};
try {

View File

@ -1,6 +1,6 @@
const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('setPassword', {
Self.remoteMethod('setPassword', {
description: 'Sets the password of a non-worker client',
accepts: [
{
@ -21,13 +21,13 @@ module.exports = Self => {
}
});
Self.setPassword = async function(ctx, id, newPassword) {
Self.setPassword = async function(id, newPassword) {
const models = Self.app.models;
const isClient = await models.Client.findById(id, null);
const isUserAccount = await models.UserAccount.findById(id, null);
const isClient = await models.Client.findById(id);
const isAccount = await models.Account.findById(id);
if (isClient && !isUserAccount)
if (isClient && !isAccount)
await models.VnUser.setPassword(id, newPassword);
else
throw new UserError(`Modifiable password only via recovery or by an administrator`);

View File

@ -1,16 +1,11 @@
const models = require('vn-loopback/server/server').models;
describe('Client setPassword', () => {
const salesPersonId = 19;
const ctx = {
req: {accessToken: {userId: salesPersonId}}
};
fdescribe('Client setPassword', () => {
it('should throw an error the setPassword target is not just a client but a worker', async() => {
let error;
try {
await models.Client.setPassword(ctx, 1, 't0pl3v3l.p455w0rd!');
await models.Client.setPassword(1, 't0pl3v3l.p455w0rd!');
} catch (e) {
error = e;
}
@ -22,7 +17,7 @@ describe('Client setPassword', () => {
let error;
try {
await models.Client.setPassword(ctx, 1101, 't0pl3v3l.p455w0rd!');
await models.Client.setPassword(1101, 't0pl3v3l.p455w0rd!');
} catch (e) {
error = e;
}

View File

@ -51,9 +51,9 @@ module.exports = Self => {
throw new UserError(`Not enough privileges to edit a client`);
const isClient = await models.Client.findById(id, null, myOptions);
const isUserAccount = await models.UserAccount.findById(id, null, myOptions);
const isAccount = await models.Account.findById(id, null, myOptions);
if (isClient && !isUserAccount) {
if (isClient && !isAccount) {
const user = await models.VnUser.findById(id, null, myOptions);
await user.updateAttributes(ctx.args, myOptions);
} else

View File

@ -184,7 +184,7 @@ module.exports = Self => {
let invalidBusinessType = false;
if (!ctx.isNewInstance) {
const isWorker = await Self.app.models.UserAccount.findById(orgData.id);
const isWorker = await Self.app.models.Account.findById(orgData.id);
const changedFields = Object.keys(changes);
const hasChangedOtherFields = changedFields.some(key => key !== 'businessTypeFk');

View File

@ -25,7 +25,7 @@ module.exports = Self => {
Self.observe('after save', async ctx => {
const loopBackContext = LoopBackContext.getCurrentContext();
const models = Self.app.models;
const user = await models.user.findById(loopBackContext.active.accessToken.userId);
const user = await models.VnUser.findById(loopBackContext.active.accessToken.userId);
const bankEntity = await models.BankEntity.findById(ctx.instance.bankEntityFk);
await Self.app.models.Mail.create({
receiver: 'finanzas@verdnatura.es',

View File

@ -155,7 +155,7 @@ module.exports = Self => {
myOptions
);
await models.UserAccount.create(
await models.Account.create(
{
id: user.id,
},
@ -245,7 +245,7 @@ module.exports = Self => {
throw error;
}
await models.user.resetPassword({
await models.VnUser.resetPassword({
email: args.email,
emailTemplate: 'worker-welcome',
id: client.id