Skip to content

Commit

Permalink
Jwt code: hasAccess(X), not canX()
Browse files Browse the repository at this point in the history
  • Loading branch information
arildm committed Mar 26, 2024
1 parent 7364547 commit 753f13b
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 26 deletions.
5 changes: 3 additions & 2 deletions src/auth/auth.composable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { useRouter, useRoute } from "vue-router";
import { checkLogin } from "@/auth/auth";
import api from "@/api/api";
import useSpin from "@/spin/spin.composable";
import { canAdmin, decodeJwt, type JwtSbPayload } from "@/auth/jwtSb";
import { hasAccess, decodeJwt, type JwtSbPayload } from "@/auth/jwtSb";

/**
* JWT request slot.
Expand Down Expand Up @@ -32,7 +32,8 @@ export function useAuth() {
jwt.value ? decodeJwt(jwt.value)?.payload : undefined,
);
const canUserAdmin = computed<boolean>(
() => !!payload.value && canAdmin(payload.value, "other", "mink-app"),
() =>
!!payload.value && hasAccess(payload.value, "other", "mink-app", "ADMIN"),
);
const canUserWrite = computed(() => isAuthenticated.value);
/** Indicates whether a jwt request is currently loading. */
Expand Down
29 changes: 5 additions & 24 deletions src/auth/jwtSb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,43 +37,24 @@ export function decodeJwt(jwt: string): JwtSb | undefined {

export function assertValidPayload(payload: any): payload is JwtSbPayload {
const isValid =
payload &&
payload.scope &&
payload?.scope &&
payload.levels &&
payload.levels.ADMIN &&
payload.levels.WRITE &&
payload.levels.READ;

if (!isValid) {
if (!isValid)
throw new TypeError("Malformed jwt payload: " + JSON.stringify(payload));
}

return true;
}

export function canAdmin(
payload: JwtSbPayload,
resourceType: string,
resourceName: string,
) {
assertValidPayload(payload);
return payload.scope[resourceType]?.[resourceName] >= payload.levels.ADMIN;
}

export function canWrite(
payload: JwtSbPayload,
resourceType: string,
resourceName: string,
) {
assertValidPayload(payload);
return payload.scope[resourceType]?.[resourceName] >= payload.levels.WRITE;
}

export function canRead(
export function hasAccess(
payload: JwtSbPayload,
resourceType: string,
resourceName: string,
level: keyof JwtSbPayload["levels"],
) {
assertValidPayload(payload);
return payload.scope[resourceType]?.[resourceName] >= payload.levels.READ;
return payload.scope[resourceType]?.[resourceName] >= payload.levels[level];
}

0 comments on commit 753f13b

Please sign in to comment.