Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
ORESoftware opened this issue Mar 11, 2020 · 1 comment
Open

Comments

@ORESoftware
Copy link

ORESoftware commented Mar 11, 2020

We have this right now which works:

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:

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?

@ORESoftware
Copy link
Author

ORESoftware commented Mar 11, 2020

So it looks like we can use something like this:

func LoadUser(permissions ...string) {
    return func(req *http.Request, res http.ResponseWriter) {
             var u UserModel;
             err := jwt.Decrypt(req.Header.Get("Authorization"), pwd, &u)
             if err != nil {
                http.Error(res, Response{"ok": 0, "error": "Forbidden"}.String(), http.StatusForbidden)
                return;
             }
             m.Map(&u)
    }
}

is that about right?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant