BVB Source Codes

parse-server Show Auth.js Source code

Return Download parse-server: download Auth.js Source code - Download parse-server Source code - Type:.js
  1. var Parse = require('parse/node').Parse;
  2. var RestQuery = require('./RestQuery');
  3.  
  4. // An Auth object tells you who is requesting something and whether
  5. // the master key was used.
  6. // userObject is a Parse.User and can be null if there's no user.
  7. function Auth({ config, isMaster = false, user, installationId } = {}) {
  8.   this.config = config;
  9.   this.installationId = installationId;
  10.   this.isMaster = isMaster;
  11.   this.user = user;
  12.  
  13.   // Assuming a users roles won't change during a single request, we'll
  14.   // only load them once.
  15.   this.userRoles = [];
  16.   this.fetchedRoles = false;
  17.   this.rolePromise = null;
  18. }
  19.  
  20. // Whether this auth could possibly modify the given user id.
  21. // It still could be forbidden via ACLs even if this returns true.
  22. Auth.prototype.couldUpdateUserId = function(userId) {
  23.   if (this.isMaster) {
  24.     return true;
  25.   }
  26.   if (this.user && this.user.id === userId) {
  27.     return true;
  28.   }
  29.   return false;
  30. };
  31.  
  32. // A helper to get a master-level Auth object
  33. function master(config) {
  34.   return new Auth({ config, isMaster: true });
  35. }
  36.  
  37. // A helper to get a nobody-level Auth object
  38. function nobody(config) {
  39.   return new Auth({ config, isMaster: false });
  40. }
  41.  
  42.  
  43. // Returns a promise that resolves to an Auth object
  44. var getAuthForSessionToken = function({ config, sessionToken, installationId } = {}) {
  45.   return config.cacheController.user.get(sessionToken).then((userJSON) => {
  46.     if (userJSON) {
  47.       const cachedUser = Parse.Object.fromJSON(userJSON);
  48.       return Promise.resolve(new Auth({config, isMaster: false, installationId, user: cachedUser}));
  49.     }
  50.  
  51.     var restOptions = {
  52.       limit: 1,
  53.       include: 'user'
  54.     };
  55.  
  56.     var query = new RestQuery(config, master(config), '_Session', {sessionToken}, restOptions);
  57.     return query.execute().then((response) => {
  58.       var results = response.results;
  59.       if (results.length !== 1 || !results[0]['user']) {
  60.         throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'invalid session token');
  61.       }
  62.  
  63.       var now = new Date(),
  64.         expiresAt = results[0].expiresAt ? new Date(results[0].expiresAt.iso) : undefined;
  65.       if (expiresAt < now) {
  66.         throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN,
  67.           'Session token is expired.');
  68.       }
  69.       var obj = results[0]['user'];
  70.       delete obj.password;
  71.       obj['className'] = '_User';
  72.       obj['sessionToken'] = sessionToken;
  73.       config.cacheController.user.put(sessionToken, obj);
  74.       const userObject = Parse.Object.fromJSON(obj);
  75.       return new Auth({config, isMaster: false, installationId, user: userObject});
  76.     });
  77.   });
  78. };
  79.  
  80. var getAuthForLegacySessionToken = function({config, sessionToken, installationId } = {}) {
  81.   var restOptions = {
  82.     limit: 1
  83.   };
  84.   var query = new RestQuery(config, master(config), '_User', { sessionToken: sessionToken}, restOptions);
  85.   return query.execute().then((response) => {
  86.     var results = response.results;
  87.     if (results.length !== 1) {
  88.       throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'invalid legacy session token');
  89.     }
  90.     const obj = results[0];
  91.     obj.className = '_User';
  92.     const userObject = Parse.Object.fromJSON(obj);
  93.     return new Auth({config, isMaster: false, installationId, user: userObject});
  94.   });
  95. }
  96.  
  97. // Returns a promise that resolves to an array of role names
  98. Auth.prototype.getUserRoles = function() {
  99.   if (this.isMaster || !this.user) {
  100.     return Promise.resolve([]);
  101.   }
  102.   if (this.fetchedRoles) {
  103.     return Promise.resolve(this.userRoles);
  104.   }
  105.   if (this.rolePromise) {
  106.     return this.rolePromise;
  107.   }
  108.   this.rolePromise = this._loadRoles();
  109.   return this.rolePromise;
  110. };
  111.  
  112. // Iterates through the role tree and compiles a users roles
  113. Auth.prototype._loadRoles = function() {
  114.   var cacheAdapter = this.config.cacheController;
  115.   return cacheAdapter.role.get(this.user.id).then((cachedRoles) => {
  116.     if (cachedRoles != null) {
  117.       this.fetchedRoles = true;
  118.       this.userRoles = cachedRoles;
  119.       return Promise.resolve(cachedRoles);
  120.     }
  121.  
  122.     var restWhere = {
  123.       'users': {
  124.         __type: 'Pointer',
  125.         className: '_User',
  126.         objectId: this.user.id
  127.       }
  128.     };
  129.     // First get the role ids this user is directly a member of
  130.     var query = new RestQuery(this.config, master(this.config), '_Role', restWhere, {});
  131.     return query.execute().then((response) => {
  132.       var results = response.results;
  133.       if (!results.length) {
  134.         this.userRoles = [];
  135.         this.fetchedRoles = true;
  136.         this.rolePromise = null;
  137.  
  138.         cacheAdapter.role.put(this.user.id, this.userRoles);
  139.         return Promise.resolve(this.userRoles);
  140.       }
  141.       var rolesMap = results.reduce((m, r) => {
  142.         m.names.push(r.name);
  143.         m.ids.push(r.objectId);
  144.         return m;
  145.       }, {ids: [], names: []});
  146.  
  147.       // run the recursive finding
  148.       return this._getAllRolesNamesForRoleIds(rolesMap.ids, rolesMap.names)
  149.         .then((roleNames) => {
  150.           this.userRoles = roleNames.map((r) => {
  151.             return 'role:' + r;
  152.           });
  153.           this.fetchedRoles = true;
  154.           this.rolePromise = null;
  155.  
  156.           cacheAdapter.role.put(this.user.id, this.userRoles);
  157.           return Promise.resolve(this.userRoles);
  158.         });
  159.     });
  160.   });
  161. };
  162.  
  163. // Given a list of roleIds, find all the parent roles, returns a promise with all names
  164. Auth.prototype._getAllRolesNamesForRoleIds = function(roleIDs, names = [], queriedRoles = {}) {
  165.   const ins = roleIDs.filter((roleID) => {
  166.     return queriedRoles[roleID] !== true;
  167.   }).map((roleID) => {
  168.     // mark as queried
  169.     queriedRoles[roleID] = true;
  170.     return {
  171.       __type: 'Pointer',
  172.       className: '_Role',
  173.       objectId: roleID
  174.     }
  175.   });
  176.  
  177.   // all roles are accounted for, return the names
  178.   if (ins.length == 0) {
  179.     return Promise.resolve([...new Set(names)]);
  180.   }
  181.   // Build an OR query across all parentRoles
  182.   let restWhere;
  183.   if (ins.length == 1) {
  184.     restWhere = { 'roles': ins[0] };
  185.   } else {
  186.     restWhere = { 'roles': { '$in': ins }}
  187.   }
  188.   const query = new RestQuery(this.config, master(this.config), '_Role', restWhere, {});
  189.   return query.execute().then((response) => {
  190.     var results = response.results;
  191.     // Nothing found
  192.     if (!results.length) {
  193.       return Promise.resolve(names);
  194.     }
  195.     // Map the results with all Ids and names
  196.     const resultMap = results.reduce((memo, role) => {
  197.       memo.names.push(role.name);
  198.       memo.ids.push(role.objectId);
  199.       return memo;
  200.     }, {ids: [], names: []});
  201.     // store the new found names
  202.     names = names.concat(resultMap.names);
  203.     // find the next ones, circular roles will be cut
  204.     return this._getAllRolesNamesForRoleIds(resultMap.ids, names, queriedRoles)
  205.   }).then((names) => {
  206.     return Promise.resolve([...new Set(names)])
  207.   })
  208. }
  209.  
  210. module.exports = {
  211.   Auth: Auth,
  212.   master: master,
  213.   nobody: nobody,
  214.   getAuthForSessionToken,
  215.   getAuthForLegacySessionToken
  216. };
  217.  
downloadAuth.js Source code - Download parse-server Source code
Related Source Codes/Software:
react-boilerplate - 2017-06-07
webtorrent - Streaming torrent client for the web ... 2017-06-06
machine-learning-for-software-engineers - A complete daily plan for studying to become a mac... 2017-06-06
upterm - A terminal emulator for the 21st century. 2017-06-06
lottie-android - Render After Effects animations natively on Androi... 2017-06-07
AsyncDisplayKit - Smooth asynchronous user interfaces for iOS apps. ... 2017-06-07
ionicons - The premium icon font for Ionic ... 2017-06-07
storybook - 2017-06-07
prettier - Prettier is an opinionated JavaScript formatter. ... 2017-06-08
CRYENGINE - CRYENGINE is a powerful real-time game development... 2017-06-11
postal - 2017-06-11
reactide - Reactide is the first dedicated IDE for React web ... 2017-06-11
rkt - rkt is a pod-native container engine for Linux. It... 2017-06-11
uWebSockets - Tiny WebSockets https://for... 2017-06-11
realworld - TodoMVC for the RealWorld - Exemplary fullstack Me... 2017-06-11
goreplay - GoReplay is an open-source tool for capturing and ... 2017-06-10
pyenv - Simple Python version management 2017-06-10
redux-saga - An alternative side effect model for Redux apps ... 2017-06-10
angular-starter - 2017-06-10

 Back to top