Press n or j to go to the next uncovered block, b, p or k for the previous block.
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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | 'use strict'; const path = require('path'); const async = require('async'); const querystring = require('querystring'); const loopback = require("loopback"); const logger = require('../../services/logger'); const config = require('../../server/config.json'); const PASSWORD_MIN_LENGTH = 8; module.exports = function(Enduser) { Enduser.settings.caseSensitiveEmail = false; Enduser.beforeRemote('login', function(context, userInstance, next) { Enduser.find({ where: { email: {ilike: context.args.credentials.email } } }, function(err, user) { Iif (err) return next(err); Iif (!user || user[0] == null) return next(false); Iif (user[0].PasswordChangedAt == null) { return next(new Error("Default password hasn't been changed!")); } return next(); }); }); Enduser.afterRemote('login', (context, result, next) => { Enduser.findById(result.userId, (err, user) => { Iif (err) return next(err); Iif (!user) return next(false); user.updateAttributes({ LastLogin: new Date() }, (err, updatedUser) => { Iif (err) return next(err); return next(); }); }); }); /* Enduser.afterRemote('confirm', function(context, userInstance, next) { const userId = context.args.uid; Enduser.find({ where: { id: userId } }, function(err, user) { if (err) return next(err); if (user[0] == null) return next(new Error("Not found!")); user[0].createAccessToken(config.passwordResetTtl, function(err, obj) { if (err) return next(err); obj.updateAttribute('scopes', ['DEFAULT', 'reset'], function(err, token) { if (err) return next(err); next(); }); }); }); }); */ Enduser.confirmAndSetPassword = function(confirmString, password, cb) { const confirmData = querystring.parse(confirmString.split('?')[1]); const error = new Error(); Enduser.find({ where: { id: confirmData.uid } }, function(err, user) { if (err) return cb(err); if (!user || !user[0]) { error.status = 404; error.message = 'Not found!'; return cb(error); } if (user[0].emailVerified === true) { error.status = 400; error.message = 'Already confirmed!'; return cb(error); } if (password.length < PASSWORD_MIN_LENGTH) { error.status = 422; error.message = 'Password is too short.' return cb(error); } Enduser.confirm(confirmData.uid, confirmData.token, null, function(err, confirm) { if (err) { error.status = 500; error.message = 'Confirmation failed!'; return cb(error) } const updatedAttributes = {'password': password,'PasswordChangedAt': new Date()}; user[0].updateAttributes(updatedAttributes, function(err, updatedUser) { if (err) { error.status = 500; error.message = 'Confirmation failed!'; return cb(error) } return cb(); }); }); }); }; Enduser.remoteMethod('confirmAndSetPassword', { accepts: [ { arg: 'confirm', type: 'string' }, { arg: 'password', type: 'string' } ] }); Enduser.createUser = function(email, password, roleName, siteId, cb) { try { Enduser.app.dataSources.db.transaction(async models => { const enduser = await models.endUser.create({ email: email, password: Enduser.hashPassword(password), CreatedAt: new Date(), emailVerified: true, PasswordChangedAt: new Date() }); const role = await models.Role.findOne({ where: { name: roleName } }); const rolemapping = await models.RoleMapping.create({ principalType: 'USER', principalId: enduser.id, roleId: role.id }); const address = await models.address.create({CreatedAt: new Date()}); const person = await models.person.create({UserId: enduser.id, AddressId: address.id, CreatedAt: new Date()}); let site = siteId; Eif (!site) { const firstSite = await models.site.findOne(); Eif (firstSite) site = firstSite.id; } const resource = await models.resource.create({PersonId: person.id, SiteId: site, CreatedAt: new Date()}); const data = {enduser, role, rolemapping, address, person, resource}; return cb(null, data); }); } catch (e) { logger.debug(`Error creating user, ${e}`); return cb(null); } } Enduser.remoteMethod('createUser', { accepts: [ { arg: 'email', type: 'string', required: true }, { arg: 'password', type: 'string', required: true }, { arg: 'role', type: 'string', required: true }, { arg: 'siteId', type: 'number', required: true } ], returns: { arg: 'response', type: 'object', root: true } }); Enduser.createNewUser = function(email, firstName, lastName, siteId, roles, cb) { const date = new Date(); const roleIds = []; let errorAfterCreate = false; Enduser.app.models.site.find({ where: { id: siteId } }, function (err, site) { if (err) return cb(err); if (!site || !site[0]) return cb(new Error("Site not found.")); async.each(roles, function(element, callback) { Enduser.app.models.Role.find({ where: { id: element.id } }, function (err, result) { if (err || !result || result[0] == null) { return cb(new Error(`Could not find role "${element.Name}"!`)); } roleIds.push(result[0].id); callback(); }); }, function (err) { if (err) return cb(err); const password = Math.random().toString(36).slice(-6); const userData = { "email": email, "password": password, "CreatedAt": date } Enduser.create(userData, function(err, user) { if (err) return cb(err); roleIds.forEach(function(item) { Enduser.app.models.RoleMapping.create({ principalType: 'USER', principalId: user.id, roleId: item }, function(err, principal) { if (err) { logger.debug(`Error creating role for ${email}`); errorAfterCreate = true; } }); }); const addressData = {"CreatedAt": date}; Enduser.app.models.Address.create(addressData, function(err, address) { if (err) { logger.debug(`Error creating Address for ${email}`); errorAfterCreate = true; } const personData = { "UserId": user.id, "Firstname": firstName, "Lastname": lastName, "AddressId": address.id, "CreatedAt": date } Enduser.app.models.Person.create(personData, function(err, person) { if (err) { logger.debug(`Error creating Person for ${email}`); errorAfterCreate = true; } const resourceData = { "PersonId": person.id, "SiteId": siteId, "CreatedAt": date } Enduser.app.models.Resource.create(resourceData, function(err, resource) { if (err) { logger.debug(`Error creating Resource for ${email}`); errorAfterCreate = true; } if (errorAfterCreate) { Enduser.destroyById(user.id, function(err, deleted) { if (err) return cb(err); if (deleted.count > 0) return cb(new Error(`Error creating associated tables. User ${email} not created!`)); return cb(new Error(`Error creating associated tables and error deleting created user.`)); }); } else { const port = `:${config.uiPort}`; const noPort = ""; const verifyHref = `${config.protocol}://${config.serviceDomain ? config.serviceDomain : config.host}${config.serviceDomain? noPort : port}/confirm?uid=${user.id}&redirect=%2F`; const options = { type: 'email', port: '443', to: user.email, from: config.defaultEmailSender, subject: 'Welcome to caleō!', firstName: firstName, verifyHref: verifyHref, template: path.resolve(__dirname, '../templates/verify-email.ejs'), }; user.verify(options, function(err, response, next) { if (err) { logger.debug(`Error verifying user ${email}`); Enduser.destroyById(user.id, function(err, deleted) { if (err || deleted.count === 0) logger.debug(`Error deleting user ${email} after failed verify`); }); } return cb(null, user.id, person.id, address.id, resource.id); }); } }); }); }); }); }); }); } Enduser.remoteMethod('createNewUser', { accepts: [{ arg: 'Email', type: 'string' }, { arg: 'FirstName', type: 'string' }, { arg: 'LastName', type: 'string' }, { arg: 'SiteId', type: 'number' }, { arg: 'RoleNames', type: 'array' }], returns: [{ arg: 'userId', type: 'number' }, { arg: 'personId', type: 'number' }, { arg: 'addressId', type: 'number' }, { arg: 'resourceId', type: 'number' } ] }); Enduser.afterRemote('setPassword', function(context, user, next) { const date = new Date(); Enduser.find({ where: { id: context.args.id } }, function (err, result) { if(err) return next(err); if(!result || result[0] == null) return next(new Error("Not found!")); result[0].updateAttribute('PasswordChangedAt', date, function(err, obj) { if(err) return next(err); if(!obj || obj[0]) return next(new Error("Not found!")); Enduser.logout(context.req.accessToken.id, function(err) { if (err) return next(err); }); next(null, true); }); }); }); Enduser.beforeRemote('setPassword', function(context, user, next) { if (context.req.accessToken.scopes !== null) { if (context.req.accessToken.scopes.includes('reset')) if (context.req.body.newPassword.length < PASSWORD_MIN_LENGTH) { let error = new Error(); error.status = 422; error.message = 'Password is too short.' return next(error); } return next(); } else { const error = new Error(); error.status = 401; error.message = 'Authorization Required'; error.code = 'AUTHORIZATION_REQUIRED'; return next(error); } }); Enduser.beforeRemote('resetPassword', function(context, user, next) { Enduser.find({ where: { email: context.req.body.email } }, function(err, user) { if (err) return next(err); if (!user || !user[0]) context.res.status(204).send(null); else next(); }); }); Enduser.on('resetPasswordRequest', function(info) { info.user.createAccessToken(config.passwordResetTtl, function(err, obj) { if (err) return logger.debug(err); obj.updateAttribute('scopes', ['DEFAULT', 'reset'], function(err, cb) { if (err) return logger.debug(err); const port = `:${config.uiPort}`; const noPort = ""; const verifyHref = `${config.protocol}://${config.serviceDomain ? config.serviceDomain : config.host}${config.serviceDomain? noPort : port}/reset-password?access_token=${cb.id}`; Enduser.app.models.person.find({ where: { UserId: info.user.id } }, function(err, person) { if (err) return logger.debug(err); if (!person || !person[0]) return logger.debug(`User ${info.email} not found`); const templateData = {firstName: person[0].Firstname, verifyHref: verifyHref}; const renderer = loopback.template(path.resolve(__dirname, __dirname, '../templates/reset-password.ejs')); const html = renderer(templateData); Enduser.app.models.Email.send({ to: info.email, from: config.defaultEmailSender, subject: 'Reset your caleō password', host: 'Localhost', html: html }, function(err) { if (err) return logger.debug(err); }); }); }); }); }); Enduser.getResource = function(userId, cb) { if(userId === '' || !userId || typeof userId === 'undefined' || userId == null){ const error = new Error('Missing data'); error.status = 401; return cb(error); } Enduser.app.models.Person.find({ where: { UserId: userId } }, function(err, person) { if (err) return cb(err); if (!person || !person[0]) { const error = new Error('Person not found!'); error.status = 401; return cb(error); } Enduser.app.models.Resource.find({ where: { PersonId: person[0].id } }, function(err, resource) { if (err) return cb(err); if (!resource || !resource[0]) return cb(new Error('Resource not found!')); return cb(null, resource[0].id); }); }); } Enduser.remoteMethod('getResource', { accepts: { arg: 'UserId', type: 'number' }, returns: { arg: 'ResourceId', type: 'number' } }); Enduser.getUser = function(userId, cb) { Enduser.findOne( { include: [{roles:"role"}, {person:"resource"}], where: { id: userId } }, async function(err, result) { if (err) return cb(err); const permissions = await Enduser.app.models.accessControl.getPermissions(userId); result.permissions = permissions; return cb(null, result); }); }; Enduser.remoteMethod('getUser', { http: {verb: 'get'}, accepts: [ { arg: 'UserId', type: 'number' } ], returns: { arg: 'result', type: 'object' } }); Enduser.reActivate = async (userId, cb) => { try { const user = await Enduser.findById(userId); const person = await Enduser.app.models.person.find({ where: { UserId: userId } }); const port = `:${config.uiPort}`; const noPort = ""; const verifyHref = `${config.protocol}://${config.serviceDomain ? config.serviceDomain : config.host}${config.serviceDomain? noPort : port}/confirm?uid=${user.id}&redirect=%2F`; const options = { type: 'email', port: '443', to: user.email, from: config.defaultEmailSender, subject: 'Welcome to caleō!', firstName: person[0].Firstame, verifyHref: verifyHref, template: path.resolve(__dirname, '../templates/verify-email.ejs'), }; user.verify(options, function(err, response) { if (err) { logger.error(`Error verifying user ${user.email}:` +err); } else { logger.debug('Response: '+JSON.stringify(response)); } return cb(null, user.id, person.id); }); } catch (e) { logger.error('Error re-sending activation email.') return cb(e); }; }; Enduser.remoteMethod('reActivate', { accepts: [ { arg: 'userId', type: 'number' } ], returns: [ { arg: 'response', type: 'object' } ] }); Enduser.remoteMethod('deleteUser', { http: {verb: 'del'}, accepts: [ { arg: 'userId', type: 'number', required: true } ], returns: { arg: 'count', type: 'number' } }); Enduser.deleteUser = async (userId) => { try { const deleteCount = await Enduser.destroyById(userId); logger.info(`Deleted user: ${userId}`); return deleteCount.count; } catch (e) { logger.error(`Error deleting user ${userId}, ${e}`); return 0; } } Enduser.remoteMethod('findRoles', { http: {verb: 'get'}, returns: { arg: 'response', type: 'array', root: true } }); Enduser.findRoles = async() => { try { const translatedRoles = []; const roleTranslations = await Enduser.app.models.roleTranslations.find(); const roles = await Enduser.app.models.Role.find(); for (const role of roles) { role.translations = []; for (const roleTranslation of roleTranslations) { if (roleTranslation.RoleId === role.id) { role.translations.push(roleTranslation); } } translatedRoles.push(role); } return translatedRoles; } catch (e) { logger.error(`Error finding roles, ${e}`); return []; } } Enduser.remoteMethod('createRole', { http: {verb: 'post'}, accepts: [ { arg: 'translations', type: 'array', required: true } ], returns: [{ arg: 'groups', type: 'array' }, { arg: 'roles', type: 'object' } ] }); Enduser.createRole = async(translations, cb) => { let operations = []; let roles ={}; try { if (translations.length === 0) throw new Error("Error getting translations for new role."); // Role name cannot be empty for LoopBack role table. Generate new name. let name = `role_${translations[0].name.trim()}_${translations[0].languageId}`; await Enduser.app.dataSources.db.transaction(async models => { const checkRoleName = await models.Role.findOne({ where: { name: name } }); if (checkRoleName) { // If generated name already exists. name = name + Math.floor(Math.random() * 99999); } const role = await models.Role.create({ name: name, created: Date.now() }); for (const translation of translations) { if (translation.name == null || translation.name.trim().length > 15 || translation.name.trim().length < 3) throw new RangeError("Role name must be 3-15 characters."); const checkIfExists = await models.roleTranslations.findOne({ where: { Name: translation.name, LanguageId: translation.languageId } }); if (checkIfExists) { const error = new Error("Role already exists"); error.name = 'Exists'; throw error; } await models.roleTranslations.create({ Name: translation.name, Description: translation.description, LanguageId: translation.languageId, RoleId: role.id }); } }); } catch (e) { if (e instanceof RangeError) throw e; if (e.name === 'Exists') throw e; logger.error(`Error creating role, ${e}`); throw new Error("Unexpected error!"); } const returnTable = await Enduser.app.models.accessControl.getOperationsTable(); operations = returnTable.groups; roles = returnTable.roles; return cb(null, operations, roles); } Enduser.remoteMethod('editRole', { http: {verb: 'put'}, accepts: [ { arg: 'translations', type: 'array', required: true }, { arg: 'id', type: 'number', required: true } ], returns: [{ arg: 'groups', type: 'array' }, { arg: 'roles', type: 'object' } ] }); Enduser.editRole = async(translations, id, cb) => { let operations = []; let roles ={}; try { if (translations.length === 0) throw new Error("Error getting translations for edited role"); await Enduser.app.dataSources.db.transaction(async models => { const roleExists = await models.Role.findById(id); if (!roleExists) throw new Error("Role does not exist.") for (const translation of translations) { if (translation.name == null || translation.name.trim().length > 15 || translation.name.trim().length < 3) throw new RangeError("Role name must be 3-15 characters."); const oldTranslation = await models.roleTranslations.findById(translation.id); if (!oldTranslation) throw new Error("Could not find translation for id: ", translation.id); await oldTranslation.updateAttributes({ Name: translation.name, Description: translation.description }); } }); } catch (e) { if (e instanceof RangeError) throw e; if (e.name === 'Exists') throw e; logger.error(`Error creating role, ${e}`); throw new Error("Unexpected error!"); } const returnTable = await Enduser.app.models.accessControl.getOperationsTable(); operations = returnTable.groups; roles = returnTable.roles; return cb(null, operations, roles); } Enduser.remoteMethod('deleteRole', { http: {verb: 'delete'}, accepts: [ { arg: 'role', type: 'object', required: true } ], returns: [{ arg: 'groups', type: 'array' }, { arg: 'roles', type: 'object' } ] }); Enduser.deleteRole = async (data, cb) => { let operations = []; let roles = {}; try { await Enduser.app.dataSources.db.transaction(async models => { await models.Role.destroyById(data.id); const deleteMappings = await models.RoleMapping.find({ where: { roleId: data.id } }); for (const mapping of deleteMappings) { await models.RoleMapping.destroyById(mapping.id); } }); } catch (e) { logger.error(`Error deleting role, ${e}`); throw new Error("Error!"); } const returnTable = await Enduser.app.models.accessControl.getOperationsTable(); operations = returnTable.groups; roles = returnTable.roles; return cb(null, operations, roles); } Enduser.getAllowedOrganizations = async (accessToken) => { const salesPersons = await Enduser.app.models.salesperson.find({ where: { UserId: accessToken.userId } }); const allowedOrganizations = salesPersons.map(sales => sales.OrganizationId); return allowedOrganizations; } Enduser.remoteMethod('getAllowedOrganizations', { http: {verb: 'get'}, accepts: [ { arg: 'accessToken', type: 'object', http: (ctx) => ctx.req.accessToken } ], returns: [ { arg: 'allowedOrganizations', type: 'object' } ] }); } |