From cf5bb85cede5b05b58ed2b40460d0b913e8b2cf6 Mon Sep 17 00:00:00 2001 From: jloup Date: Sun, 13 May 2018 15:47:59 +0100 Subject: [PATCH] User roles. --- api/routes.go | 5 +++++ api/user.go | 14 ++++++++++++++ db/migrations.go | 11 +++++++++++ db/user.go | 10 ++++++++-- 4 files changed, 38 insertions(+), 2 deletions(-) diff --git a/api/routes.go b/api/routes.go index 404f821..3adbfe9 100644 --- a/api/routes.go +++ b/api/routes.go @@ -55,6 +55,11 @@ var Groups = []Group{ {"GET", []gin.HandlerFunc{UserAccount}, "/account"}, }, }, + { + "/admin", + []Middleware{JwtAuth, UserConfirmed, UserIsAdmin, OtpAuth}, + []Route{}, + }, } func Signup(c *gin.Context) { diff --git a/api/user.go b/api/user.go index a2737fd..bc24bbb 100644 --- a/api/user.go +++ b/api/user.go @@ -30,6 +30,20 @@ func UserConfirmed(c *gin.Context) *Error { return nil } +func UserIsAdmin(c *gin.Context) *Error { + user, exists := c.Get("user") + + if !exists { + return &Error{NotAuthorized, "not authorized", fmt.Errorf("no user key in context")} + } + + if user.(db.User).Role != db.RoleAdmin { + return &Error{NotAuthorized, "not authorized", fmt.Errorf("user '%v' is not admin", user)} + } + + return nil +} + func GetUser(c *gin.Context) db.User { user, _ := c.Get("user") diff --git a/db/migrations.go b/db/migrations.go index f0df49c..e8fc40d 100644 --- a/db/migrations.go +++ b/db/migrations.go @@ -89,4 +89,15 @@ var migrations []Migration = []Migration{ "DROP TYPE market_config_status", }, }, + { + Version: 201805131000, + Up: []string{ + "CREATE TYPE user_role AS ENUM ('admin', 'user')", + "ALTER TABLE users ADD role user_role NOT NULL DEFAULT 'user'", + }, + Down: []string{ + "ALTER TABLE users DROP COLUMN role", + "DROP TYPE user_role", + }, + }, } diff --git a/db/user.go b/db/user.go index 64ca6a6..24ce491 100644 --- a/db/user.go +++ b/db/user.go @@ -11,10 +11,16 @@ const ( AwaitingConfirmation ) +type UserRole string + +const RoleUser UserRole = "user" +const RoleAdmin UserRole = "admin" + type User struct { Id int64 - Email string `sql:",unique,notnull"` - PasswordHash string `sql:",notnull"` + Role UserRole + Email string + PasswordHash string OtpSecret string IsOtpSetup bool Status UserStatus -- 2.41.0