Updates to latest auth.js generated code

Closes #41
This commit is contained in:
Rob Cameron
2022-03-25 10:51:29 -07:00
parent ee31dc4e0f
commit 7158ea1588

View File

@@ -34,11 +34,6 @@ export const isAuthenticated = () => {
return !!context.currentUser return !!context.currentUser
} }
/**
* When checking role membership, roles can be a single value, a list, or none.
* You can use Prisma enums too (if you're using them for roles), just import your enum type from `@prisma/client`
*/
/** /**
* Checks if the currentUser is authenticated (and assigned one of the given roles) * Checks if the currentUser is authenticated (and assigned one of the given roles)
* *
@@ -47,26 +42,39 @@ export const isAuthenticated = () => {
* @returns {boolean} - Returns true if the currentUser is logged in and assigned one of the given roles, * @returns {boolean} - Returns true if the currentUser is logged in and assigned one of the given roles,
* or when no roles are provided to check against. Otherwise returns false. * or when no roles are provided to check against. Otherwise returns false.
*/ */
export const hasRole = ({ roles }) => { export const hasRole = (roles) => {
if (!isAuthenticated()) { if (!isAuthenticated()) {
return false return false
} }
// If your User model includes roles, uncomment the role checks on currentUser const currentUserRoles = context.currentUser?.roles
if (roles) {
if (Array.isArray(roles)) {
// return context.currentUser.roles?.some((r) => roles.includes(r))
}
if (typeof roles === 'string') { if (typeof roles === 'string') {
// return context.currentUser.roles?.includes(roles) if (typeof currentUserRoles === 'string') {
// roles to check is a string, currentUser.roles is a string
return currentUserRoles === roles
} else if (Array.isArray(currentUserRoles)) {
// roles to check is a string, currentUser.roles is an array
return currentUserRoles?.some((allowedRole) => roles === allowedRole)
}
}
if (Array.isArray(roles)) {
if (Array.isArray(currentUserRoles)) {
// roles to check is an array, currentUser.roles is an array
return currentUserRoles?.some((allowedRole) =>
roles.includes(allowedRole)
)
} else if (typeof context.currentUser.roles === 'string') {
// roles to check is an array, currentUser.roles is a string
return roles.some(
(allowedRole) => context.currentUser?.roles === allowedRole
)
}
} }
// roles not found // roles not found
return false return false
}
return true
} }
/** /**
@@ -88,7 +96,7 @@ export const requireAuth = ({ roles }) => {
throw new AuthenticationError("You don't have permission to do that.") throw new AuthenticationError("You don't have permission to do that.")
} }
if (!hasRole({ roles })) { if (roles && !hasRole(roles)) {
throw new ForbiddenError("You don't have access to do that.") throw new ForbiddenError("You don't have access to do that.")
} }
} }