Extending auth providers #1765
Replies: 2 comments 10 replies
-
If I get it right you are trying to create a custom guard right? |
Beta Was this translation helpful? Give feedback.
-
Let's say you want to implement a custom TeamGuard for your Sports related website and on some routes people can only view them if they belong to the team they want to view: import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import NotYourTeamException from 'App/Exceptions/NotYourTeamException'
export default class TeamGuard {
public async handle (ctx: HttpContextContract, next: () => Promise<void>) {
const { auth, params } = ctx
await auth.user!.preload('teams')
const teamId = params.teamId
const team = auth.user?.teams.find(team => team.id === teamId)
const doesntBelongToTeam = !team
if (doesntBelongToTeam) {
throw new NotYourTeamException ()
}
ctx.team = team
await next()
}
} This guard assumes that you will only use it together with the default AuthGuard AND only after the authguard since it relies on "auth.user" to exist. Now we register this guard as a middleware inside the kernel.ts: Server.middleware.registerNamed({
auth: 'App/Middleware/Auth',
team: 'App/Middleware/TeamGuard',
}) Now we can use them for the routes: Route.get('/team/:teamId', 'TeamController.getTeam').middleware([ 'auth', 'team' ]) |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi,
I looked to the documentation to find how to extend auth providers but i can't find it anywere.
I know that the documentation is in progress so if someone can give me some indications or help to build and register a custom provider I could with pleasure offer a pull request to explain this concept in the documentation.
For the moment i juste saw the extend method in the AuthManager class.
Firstly i thought i just had to create a Provider in the providers folder but the schema requested in not the same as the Auth provider.
If someone have allready created a custom guard, i will happy to see it as example.
Thank you for the help you can provide to this discussion !
Beta Was this translation helpful? Give feedback.
All reactions