Availability based on permissions
This commit is contained in:
22
frontend/lib/getMe.ts
Normal file
22
frontend/lib/getMe.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { cache } from "react";
|
||||
import { API_URL } from "./constants";
|
||||
import { ApiResponse } from "@/types/types";
|
||||
import IUser from "@/interfaces/IUser";
|
||||
import { cookies } from "next/headers";
|
||||
|
||||
const getMe = cache(
|
||||
async (sessionCookie?: string): Promise<ApiResponse<IUser> | null> => {
|
||||
if (!sessionCookie) {
|
||||
const store = await cookies();
|
||||
const token = store.get("auth_token")?.value;
|
||||
if (!token) return null;
|
||||
sessionCookie = token;
|
||||
}
|
||||
const res = await fetch(`${API_URL}/users/me`, {
|
||||
headers: { Authorization: `Bearer ${sessionCookie}` },
|
||||
});
|
||||
return await res.json();
|
||||
},
|
||||
);
|
||||
|
||||
export default getMe;
|
||||
25
frontend/lib/hasPermissions.ts
Normal file
25
frontend/lib/hasPermissions.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import { Role } from "@/types/types";
|
||||
|
||||
export default function hasPermissions(
|
||||
roles: Role[],
|
||||
permissions: { [key: string]: string[] },
|
||||
) {
|
||||
const permissionsSet: Map<string, null> = new Map();
|
||||
for (const role of roles) {
|
||||
if (!role.permissions) continue;
|
||||
for (const perm of role?.permissions) {
|
||||
const key = perm.resource + ":" + perm.action;
|
||||
permissionsSet.set(key, null);
|
||||
}
|
||||
}
|
||||
|
||||
for (const [perm, actions] of Object.entries(permissions)) {
|
||||
for (const action of actions) {
|
||||
if (!permissionsSet.has(perm + ":" + action)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
Reference in New Issue
Block a user