Skip to content

feat(performance): use $graphLookup for auth #6556

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 5 commits into
base: alpha
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
178 changes: 152 additions & 26 deletions src/Auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ function Auth({

// Whether this auth could possibly modify the given user id.
// It still could be forbidden via ACLs even if this returns true.
Auth.prototype.isUnauthenticated = function() {
Auth.prototype.isUnauthenticated = function () {
if (this.isMaster) {
return false;
}
Expand All @@ -55,7 +55,7 @@ function nobody(config) {
}

// Returns a promise that resolves to an Auth object
const getAuthForSessionToken = async function({
const getAuthForSessionToken = async function ({
config,
cacheController,
sessionToken,
Expand Down Expand Up @@ -94,11 +94,13 @@ const getAuthForSessionToken = async function({
);
results = (await query.execute()).results;
} else {
results = (await new Parse.Query(Parse.Session)
.limit(1)
.include('user')
.equalTo('sessionToken', sessionToken)
.find({ useMasterKey: true })).map(obj => obj.toJSON());
results = (
await new Parse.Query(Parse.Session)
.limit(1)
.include('user')
.equalTo('sessionToken', sessionToken)
.find({ useMasterKey: true })
).map((obj) => obj.toJSON());
}

if (results.length !== 1 || !results[0]['user']) {
Expand Down Expand Up @@ -134,7 +136,7 @@ const getAuthForSessionToken = async function({
});
};

var getAuthForLegacySessionToken = function({
var getAuthForLegacySessionToken = function ({
config,
sessionToken,
installationId,
Expand All @@ -149,7 +151,7 @@ var getAuthForLegacySessionToken = function({
{ sessionToken },
restOptions
);
return query.execute().then(response => {
return query.execute().then((response) => {
var results = response.results;
if (results.length !== 1) {
throw new Parse.Error(
Expand All @@ -169,8 +171,132 @@ var getAuthForLegacySessionToken = function({
});
};

Auth.prototype.getUserRoles = function () {
if (this.isMaster || !this.user) {
return Promise.resolve([]);
}
if (this.fetchedRoles) {
return Promise.resolve(this.userRoles);
}
if (this.rolePromise) {
return this.rolePromise;
}
this.rolePromise = this._loadUserRolesForAccess();
return this.rolePromise;
};

Auth.prototype._loadUserRolesForAccess = async function () {
if (this.cacheController) {
const cachedRoles = await this.cacheController.role.get(this.user.id);
if (cachedRoles != null) {
this.fetchedRoles = true;
this.userRoles = cachedRoles;
return cachedRoles;
}
}

const { results } = await new RestQuery(
this.config,
master(this.config),
'_Join:users:_Role',
{},
{
pipeline: this._generateRoleGraphPipeline(),
}
).execute();

const { directRoles, childRoles } = results[0] || {
directRoles: [],
childRoles: [],
};

const roles = [...directRoles, ...childRoles];
this.userRoles = roles.map((role) => `role:${role.name}`);
this.fetchedRoles = true;
this.rolePromise = null;
this.cacheRoles();
return this.userRoles;
};

Auth.prototype._generateRoleGraphPipeline = function () {
return [
{
$match: {
relatedId: this.user.id,
},
},
{
$graphLookup: {
from: '_Join:roles:_Role',
startWith: '$owningId',
connectFromField: 'owningId',
connectToField: 'relatedId',
as: 'childRolePath',
},
},
{
$facet: {
directRoles: [
{
$lookup: {
from: '_Role',
localField: 'owningId',
foreignField: '_id',
as: 'Roles',
},
},
{
$unwind: {
path: '$Roles',
},
},
{
$replaceRoot: {
newRoot: {
$ifNull: ['$Roles', { $literal: {} }],
},
},
},
{
$project: {
name: 1,
},
},
],
childRoles: [
{
$lookup: {
from: '_Role',
localField: 'childRolePath.owningId',
foreignField: '_id',
as: 'Roles',
},
},
{
$unwind: {
path: '$Roles',
},
},
{
$replaceRoot: {
newRoot: {
$ifNull: ['$Roles', { $literal: {} }],
},
},
},
{
$project: {
name: 1,
},
},
],
},
},
];
};

// Returns a promise that resolves to an array of role names
Auth.prototype.getUserRoles = function() {
Auth.prototype.getUserRoles = function () {
if (this.isMaster || !this.user) {
return Promise.resolve([]);
}
Expand All @@ -184,7 +310,7 @@ Auth.prototype.getUserRoles = function() {
return this.rolePromise;
};

Auth.prototype.getRolesForUser = async function() {
Auth.prototype.getRolesForUser = async function () {
//Stack all Parse.Role
const results = [];
if (this.config) {
Expand All @@ -201,17 +327,17 @@ Auth.prototype.getRolesForUser = async function() {
'_Role',
restWhere,
{}
).each(result => results.push(result));
).each((result) => results.push(result));
} else {
await new Parse.Query(Parse.Role)
.equalTo('users', this.user)
.each(result => results.push(result.toJSON()), { useMasterKey: true });
.each((result) => results.push(result.toJSON()), { useMasterKey: true });
}
return results;
};

// Iterates through the role tree and compiles a user's roles
Auth.prototype._loadRoles = async function() {
Auth.prototype._loadRoles = async function () {
if (this.cacheController) {
const cachedRoles = await this.cacheController.role.get(this.user.id);
if (cachedRoles != null) {
Expand Down Expand Up @@ -246,7 +372,7 @@ Auth.prototype._loadRoles = async function() {
rolesMap.ids,
rolesMap.names
);
this.userRoles = roleNames.map(r => {
this.userRoles = roleNames.map((r) => {
return 'role:' + r;
});
this.fetchedRoles = true;
Expand All @@ -255,30 +381,30 @@ Auth.prototype._loadRoles = async function() {
return this.userRoles;
};

Auth.prototype.cacheRoles = function() {
Auth.prototype.cacheRoles = function () {
if (!this.cacheController) {
return false;
}
this.cacheController.role.put(this.user.id, Array(...this.userRoles));
return true;
};

Auth.prototype.getRolesByIds = async function(ins) {
Auth.prototype.getRolesByIds = async function (ins) {
const results = [];
// Build an OR query across all parentRoles
if (!this.config) {
await new Parse.Query(Parse.Role)
.containedIn(
'roles',
ins.map(id => {
ins.map((id) => {
const role = new Parse.Object(Parse.Role);
role.id = id;
return role;
})
)
.each(result => results.push(result.toJSON()), { useMasterKey: true });
.each((result) => results.push(result.toJSON()), { useMasterKey: true });
} else {
const roles = ins.map(id => {
const roles = ins.map((id) => {
return {
__type: 'Pointer',
className: '_Role',
Expand All @@ -292,18 +418,18 @@ Auth.prototype.getRolesByIds = async function(ins) {
'_Role',
restWhere,
{}
).each(result => results.push(result));
).each((result) => results.push(result));
}
return results;
};

// Given a list of roleIds, find all the parent roles, returns a promise with all names
Auth.prototype._getAllRolesNamesForRoleIds = function(
Auth.prototype._getAllRolesNamesForRoleIds = function (
roleIDs,
names = [],
queriedRoles = {}
) {
const ins = roleIDs.filter(roleID => {
const ins = roleIDs.filter((roleID) => {
const wasQueried = queriedRoles[roleID] !== true;
queriedRoles[roleID] = true;
return wasQueried;
Expand All @@ -315,7 +441,7 @@ Auth.prototype._getAllRolesNamesForRoleIds = function(
}

return this.getRolesByIds(ins)
.then(results => {
.then((results) => {
// Nothing found
if (!results.length) {
return Promise.resolve(names);
Expand All @@ -338,12 +464,12 @@ Auth.prototype._getAllRolesNamesForRoleIds = function(
queriedRoles
);
})
.then(names => {
.then((names) => {
return Promise.resolve([...new Set(names)]);
});
};

const createSession = function(
const createSession = function (
config,
{ userId, createdWith, installationId, additionalSessionData }
) {
Expand Down
Loading