Next.js Discord

Discord Forum

How to limit access to authorized users (the resource creator) or admins?

Unanswered
Bumble bee posted this in #help-forum
Open in Discord
Avatar
Bumble beeOP
How would you do it (generally)?

My code looks like this:

export async function POST(request: NextRequest, route: NextRoute) {
    const { slug, name, description } = await request.json()

    const city = await database.city.create({
        data: { slug, name, description }
    })

    const data = { city }

    return NextResponse.json({ data })
}

7 Replies

Avatar
Z4NR34L
I'm using next-auth, where you only need to fetch session from request and check it 😉
Avatar
Bumble beeOP
I also did it like this:

async function allowAction(creator?: User) {
    const currentUser = await getCurrentUser()

    if (creator) {
        return (
            currentUser.role === 'ADMIN' ||
            (currentUser.role === 'PRO_USER' && creator.id === currentUser.id)
        )
    } else {
        return currentUser.role === 'ADMIN' || currentUser.role === 'PRO_USER'
    }
}
i am working with JWT
Avatar
Z4NR34L
what auth package are you using? you can add anything to JWT payload in next-auth without any issue, so when you decrypt session on server-side you will have anything you passed with it
Avatar
Bumble beeOP
mmmh ok
Avatar
Z4NR34L
Please consider marking this thread as answered if thats solved 😄
Avatar
Bumble beeOP
how can I do that ?!!!