#426·martini

How to include auth middleware that handles roles for logged-in users

Author: ORESoftwareCreated Mar 11, 2020Updated Mar 11, 2020

We have this right now which works:

go
func (ctr *Controller) Routes(m *martini.ClassicMartini) {
   m.Post("/cp/foo", common.AsJson, common.RequestTimer, ctr.Login)
   m.Get("/cp/bar", common.AsJson, common.RequestTimer, ctr.Logout)
}

we want to do something like this:

go
func (ctr *Controller) Routes(m *martini.ClassicMartini) {
   m.Post("/cp/foo", common.AsJson, common.LoadUser("admin"), common.RequestTimer, ctr.Login)
   m.Get("/cp/bar", common.AsJson, common.LoadUser("admin", "super"), common.RequestTimer, ctr.Logout)
}

basically we want some middleware that can load a user from a JWT and ensure that they have the right role (either admin or super or both etc). The above would work fine, but we want to send a 401 back in the middleware if the user doesn't have the right roles or if the JWT cannot be decrypted.

Is there a way to define middleware for each route, where that middleware can respond, so we don't have to handle that logic at every endpoint?