8000 How to include auth middleware that handles roles for logged-in users · Issue #426 · go-martini/martini · GitHub
[go: up one dir, main page]

Skip to content

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

Open

Description

@ORESoftware

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?

Activity

  1. ORESoftware commented on Mar 11, 2020

    @ORESoftware
    Author

    So it looks like we can use something like this:

    func LoadUser(permissions<
    4C09
    /span> ...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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      0