NORY-36: add permission check to dashboard middleware
This commit is contained in:
parent
66775a001e
commit
9ff25c4a6e
1 changed files with 33 additions and 6 deletions
|
@ -1,13 +1,13 @@
|
||||||
import { NextResponse } from 'next/server';
|
import { NextRequest, NextResponse } from 'next/server';
|
||||||
import { cookies } from 'next/headers';
|
import { cookies } from 'next/headers';
|
||||||
import { getFrontendApi } from '@/ory/sdk/server';
|
import { getFrontendApi, getPermissionApi } from '@/ory/sdk/server';
|
||||||
|
|
||||||
export async function middleware() {
|
export async function middleware(request: NextRequest) {
|
||||||
|
|
||||||
const api = await getFrontendApi();
|
const frontendApi = await getFrontendApi();
|
||||||
const cookie = await cookies();
|
const cookie = await cookies();
|
||||||
|
|
||||||
const session = await api
|
const session = await frontendApi
|
||||||
.toSession({ cookie: 'ory_kratos_session=' + cookie.get('ory_kratos_session')?.value })
|
.toSession({ cookie: 'ory_kratos_session=' + cookie.get('ory_kratos_session')?.value })
|
||||||
.then((response) => response.data)
|
.then((response) => response.data)
|
||||||
.catch(() => null);
|
.catch(() => null);
|
||||||
|
@ -25,7 +25,34 @@ export async function middleware() {
|
||||||
return NextResponse.redirect(url);
|
return NextResponse.redirect(url);
|
||||||
}
|
}
|
||||||
|
|
||||||
return NextResponse.next();
|
if (request.nextUrl.pathname === '/unauthorised') {
|
||||||
|
return NextResponse.next();
|
||||||
|
}
|
||||||
|
|
||||||
|
const permissionApi = await getPermissionApi();
|
||||||
|
const isAdmin = await permissionApi.checkPermission({
|
||||||
|
namespace: 'roles',
|
||||||
|
object: 'admin',
|
||||||
|
relation: 'member',
|
||||||
|
subjectId: session!.identity!.id,
|
||||||
|
})
|
||||||
|
.then(({ data: { allowed } }) => {
|
||||||
|
console.log('is_admin', session!.identity!.id, allowed);
|
||||||
|
return allowed;
|
||||||
|
})
|
||||||
|
.catch((response) => {
|
||||||
|
console.log('is_admin', session!.identity!.id, response, 'check failed');
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (isAdmin) {
|
||||||
|
return NextResponse.next();
|
||||||
|
} else {
|
||||||
|
console.log('MISSING PERMISSION');
|
||||||
|
const url = `${process.env.NEXT_PUBLIC_DASHBOARD_NODE_URL}/unauthorised`;
|
||||||
|
console.log('REDIRECT TO', url);
|
||||||
|
return NextResponse.redirect(url!);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const config = {
|
export const config = {
|
||||||
|
|
Loading…
Add table
Reference in a new issue