-
Notifications
You must be signed in to change notification settings - Fork 72
Servant Authorization Example using Type Level Params #172
Comments
@DeepakKapiswe and I talked about this on IRC and it seemed like my short description there was a bit too short. Let's say we're going to have the following data Role = Normal | Moderator | Admin
deriving Ord
data User = User { username :: String, role :: Role } The second approach is about adding a type parameter to newtype UserAtLeast (r :: Role) = UAL User A key function we will need: userAtLeast :: User -> Maybe (UserAtLeast r) But we need to constrain the class KnownRole (r :: Role) where
knownRole :: Proxy r -> Role
instance KnownRole 'Normal where
knownRole _ = Normal
instance KnownRole 'Moderator where
knownRole _ = Moderator
instance KnownRole 'Admin where
knownRole _ = Admin Now we should be able to implement -- requires {-# LANGUAGE ScopedTypeVariables #-}
userAtLeast :: forall (r :: Role). KnownRole r => User -> Maybe (UserAtLeast r)
userAtLeast usr
| minRole <= role usr = Just (UAL usr)
| otherwise = Nothing
where minRole = knownRole (Proxy :: Proxy r) Now, given a You just have to use With servant's general auth machinery, since you're the one constructing the auth check (unlike with servant-auth), you could stick a call to Note: it's not strictly necessary to have If someone has the interest and the time, it'd be great to turn all those comments into a cookbook that discusses authorization/roles at length, illustrating both approaches ideally. |
Thanks a lot @alpmestan for your detailed and swift answer, really helpful.
|
If someone wants to specify the permission on API not only based on ordering but specifically for particular user types / roles
and then we can write our API as: |
Can someone please explain or give a beginner friendly minimal example of Authorization implementation using 2nd Approach of the comment :
described here #73 (comment)
The text was updated successfully, but these errors were encountered: