{"id":24109651,"url":"https://github.com/xyproto/permissions","last_synced_at":"2025-05-07T11:25:37.866Z","repository":{"id":265937922,"uuid":"873540504","full_name":"xyproto/permissions","owner":"xyproto","description":"  :closed_lock_with_key: Middleware for keeping track of users, login states and permissions","archived":false,"fork":false,"pushed_at":"2024-12-01T16:14:21.000Z","size":17067,"stargazers_count":6,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-01-11T01:00:33.442Z","etag":null,"topics":["bcrypt","middleware","permissions","redis","sessions","user-auth"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/xyproto.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":["xyproto","jaredfolkins"],"patreon":null,"open_collective":null,"ko_fi":null,"tidelift":null,"community_bridge":null,"liberapay":null,"issuehunt":null,"otechie":null,"custom":null}},"created_at":"2024-10-16T10:41:18.000Z","updated_at":"2024-12-27T02:07:55.000Z","dependencies_parsed_at":"2024-12-01T17:28:05.602Z","dependency_job_id":"35cc606a-fe3f-4c78-90e9-31d6698e35a1","html_url":"https://github.com/xyproto/permissions","commit_stats":null,"previous_names":["xyproto/permissions"],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xyproto%2Fpermissions","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xyproto%2Fpermissions/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xyproto%2Fpermissions/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xyproto%2Fpermissions/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/xyproto","download_url":"https://codeload.github.com/xyproto/permissions/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252867248,"owners_count":21816639,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bcrypt","middleware","permissions","redis","sessions","user-auth"],"created_at":"2025-01-11T01:00:49.681Z","updated_at":"2025-05-07T11:25:37.845Z","avatar_url":"https://github.com/xyproto.png","language":"Go","funding_links":["https://github.com/sponsors/xyproto","https://github.com/sponsors/jaredfolkins"],"categories":["Authentication and Authorization","Authentication and OAuth"],"sub_categories":[],"readme":"# Permissions [![Build](https://github.com/xyproto/permissions/actions/workflows/build.yml/badge.svg)](https://github.com/xyproto/permissions/actions/workflows/build.yml) [![GoDoc](https://godoc.org/github.com/xyproto/permissions?status.svg)](http://godoc.org/github.com/xyproto/permissions) [![Go Report Card](https://goreportcard.com/badge/github.com/xyproto/permissions)](https://goreportcard.com/report/github.com/xyproto/permissions)\n\nMiddleware for keeping track of users, login states and permissions.\n\nThis is the continuation of [permissions2](https://github.com/xyproto/permissions2).\n\n## Online API Documentation\n\n[godoc.org](http://godoc.org/github.com/xyproto/permissions)\n\n## Features and limitations\n\n* Uses secure cookies and stores user information in a Redis database.\n* Suitable for running a local Redis server, registering/confirming users and managing public/user/admin pages.\n* Also supports connecting to remote Redis servers.\n* Does not support SQL databases. For MariaDB/MySQL support, look into [permissionsql](https://github.com/xyproto/permissionsql).\n* For Bolt database support (no database host needed, uses a file), look into [permissionbolt](https://github.com/xyproto/permissionbolt).\n* For PostgreSQL database support (using the HSTORE feature), look into [pstore](https://github.com/xyproto/pstore).\n* Supports registration and confirmation via generated confirmation codes.\n* Tries to keep things simple.\n* Only supports *public*, *user* and *admin* permissions out of the box, but offers functionality for implementing more fine grained permissions, if so desired.\n* The default permissions can be cleared with the `Clear()` function.\n* Supports [Chi](https://github.com/go-chi/chi), [Negroni](https://github.com/urfave/negroni), [Martini](https://github.com/go-martini/martini), [Gin](https://github.com/gin-gonic/gin), [Goji](https://github.com/zenazn/goji) and plain `net/http`.\n* Should also work with other frameworks, since the standard `http.HandlerFunc` is used everywhere.\n\n## Requirements\n\n* Redis \u003e= 2.6.12 (or an open source Redis clone)\n* Go \u003e= 1.21\n\n## Examples\n\nThere is more information after the examples.\n\n### Example for [Chi](https://github.com/go-chi/chi)\n\n~~~ go\npackage main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"net/http\"\n    \"strings\"\n\n    \"github.com/go-chi/chi/v5\"\n    \"github.com/xyproto/permissions\"\n)\n\nfunc main() {\n    m := chi.NewRouter()\n\n    // New permissions middleware\n    perm, err := permissions.New2()\n    if err != nil {\n        log.Fatalln(err)\n    }\n\n    // Blank slate, no default permissions\n    //perm.Clear()\n\n    // Get the userstate, used in the handlers below\n    userstate := perm.UserState()\n\n    // Set up the middleware handler for Chi\n    m.Use(perm.Middleware)\n\n    m.Get(\"/\", func(w http.ResponseWriter, req *http.Request) {\n        fmt.Fprintf(w, \"Has user bob: %v\\n\", userstate.HasUser(\"bob\"))\n        fmt.Fprintf(w, \"Logged in on server: %v\\n\", userstate.IsLoggedIn(\"bob\"))\n        fmt.Fprintf(w, \"Is confirmed: %v\\n\", userstate.IsConfirmed(\"bob\"))\n        fmt.Fprintf(w, \"Username stored in cookies (or blank): %v\\n\", userstate.Username(req))\n        fmt.Fprintf(w, \"Current user is logged in, has a valid cookie and *user rights*: %v\\n\", userstate.UserRights(req))\n        fmt.Fprintf(w, \"Current user is logged in, has a valid cookie and *admin rights*: %v\\n\", userstate.AdminRights(req))\n        fmt.Fprintf(w, \"\\nTry: /register, /confirm, /remove, /login, /logout, /makeadmin, /clear, /data and /admin\")\n    })\n\n    m.Get(\"/register\", func(w http.ResponseWriter, r *http.Request) {\n        userstate.AddUser(\"bob\", \"hunter1\", \"bob@zombo.com\")\n        fmt.Fprintf(w, \"User bob was created: %v\\n\", userstate.HasUser(\"bob\"))\n    })\n\n    m.Get(\"/confirm\", func(w http.ResponseWriter, r *http.Request) {\n        userstate.MarkConfirmed(\"bob\")\n        fmt.Fprintf(w, \"User bob was confirmed: %v\\n\", userstate.IsConfirmed(\"bob\"))\n    })\n\n    m.Get(\"/remove\", func(w http.ResponseWriter, r *http.Request) {\n        userstate.RemoveUser(\"bob\")\n        fmt.Fprintf(w, \"User bob was removed: %v\\n\", !userstate.HasUser(\"bob\"))\n    })\n\n    m.Get(\"/login\", func(w http.ResponseWriter, r *http.Request) {\n        userstate.Login(w, \"bob\")\n        fmt.Fprintf(w, \"bob is now logged in: %v\\n\", userstate.IsLoggedIn(\"bob\"))\n    })\n\n    m.Get(\"/logout\", func(w http.ResponseWriter, r *http.Request) {\n        userstate.Logout(\"bob\")\n        fmt.Fprintf(w, \"bob is now logged out: %v\\n\", !userstate.IsLoggedIn(\"bob\"))\n    })\n\n    m.Get(\"/makeadmin\", func(w http.ResponseWriter, r *http.Request) {\n        userstate.SetAdminStatus(\"bob\")\n        fmt.Fprintf(w, \"bob is now administrator: %v\\n\", userstate.IsAdmin(\"bob\"))\n    })\n\n    m.Get(\"/clear\", func(w http.ResponseWriter, r *http.Request) {\n        userstate.ClearCookie(w)\n        fmt.Fprintf(w, \"Clearing cookie\")\n    })\n\n    m.Get(\"/data\", func(w http.ResponseWriter, r *http.Request) {\n        fmt.Fprintf(w, \"user page that only logged in users must see!\")\n    })\n\n    m.Get(\"/admin\", func(w http.ResponseWriter, r *http.Request) {\n        fmt.Fprintf(w, \"super secret information that only logged in administrators must see!\\n\\n\")\n        if usernames, err := userstate.AllUsernames(); err == nil {\n            fmt.Fprintf(w, \"list of all users: \"+strings.Join(usernames, \", \"))\n        }\n    })\n\n    // Custom handler for when permissions are denied\n    perm.SetDenyFunction(func(w http.ResponseWriter, req *http.Request) {\n        http.Error(w, \"Permission denied!\", http.StatusForbidden)\n    })\n\n    // Serve\n    http.ListenAndServe(\":3000\", m)\n}\n~~~\n\n### Example for [Negroni](https://github.com/urfave/negroni)\n\n~~~ go\npackage main\n\nimport (\n    \"fmt\"\n    \"net/http\"\n    \"strings\"\n    \"log\"\n\n    \"github.com/urfave/negroni\"\n    \"github.com/xyproto/permissions\"\n)\n\nfunc main() {\n    n := negroni.Classic()\n    mux := http.NewServeMux()\n\n    // New permissions middleware\n    perm, err := permissions.New2()\n    if err != nil {\n        log.Fatalln(err)\n    }\n\n    // Blank slate, no default permissions\n    //perm.Clear()\n\n    // Get the userstate, used in the handlers below\n    userstate := perm.UserState()\n\n    mux.HandleFunc(\"/\", func(w http.ResponseWriter, req *http.Request) {\n        fmt.Fprintf(w, \"Has user bob: %v\\n\", userstate.HasUser(\"bob\"))\n        fmt.Fprintf(w, \"Logged in on server: %v\\n\", userstate.IsLoggedIn(\"bob\"))\n        fmt.Fprintf(w, \"Is confirmed: %v\\n\", userstate.IsConfirmed(\"bob\"))\n        fmt.Fprintf(w, \"Username stored in cookies (or blank): %v\\n\", userstate.Username(req))\n        fmt.Fprintf(w, \"Current user is logged in, has a valid cookie and *user rights*: %v\\n\", userstate.UserRights(req))\n        fmt.Fprintf(w, \"Current user is logged in, has a valid cookie and *admin rights*: %v\\n\", userstate.AdminRights(req))\n        fmt.Fprintf(w, \"\\nTry: /register, /confirm, /remove, /login, /logout, /makeadmin, /clear, /data and /admin\")\n    })\n\n    mux.HandleFunc(\"/register\", func(w http.ResponseWriter, req *http.Request) {\n        userstate.AddUser(\"bob\", \"hunter1\", \"bob@zombo.com\")\n        fmt.Fprintf(w, \"User bob was created: %v\\n\", userstate.HasUser(\"bob\"))\n    })\n\n    mux.HandleFunc(\"/confirm\", func(w http.ResponseWriter, req *http.Request) {\n        userstate.MarkConfirmed(\"bob\")\n        fmt.Fprintf(w, \"User bob was confirmed: %v\\n\", userstate.IsConfirmed(\"bob\"))\n    })\n\n    mux.HandleFunc(\"/remove\", func(w http.ResponseWriter, req *http.Request) {\n        userstate.RemoveUser(\"bob\")\n        fmt.Fprintf(w, \"User bob was removed: %v\\n\", !userstate.HasUser(\"bob\"))\n    })\n\n    mux.HandleFunc(\"/login\", func(w http.ResponseWriter, req *http.Request) {\n        userstate.Login(w, \"bob\")\n        fmt.Fprintf(w, \"bob is now logged in: %v\\n\", userstate.IsLoggedIn(\"bob\"))\n    })\n\n    mux.HandleFunc(\"/logout\", func(w http.ResponseWriter, req *http.Request) {\n        userstate.Logout(\"bob\")\n        fmt.Fprintf(w, \"bob is now logged out: %v\\n\", !userstate.IsLoggedIn(\"bob\"))\n    })\n\n    mux.HandleFunc(\"/makeadmin\", func(w http.ResponseWriter, req *http.Request) {\n        userstate.SetAdminStatus(\"bob\")\n        fmt.Fprintf(w, \"bob is now administrator: %v\\n\", userstate.IsAdmin(\"bob\"))\n    })\n\n    mux.HandleFunc(\"/clear\", func(w http.ResponseWriter, req *http.Request) {\n        userstate.ClearCookie(w)\n        fmt.Fprintf(w, \"Clearing cookie\")\n    })\n\n    mux.HandleFunc(\"/data\", func(w http.ResponseWriter, req *http.Request) {\n        fmt.Fprintf(w, \"user page that only logged in users must see!\")\n    })\n\n    mux.HandleFunc(\"/admin\", func(w http.ResponseWriter, req *http.Request) {\n        fmt.Fprintf(w, \"super secret information that only logged in administrators must see!\\n\\n\")\n        if usernames, err := userstate.AllUsernames(); err == nil {\n            fmt.Fprintf(w, \"list of all users: \"+strings.Join(usernames, \", \"))\n        }\n    })\n\n    // Custom handler for when permissions are denied\n    perm.SetDenyFunction(func(w http.ResponseWriter, req *http.Request) {\n        http.Error(w, \"Permission denied!\", http.StatusForbidden)\n    })\n\n    // Enable the permissions middleware\n    n.Use(perm)\n\n    // Use mux for routing, this goes last\n    n.UseHandler(mux)\n\n    // Serve\n    n.Run(\":3000\")\n}\n~~~\n\n### Example for [Martini](https://github.com/go-martini/martini)\n\n~~~ go\npackage main\n\nimport (\n    \"fmt\"\n    \"net/http\"\n    \"strings\"\n    \"log\"\n\n    \"github.com/go-martini/martini\"\n    \"github.com/xyproto/permissions\"\n)\n\nfunc main() {\n    m := martini.Classic()\n\n    // New permissions middleware\n    perm, err := permissions.New2()\n    if err != nil {\n        log.Fatalln(err)\n    }\n\n    // Blank slate, no default permissions\n    //perm.Clear()\n\n    // Get the userstate, used in the handlers below\n    userstate := perm.UserState()\n\n    m.Get(\"/\", func(w http.ResponseWriter, req *http.Request) {\n        fmt.Fprintf(w, \"Has user bob: %v\\n\", userstate.HasUser(\"bob\"))\n        fmt.Fprintf(w, \"Logged in on server: %v\\n\", userstate.IsLoggedIn(\"bob\"))\n        fmt.Fprintf(w, \"Is confirmed: %v\\n\", userstate.IsConfirmed(\"bob\"))\n        fmt.Fprintf(w, \"Username stored in cookies (or blank): %v\\n\", userstate.Username(req))\n        fmt.Fprintf(w, \"Current user is logged in, has a valid cookie and *user rights*: %v\\n\", userstate.UserRights(req))\n        fmt.Fprintf(w, \"Current user is logged in, has a valid cookie and *admin rights*: %v\\n\", userstate.AdminRights(req))\n        fmt.Fprintf(w, \"\\nTry: /register, /confirm, /remove, /login, /logout, /makeadmin, /clear, /data and /admin\")\n    })\n\n    m.Get(\"/register\", func(w http.ResponseWriter) {\n        userstate.AddUser(\"bob\", \"hunter1\", \"bob@zombo.com\")\n        fmt.Fprintf(w, \"User bob was created: %v\\n\", userstate.HasUser(\"bob\"))\n    })\n\n    m.Get(\"/confirm\", func(w http.ResponseWriter) {\n        userstate.MarkConfirmed(\"bob\")\n        fmt.Fprintf(w, \"User bob was confirmed: %v\\n\", userstate.IsConfirmed(\"bob\"))\n    })\n\n    m.Get(\"/remove\", func(w http.ResponseWriter) {\n        userstate.RemoveUser(\"bob\")\n        fmt.Fprintf(w, \"User bob was removed: %v\\n\", !userstate.HasUser(\"bob\"))\n    })\n\n    m.Get(\"/login\", func(w http.ResponseWriter) {\n        userstate.Login(w, \"bob\")\n        fmt.Fprintf(w, \"bob is now logged in: %v\\n\", userstate.IsLoggedIn(\"bob\"))\n    })\n\n    m.Get(\"/logout\", func(w http.ResponseWriter) {\n        userstate.Logout(\"bob\")\n        fmt.Fprintf(w, \"bob is now logged out: %v\\n\", !userstate.IsLoggedIn(\"bob\"))\n    })\n\n    m.Get(\"/makeadmin\", func(w http.ResponseWriter) {\n        userstate.SetAdminStatus(\"bob\")\n        fmt.Fprintf(w, \"bob is now administrator: %v\\n\", userstate.IsAdmin(\"bob\"))\n    })\n\n    m.Get(\"/clear\", func(w http.ResponseWriter) {\n        userstate.ClearCookie(w)\n        fmt.Fprintf(w, \"Clearing cookie\")\n    })\n\n    m.Get(\"/data\", func(w http.ResponseWriter) {\n        fmt.Fprintf(w, \"user page that only logged in users must see!\")\n    })\n\n    m.Get(\"/admin\", func(w http.ResponseWriter) {\n        fmt.Fprintf(w, \"super secret information that only logged in administrators must see!\\n\\n\")\n        if usernames, err := userstate.AllUsernames(); err == nil {\n            fmt.Fprintf(w, \"list of all users: \"+strings.Join(usernames, \", \"))\n        }\n    })\n\n    // Set up a middleware handler for Martini, with a custom \"permission denied\" message.\n    permissionHandler := func(w http.ResponseWriter, req *http.Request, c martini.Context) {\n        // Check if the user has the right admin/user rights\n        if perm.Rejected(w, req) {\n            // Deny the request\n            http.Error(w, \"Permission denied!\", http.StatusForbidden)\n            // Reject the request by not calling the next handler below\n            return\n        }\n        // Call the next middleware handler\n        c.Next()\n    }\n\n    // Enable the permissions middleware\n    m.Use(permissionHandler)\n\n    // Serve\n    m.Run()\n}\n~~~\n\n### Example for [Gin](https://github.com/gin-gonic/gin)\n\n~~~ go\npackage main\n\nimport (\n    \"fmt\"\n    \"net/http\"\n    \"strings\"\n    \"log\"\n\n    \"github.com/gin-gonic/gin\"\n    \"github.com/xyproto/permissions\"\n)\n\nfunc main() {\n    g := gin.New()\n\n    // New permissions middleware\n    perm, err := permissions.New2()\n    if err != nil {\n        log.Fatalln(err)\n    }\n\n    // Blank slate, no default permissions\n    //perm.Clear()\n\n    // Set up a middleware handler for Gin, with a custom \"permission denied\" message.\n    permissionHandler := func(c *gin.Context) {\n        // Check if the user has the right admin/user rights\n        if perm.Rejected(c.Writer, c.Request) {\n            // Deny the request, don't call other middleware handlers\n            c.AbortWithStatus(http.StatusForbidden)\n            fmt.Fprint(c.Writer, \"Permission denied!\")\n            return\n        }\n        // Call the next middleware handler\n        c.Next()\n    }\n\n    // Logging middleware\n    g.Use(gin.Logger())\n\n    // Enable the permissions middleware, must come before recovery\n    g.Use(permissionHandler)\n\n    // Recovery middleware\n    g.Use(gin.Recovery())\n\n    // Get the userstate, used in the handlers below\n    userstate := perm.UserState()\n\n    g.GET(\"/\", func(c *gin.Context) {\n        msg := \"\"\n        msg += fmt.Sprintf(\"Has user bob: %v\\n\", userstate.HasUser(\"bob\"))\n        msg += fmt.Sprintf(\"Logged in on server: %v\\n\", userstate.IsLoggedIn(\"bob\"))\n        msg += fmt.Sprintf(\"Is confirmed: %v\\n\", userstate.IsConfirmed(\"bob\"))\n        msg += fmt.Sprintf(\"Username stored in cookies (or blank): %v\\n\", userstate.Username(c.Request))\n        msg += fmt.Sprintf(\"Current user is logged in, has a valid cookie and *user rights*: %v\\n\", userstate.UserRights(c.Request))\n        msg += fmt.Sprintf(\"Current user is logged in, has a valid cookie and *admin rights*: %v\\n\", userstate.AdminRights(c.Request))\n        msg += fmt.Sprintln(\"\\nTry: /register, /confirm, /remove, /login, /logout, /makeadmin, /clear, /data and /admin\")\n        c.String(http.StatusOK, msg)\n    })\n\n    g.GET(\"/register\", func(c *gin.Context) {\n        userstate.AddUser(\"bob\", \"hunter1\", \"bob@zombo.com\")\n        c.String(http.StatusOK, fmt.Sprintf(\"User bob was created: %v\\n\", userstate.HasUser(\"bob\")))\n    })\n\n    g.GET(\"/confirm\", func(c *gin.Context) {\n        userstate.MarkConfirmed(\"bob\")\n        c.String(http.StatusOK, fmt.Sprintf(\"User bob was confirmed: %v\\n\", userstate.IsConfirmed(\"bob\")))\n    })\n\n    g.GET(\"/remove\", func(c *gin.Context) {\n        userstate.RemoveUser(\"bob\")\n        c.String(http.StatusOK, fmt.Sprintf(\"User bob was removed: %v\\n\", !userstate.HasUser(\"bob\")))\n    })\n\n    g.GET(\"/login\", func(c *gin.Context) {\n        // Headers will be written, for storing a cookie\n        userstate.Login(c.Writer, \"bob\")\n        c.String(http.StatusOK, fmt.Sprintf(\"bob is now logged in: %v\\n\", userstate.IsLoggedIn(\"bob\")))\n    })\n\n    g.GET(\"/logout\", func(c *gin.Context) {\n        userstate.Logout(\"bob\")\n        c.String(http.StatusOK, fmt.Sprintf(\"bob is now logged out: %v\\n\", !userstate.IsLoggedIn(\"bob\")))\n    })\n\n    g.GET(\"/makeadmin\", func(c *gin.Context) {\n        userstate.SetAdminStatus(\"bob\")\n        c.String(http.StatusOK, fmt.Sprintf(\"bob is now administrator: %v\\n\", userstate.IsAdmin(\"bob\")))\n    })\n\n    g.GET(\"/clear\", func(c *gin.Context) {\n        userstate.ClearCookie(c.Writer)\n        c.String(http.StatusOK, \"Clearing cookie\")\n    })\n\n    g.GET(\"/data\", func(c *gin.Context) {\n        c.String(http.StatusOK, \"user page that only logged in users must see!\")\n    })\n\n    g.GET(\"/admin\", func(c *gin.Context) {\n        c.String(http.StatusOK, \"super secret information that only logged in administrators must see!\\n\\n\")\n        if usernames, err := userstate.AllUsernames(); err == nil {\n            c.String(http.StatusOK, \"list of all users: \"+strings.Join(usernames, \", \"))\n        }\n    })\n\n    // Serve\n    g.Run(\":3000\")\n}\n~~~\n\n### Example for [Goji](https://github.com/zenazn/goji)\n\n~~~ go\npackage main\n\nimport (\n    \"fmt\"\n    \"net/http\"\n    \"strings\"\n    \"log\"\n\n    \"github.com/xyproto/permissions\"\n    \"github.com/zenazn/goji\"\n)\n\nfunc main() {\n    // New permissions middleware\n    perm, err := permissions.New2()\n    if err != nil {\n        log.Fatalln(err)\n    }\n\n    // Blank slate, no default permissions\n    //perm.Clear()\n\n    // Get the userstate, used in the handlers below\n    userstate := perm.UserState()\n\n    goji.Get(\"/\", func(w http.ResponseWriter, req *http.Request) {\n        fmt.Fprintf(w, \"Has user bob: %v\\n\", userstate.HasUser(\"bob\"))\n        fmt.Fprintf(w, \"Logged in on server: %v\\n\", userstate.IsLoggedIn(\"bob\"))\n        fmt.Fprintf(w, \"Is confirmed: %v\\n\", userstate.IsConfirmed(\"bob\"))\n        fmt.Fprintf(w, \"Username stored in cookies (or blank): %v\\n\", userstate.Username(req))\n        fmt.Fprintf(w, \"Current user is logged in, has a valid cookie and *user rights*: %v\\n\", userstate.UserRights(req))\n        fmt.Fprintf(w, \"Current user is logged in, has a valid cookie and *admin rights*: %v\\n\", userstate.AdminRights(req))\n        fmt.Fprintf(w, \"\\nTry: /register, /confirm, /remove, /login, /logout, /makeadmin, /clear, /data and /admin\")\n    })\n\n    goji.Get(\"/register\", func(w http.ResponseWriter, req *http.Request) {\n        userstate.AddUser(\"bob\", \"hunter1\", \"bob@zombo.com\")\n        fmt.Fprintf(w, \"User bob was created: %v\\n\", userstate.HasUser(\"bob\"))\n    })\n\n    goji.Get(\"/confirm\", func(w http.ResponseWriter, req *http.Request) {\n        userstate.MarkConfirmed(\"bob\")\n        fmt.Fprintf(w, \"User bob was confirmed: %v\\n\", userstate.IsConfirmed(\"bob\"))\n    })\n\n    goji.Get(\"/remove\", func(w http.ResponseWriter, req *http.Request) {\n        userstate.RemoveUser(\"bob\")\n        fmt.Fprintf(w, \"User bob was removed: %v\\n\", !userstate.HasUser(\"bob\"))\n    })\n\n    goji.Get(\"/login\", func(w http.ResponseWriter, req *http.Request) {\n        userstate.Login(w, \"bob\")\n        fmt.Fprintf(w, \"bob is now logged in: %v\\n\", userstate.IsLoggedIn(\"bob\"))\n    })\n\n    goji.Get(\"/logout\", func(w http.ResponseWriter, req *http.Request) {\n        userstate.Logout(\"bob\")\n        fmt.Fprintf(w, \"bob is now logged out: %v\\n\", !userstate.IsLoggedIn(\"bob\"))\n    })\n\n    goji.Get(\"/makeadmin\", func(w http.ResponseWriter, req *http.Request) {\n        userstate.SetAdminStatus(\"bob\")\n        fmt.Fprintf(w, \"bob is now administrator: %v\\n\", userstate.IsAdmin(\"bob\"))\n    })\n\n    goji.Get(\"/clear\", func(w http.ResponseWriter, req *http.Request) {\n        userstate.ClearCookie(w)\n        fmt.Fprintf(w, \"Clearing cookie\")\n    })\n\n    goji.Get(\"/data\", func(w http.ResponseWriter, req *http.Request) {\n        fmt.Fprintf(w, \"user page that only logged in users must see!\")\n    })\n\n    goji.Get(\"/admin\", func(w http.ResponseWriter, req *http.Request) {\n        fmt.Fprintf(w, \"super secret information that only logged in administrators must see!\\n\\n\")\n        if usernames, err := userstate.AllUsernames(); err == nil {\n            fmt.Fprintf(w, \"list of all users: \"+strings.Join(usernames, \", \"))\n        }\n    })\n\n    // Custom \"permissions denied\" message\n    perm.SetDenyFunction(func(w http.ResponseWriter, req *http.Request) {\n        http.Error(w, \"Permission denied!\", http.StatusForbidden)\n    })\n\n    // Permissions middleware for Goji\n    permissionHandler := func(next http.Handler) http.Handler {\n        return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n            // Check if the user has the right admin/user rights\n            if perm.Rejected(w, req) {\n                // Deny the request\n                perm.DenyFunction()(w, req)\n                return\n            }\n            // Serve the requested page\n            next.ServeHTTP(w, req)\n        })\n    }\n\n    // Enable the permissions middleware\n    goji.Use(permissionHandler)\n\n    // Goji will listen to port 8000 by default\n    goji.Serve()\n}\n~~~\n\n### Example for just `net/http`\n\n~~~ go\npackage main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"net/http\"\n    \"strings\"\n    \"time\"\n\n    \"github.com/xyproto/permissions\"\n    \"github.com/xyproto/pinterface\"\n)\n\ntype permissionHandler struct {\n    // perm is a Permissions structure that can be used to deny requests\n    // and acquire the UserState. By using `pinterface.IPermissions` instead\n    // of `*permissions.Permissions`, the code is compatible with not only\n    // `permissions`, but also other modules that uses other database\n    // backends, like `permissionbolt` which uses Bolt.\n    perm pinterface.IPermissions\n\n    // The HTTP multiplexer\n    mux *http.ServeMux\n}\n\n// Implement the ServeHTTP method to make a permissionHandler a http.Handler\nfunc (ph *permissionHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n    // Check if the user has the right admin/user rights\n    if ph.perm.Rejected(w, req) {\n        // Let the user know, by calling the custom \"permission denied\" function\n        ph.perm.DenyFunction()(w, req)\n        // Reject the request\n        return\n    }\n    // Serve the requested page if permissions were granted\n    ph.mux.ServeHTTP(w, req)\n}\n\nfunc main() {\n    mux := http.NewServeMux()\n\n    // New permissions middleware\n    perm, err := permissions.New2()\n    if err != nil {\n        log.Fatalln(err)\n    }\n\n    // Blank slate, no default permissions\n    //perm.Clear()\n\n    // Get the userstate, used in the handlers below\n    userstate := perm.UserState()\n\n    mux.HandleFunc(\"/\", func(w http.ResponseWriter, req *http.Request) {\n        fmt.Fprintf(w, \"Has user bob: %v\\n\", userstate.HasUser(\"bob\"))\n        fmt.Fprintf(w, \"Logged in on server: %v\\n\", userstate.IsLoggedIn(\"bob\"))\n        fmt.Fprintf(w, \"Is confirmed: %v\\n\", userstate.IsConfirmed(\"bob\"))\n        fmt.Fprintf(w, \"Username stored in cookies (or blank): %v\\n\", userstate.Username(req))\n        fmt.Fprintf(w, \"Current user is logged in, has a valid cookie and *user rights*: %v\\n\", userstate.UserRights(req))\n        fmt.Fprintf(w, \"Current user is logged in, has a valid cookie and *admin rights*: %v\\n\", userstate.AdminRights(req))\n        fmt.Fprintf(w, \"\\nTry: /register, /confirm, /remove, /login, /logout, /makeadmin, /clear, /data and /admin\")\n    })\n\n    mux.HandleFunc(\"/register\", func(w http.ResponseWriter, req *http.Request) {\n        userstate.AddUser(\"bob\", \"hunter1\", \"bob@zombo.com\")\n        fmt.Fprintf(w, \"User bob was created: %v\\n\", userstate.HasUser(\"bob\"))\n    })\n\n    mux.HandleFunc(\"/confirm\", func(w http.ResponseWriter, req *http.Request) {\n        userstate.MarkConfirmed(\"bob\")\n        fmt.Fprintf(w, \"User bob was confirmed: %v\\n\", userstate.IsConfirmed(\"bob\"))\n    })\n\n    mux.HandleFunc(\"/remove\", func(w http.ResponseWriter, req *http.Request) {\n        userstate.RemoveUser(\"bob\")\n        fmt.Fprintf(w, \"User bob was removed: %v\\n\", !userstate.HasUser(\"bob\"))\n    })\n\n    mux.HandleFunc(\"/login\", func(w http.ResponseWriter, req *http.Request) {\n        userstate.Login(w, \"bob\")\n        fmt.Fprintf(w, \"bob is now logged in: %v\\n\", userstate.IsLoggedIn(\"bob\"))\n    })\n\n    mux.HandleFunc(\"/logout\", func(w http.ResponseWriter, req *http.Request) {\n        userstate.Logout(\"bob\")\n        fmt.Fprintf(w, \"bob is now logged out: %v\\n\", !userstate.IsLoggedIn(\"bob\"))\n    })\n\n    mux.HandleFunc(\"/makeadmin\", func(w http.ResponseWriter, req *http.Request) {\n        userstate.SetAdminStatus(\"bob\")\n        fmt.Fprintf(w, \"bob is now administrator: %v\\n\", userstate.IsAdmin(\"bob\"))\n    })\n\n    mux.HandleFunc(\"/clear\", func(w http.ResponseWriter, req *http.Request) {\n        userstate.ClearCookie(w)\n        fmt.Fprintf(w, \"Clearing cookie\")\n    })\n\n    mux.HandleFunc(\"/data\", func(w http.ResponseWriter, req *http.Request) {\n        fmt.Fprintf(w, \"user page that only logged in users must see!\")\n    })\n\n    mux.HandleFunc(\"/admin\", func(w http.ResponseWriter, req *http.Request) {\n        fmt.Fprintf(w, \"super secret information that only logged in administrators must see!\\n\\n\")\n        if usernames, err := userstate.AllUsernames(); err == nil {\n            fmt.Fprintf(w, \"list of all users: \"+strings.Join(usernames, \", \"))\n        }\n    })\n\n    // Custom handler for when permissions are denied\n    perm.SetDenyFunction(func(w http.ResponseWriter, req *http.Request) {\n        http.Error(w, \"Permission denied!\", http.StatusForbidden)\n    })\n\n    // Configure the HTTP server and permissionHandler struct\n    s := \u0026http.Server{\n        Addr:           \":3000\",\n        Handler:        \u0026permissionHandler{perm, mux},\n        ReadTimeout:    10 * time.Second,\n        WriteTimeout:   10 * time.Second,\n        MaxHeaderBytes: 1 \u003c\u003c 20,\n    }\n\n    log.Println(\"Listening for requests on port 3000\")\n\n    // Start listening\n    log.Fatal(s.ListenAndServe())\n}\n~~~\n\n## Default permissions\n\n* Visiting the */admin* path prefix requires the user to be logged in with admin rights, by default.\n* These path prefixes requires the user to be logged in, by default: */repo* and */data*\n* These path prefixes are public by default: */*, */login*, */register*, */style*, */img*, */js*, */favicon.ico*, */robots.txt* and */sitemap_index.xml*\n\nThe default permissions can be cleared with the `Clear()` function.\n\n\n## Password hashing\n\n* bcrypt is used by default for hashing passwords. sha256 is also supported.\n* By default, all new passwords will be hashed with bcrypt.\n* For backwards compatibility, old password hashes with the length of a sha256 hash will be checked with sha256. To disable this behavior, and only ever use bcrypt, add this line: `userstate.SetPasswordAlgo(\"bcrypt\")`\n\n\n## Coding style\n\n* The code shall always be formatted with `go fmt`.\n\n\n## Setting and getting properties for users\n\n* Setting a property:\n\n```\nusername := \"bob\"\npropertyName := \"clever\"\npropertyValue := \"yes\"\n\nuserstate.Users().Set(username, propertyName, propertyValue)\n```\n\n* Getting a property:\n\n```\nusername := \"bob\"\npropertyName := \"clever\"\npropertyValue, err := userstate.Users().Get(username, propertyName)\nif err != nil {\n    log.Print(err)\n    return err\n}\nfmt.Printf(\"%s is %s: %s\\n\", username, propertyName, propertyValue)\n```\n\nThis method can also be used for deleting users, by for example setting a `deleted` property to `true`.\n\n## Passing userstate between functions, files and to other Go packages\n\nUsing the `pinterface.IUserState` interface (from the [pinterface](https://github.com/xyproto/pinterface) package) makes it possible to pass UserState structs between functions, also in other packages. By using this, it is possible to seamlessly change the database backend from, for instance, Redis ([permissions](https://github.com/xyproto/permissions)) to BoltDB ([permissionbolt](https://github.com/xyproto/permissionbolt)).\n\n[pstore](https://github.com/xyproto/pstore), [permissionsql](https://github.com/xyproto/permissionsql), [permissionbolt](https://github.com/xyproto/permissionbolt) and [permissions](https://github.com/xyproto/permissions) are interchangeable.\n\n## Retrieving the underlying Redis database\n\nHere is a short example application for retrieving the underlying Redis pool and connection:\n\n```go\npackage main\n\nimport (\n    \"fmt\"\n    \"github.com/gomodule/redigo/redis\"\n    \"github.com/xyproto/permissions\"\n)\n\nfunc main() {\n    perm, err := permissions.New2()\n    if err != nil {\n        fmt.Println(\"Could not open Redis database\")\n        return\n    }\n    ustate := perm.UserState()\n\n    // A bit of checking is needed, since the database backend is interchangeable\n    pustate, ok := ustate.(*permissions.UserState)\n    if !ok {\n        fmt.Println(\"Not using the Redis database backend\")\n        return\n    }\n\n    // Convert from a simpleredis.ConnectionPool to a redis.Pool\n    redisPool := redis.Pool(*pustate.Pool())\n    fmt.Printf(\"Redis pool: %v (%T)\\n\", redisPool, redisPool)\n\n    // Get the Redis connection as well\n    redisConnection := redisPool.Get()\n    fmt.Printf(\"Redis connection: %v (%T)\\n\", redisConnection, redisConnection)\n}\n```\n\n## General information\n\n* Version: 1.0.0\n* License: BSD-3\n* Alexander F. Rødseth \u0026lt;xyproto@archlinux.org\u0026gt;\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fxyproto%2Fpermissions","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fxyproto%2Fpermissions","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fxyproto%2Fpermissions/lists"}