Permissions Macro Dependent on Better Auth Macro for Role-Based Access Control #1322
-
I’m working on integrating Better Auth with Elysia and want to create a permissions macro that depends on the const app = new Elysia()
.use(permissionsMacro)
.get("/todos", ({ user }) => user, {
permissions: {
todos: ['read']
},
})
.listen(3000); The import { Elysia } from "elysia";
import { auth } from "../auth";
export const betterAuthMacro = new Elysia({ name: "better-auth" })
.mount(auth.handler)
.macro({
auth: {
async resolve({ status, request: { headers } }) {
const session = await auth.api.getSession({
headers,
});
if (!session) return status(401);
return {
user: session.user,
session: session.session,
};
},
},
}); I want the
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
I did exactly this here's my code const permissions = new Elysia({name: 'permissions'})
.macro({
permissions(permissions: Record<string, string[]>) {
return {
async resolve({request: { headers }}) {
try {
const hasPermission = await auth.api.hasPermission({
headers: headers,
body: {
permissions
}
});
if (!hasPermission.success) {
throw new UnauthorizedException('You do not have permission to access this resource');
}
} catch (error) {
if (error instanceof UnauthorizedException) {
// Re-throw permission errors
throw error;
}
throw new InternalServerErrorException();
}
}
}
}
}) and my controller auth: true,
permissions: {
vendor: ['create']
}, |
Beta Was this translation helpful? Give feedback.
I did exactly this
here's my code