Roles, permissions and two-factor
Two authorization packages side by side on the same seeded users, and two-factor authentication for one of them.
laravel-bouncer keeps abilities (with ownership and forbids) in its own tables with the bouncer_ prefix,
because laravel-laratrust uses the table names roles and permissions too.
laravel-bouncer
Admins may do everything, editors view, edit and publish every post, Cem may view posts and edit his own, and is forbidden to delete any (a forbid wins over everything).
| User | Roles | view posts | edit posts | edit Cem's post | delete posts | ban users |
|---|---|---|---|---|---|---|
| Ada Lovelace | admin | allowed | allowed | allowed | allowed | allowed |
| Barış Manço | editor | allowed | allowed | allowed | denied | denied |
| Cem Karaca | - | allowed | denied | allowed | denied | denied |
bouncer.allow("editor").to_on(["view", "edit", "publish"], Entity::class("posts")).await?;
bouncer.allow(&cem).to_own(Entity::class("posts")).to("edit").await?;
bouncer.forbid(&cem).to_on("delete", Entity::class("posts")).await?;
bouncer.can(&user, "edit", Entity::new("posts", 3).with("user_id", cem.id)).await?
laravel-laratrust
Roles with permissions, and teams with the strict team check: Cem is an editor only inside the blog
team, so the checks without a team say no for him, and Barış's global role does not count inside the team.
posts.* is a wildcard check.
| User | Roles | role admin | role editor | editor in team blog | posts.edit | posts.delete | posts.* |
|---|---|---|---|---|---|---|---|
| Ada Lovelace | admin | allowed | denied | denied | allowed | allowed | allowed |
| Barış Manço | editor | denied | allowed | denied | allowed | denied | allowed |
| Cem Karaca | - | denied | denied | allowed | denied | denied | denied |
laratrust.user(cem.subject()).in_team("blog").add_role("editor").await?;
laratrust.user(user.subject()).has_role("admin").await?
laratrust.user(user.subject()).in_team("blog").has_role("editor").await?
laratrust.user(user.subject()).is_able_to("posts.*").await?
Two-factor authentication with laravel-google2fa
Set up an authenticator app for ada@example.com: generate a secret, scan the QR code (made with laravel-qrcode), then type the six digit code the app shows. The secret is stored on the demo user.
No secret yet.
let session = laravel::resolve::<TwoFactorSession>().await?; let secret = session.google2fa().generate_secret_key()?; let qr = session.qr_code_inline(&user.email, &secret)?; // data: URI, SVG session.verify_google2fa(&request, &secret, &code)? // then session.login(&request)