{"id":15394282,"url":"https://github.com/xyproto/permissionsql","last_synced_at":"2025-04-11T12:08:20.331Z","repository":{"id":26432519,"uuid":"29883090","full_name":"xyproto/permissionsql","owner":"xyproto","description":":lock_with_ink_pen: Middleware for keeping track of users, login states and permissions","archived":false,"fork":false,"pushed_at":"2024-05-09T13:05:28.000Z","size":7564,"stargazers_count":61,"open_issues_count":0,"forks_count":9,"subscribers_count":5,"default_branch":"main","last_synced_at":"2025-03-25T08:23:10.907Z","etag":null,"topics":["auth","go","mariadb","mysql","permissions"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-3-clause","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":null,"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}},"created_at":"2015-01-26T21:42:57.000Z","updated_at":"2024-09-11T16:28:00.000Z","dependencies_parsed_at":"2024-06-18T19:58:47.188Z","dependency_job_id":null,"html_url":"https://github.com/xyproto/permissionsql","commit_stats":{"total_commits":197,"total_committers":5,"mean_commits":39.4,"dds":"0.045685279187817285","last_synced_commit":"75f2d5263f4a0f10c3b0eb3ebf05ec56e0773f9b"},"previous_names":[],"tags_count":5,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xyproto%2Fpermissionsql","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xyproto%2Fpermissionsql/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xyproto%2Fpermissionsql/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xyproto%2Fpermissionsql/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/xyproto","download_url":"https://codeload.github.com/xyproto/permissionsql/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248396945,"owners_count":21097019,"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":["auth","go","mariadb","mysql","permissions"],"created_at":"2024-10-01T15:22:58.793Z","updated_at":"2025-04-11T12:08:20.308Z","avatar_url":"https://github.com/xyproto.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# PermissionSQL [![GoDoc](https://godoc.org/github.com/xyproto/permissionsql?status.svg)](http://godoc.org/github.com/xyproto/permissionsql)\n\nMiddleware for keeping track of users, login states and permissions.\n\n## Online API Documentation\n\n[godoc.org](http://godoc.org/github.com/xyproto/permissionsql)\n\n## Features and limitations\n\n* Uses secure cookies and stores user information in a MariaDB/MySQL database.\n* Suitable for running a local MariaDB/MySQL server, registering/confirming users and managing public/user/admin pages.\n* Also supports connecting to remote MariaDB/MySQL servers.\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* Supports [Negroni](https://github.com/codegangsta/negroni), [Martini](https://github.com/go-martini/martini), [Gin](https://github.com/gin-gonic/gin) and [Macaron](https://github.com/Unknwon/macaron).\n* Should also work with other frameworks, since the standard http.HandlerFunc is used everywhere.\n* The default permissions can be cleared with the Clear() function.\n\n## Connecting\n\nFor connecting to a MariaDB/MySQL host that is running locally, the `New` function can be used. For connecting to a remote server, the `NewWithDSN` function can be used.\n\n## Requirements\n\n* MariaDB or MySQL\n* Go 1.17 or later\n\n## Examples\n\n### Example for [Gin](https://github.com/gin-gonic/gin)\n\n~~~ go\npackage main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"net/http\"\n    \"strings\"\n\n    \"github.com/gin-gonic/gin\"\n    \"github.com/xyproto/permissionsql/v2\"\n)\n\nfunc main() {\n    g := gin.New()\n\n    // New permissionsql middleware\n    perm, err := permissionsql.New()\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 permissionsql 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 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/permissionsql/v2\"\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    // `permissions2`, 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 := permissionsql.New()\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## Coding style\n\n* The code shall always be formatted with `go fmt`.\n\n## Password hashing\n\n* bcrypt is used by default for hashing passwords. sha256 is also supported.\n* By default, all new password 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## 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\n## Passing userstate between functions, files and to other Go packages\n\nUsing the `*pinterface.IUserState` type (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 interface, it is possible to seamlessly change the database backend from, for instance, PostgreSQL ([pstore](https://github.com/xyproto/pstore)) to BoltDB ([permissionbolt](https://github.com/xyproto/permissionbolt)) or Redis ([permissions2](https://github.com/xyproto/permissions2)).\n\n[pstore](https://github.com/xyproto/pstore), [permissionsql](https://github.com/xyproto/permissionsql), [permissionbolt](https://github.com/xyproto/permissionbolt) and [permissions2](https://github.com/xyproto/permissions2) are interchangeable.\n\n\n## General information\n\n* Version: 2.1.2\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%2Fpermissionsql","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fxyproto%2Fpermissionsql","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fxyproto%2Fpermissionsql/lists"}