fix(permission): change permission checking

read permissions from settings.json instead
This commit is contained in:
pakintada@gmail.com 2024-03-18 14:11:24 +07:00
parent 8744ddcb8c
commit cd0f67bb44
6 changed files with 128 additions and 60 deletions

View file

@ -186,42 +186,10 @@ var (
}
)
func LoadCountrySettings() []helpers.CountryName {
res := make([]helpers.CountryName, 0)
// read file country.settings.json
content, err := os.Open("country.settings.json")
if err != nil {
fmt.Errorf("country.settings.json not found")
}
// read content to json
var countrySettings []map[string]interface{}
err = json.NewDecoder(content).Decode(&countrySettings)
if err != nil {
fmt.Errorf("error in country.settings")
return nil
}
for _, v := range countrySettings {
if ignore, ok := v["ignore"].(bool); ok {
if ignore {
continue
}
}
res = append(res, helpers.CountryName{
CountryID: v["short"].(string),
CountryName: v["name"].(string),
})
}
return res
}
func NewData(taoLogger *logger.TaoLogger, redisClient *RedisCli) *Data {
allRecipeFiles := helpers.ScanRecipeFiles(LoadCountrySettings())
allRecipeFiles := helpers.ScanRecipeFiles(helpers.LoadCountrySettings())
fmt.Println(allRecipeFiles)
defaultFile := "coffeethai02_600.json"

View file

@ -3,15 +3,15 @@ package permissions
type Permission int
const (
ThaiPermission Permission = 1 << iota
MalayPermission
AusPermission
Alpha3Permission
// ThaiPermission Permission = 1 << iota
// MalayPermission
// AusPermission
// Alpha3Permission
// NOTE: Add more permission here
Viewer = 1 << 4
Editor = Viewer << 3
// SuperAdmin have max uint
SuperAdmin = ThaiPermission | MalayPermission | AusPermission | Alpha3Permission | (Editor | Viewer)
// SuperAdmin = ThaiPermission | MalayPermission | AusPermission | Alpha3Permission | (Editor | Viewer)
)
func (userPermissions Permission) IsHavePermission(requiredPermissions Permission) bool {

View file

@ -95,3 +95,78 @@ func ScanRecipeFiles(countries []CountryName) map[string][]RecipePath {
}
return recipeFiles
}
func LoadCountrySettings() []CountryName {
res := make([]CountryName, 0)
// read file country.settings.json
content, err := os.Open("country.settings.json")
if err != nil {
fmt.Errorf("country.settings.json not found")
}
// read content to json
var countrySettings []map[string]interface{}
err = json.NewDecoder(content).Decode(&countrySettings)
if err != nil {
fmt.Errorf("error in country.settings")
return nil
}
for _, v := range countrySettings {
if ignore, ok := v["ignore"].(bool); ok {
if ignore {
continue
}
}
res = append(res, CountryName{
CountryID: v["short"].(string),
CountryName: v["name"].(string),
})
}
return res
}
// integrate with permissions
type CountryNamePerms struct {
CountryID string
CountryName string
CountryPermission int
}
func LoadCountrySettingsWithPermissions() []CountryNamePerms {
res := make([]CountryNamePerms, 0)
// read file country.settings.json
content, err := os.Open("country.settings.json")
if err != nil {
fmt.Errorf("country.settings.json not found")
}
// read content to json
var countrySettings []map[string]interface{}
err = json.NewDecoder(content).Decode(&countrySettings)
if err != nil {
fmt.Errorf("error in country.settings")
return nil
}
for _, v := range countrySettings {
if ignore, ok := v["ignore"].(bool); ok {
if ignore {
continue
}
}
res = append(res, CountryNamePerms{
CountryID: v["short"].(string),
CountryName: v["name"].(string),
CountryPermission: int(v["permissions"].(float64)),
})
}
return res
}

View file

@ -111,20 +111,28 @@ func (rr *RecipeRouter) Route(r chi.Router) {
u := r.Context().Value("user").(*models.User)
var result []string
if u.Permissions.IsHavePermission(permissions.ThaiPermission) {
result = append(result, "tha")
}
// if u.Permissions.IsHavePermission(permissions.ThaiPermission) {
// result = append(result, "tha")
// }
if u.Permissions.IsHavePermission(permissions.MalayPermission) {
result = append(result, "mys")
}
// if u.Permissions.IsHavePermission(permissions.MalayPermission) {
// result = append(result, "mys")
// }
if u.Permissions.IsHavePermission(permissions.AusPermission) {
result = append(result, "aus")
}
// if u.Permissions.IsHavePermission(permissions.AusPermission) {
// result = append(result, "aus")
// }
if u.Permissions.IsHavePermission(permissions.Alpha3Permission) {
result = append(result, "alpha")
// if u.Permissions.IsHavePermission(permissions.Alpha3Permission) {
// result = append(result, "alpha")
// }
for _, v := range helpers.LoadCountrySettingsWithPermissions() {
fmt.Println(u.Email, "can access ", v.CountryID, " ? ")
if u.Permissions.IsHavePermission(permissions.Permission(v.CountryPermission)) {
result = append(result, v.CountryID)
fmt.Println("yes")
}
}
if err := json.NewEncoder(w).Encode(&contracts.Response[[]string]{

View file

@ -3,15 +3,17 @@ package routers
import (
"context"
"encoding/json"
"github.com/go-chi/chi/v5"
"go.uber.org/zap"
"net/http"
"recipe-manager/contracts"
"recipe-manager/enums/permissions"
"recipe-manager/helpers"
"recipe-manager/middlewares"
"recipe-manager/services/logger"
"recipe-manager/services/user"
"time"
"github.com/go-chi/chi/v5"
"go.uber.org/zap"
)
type UserRouter struct {
@ -25,16 +27,23 @@ func NewUserRouter(taoLogger *logger.TaoLogger, userService user.UserService) *U
func (ur *UserRouter) Route(r chi.Router) {
// Generate SuperAdmin permissions for seed
perms := helpers.LoadCountrySettingsWithPermissions()
superPerm := perms[0].CountryPermission
for _, p := range perms {
superPerm = superPerm | p.CountryPermission
}
// Users
r.Route("/users", func(r chi.Router) {
r.Get("/", middlewares.ValidatePermissions([]permissions.Permission{permissions.SuperAdmin}, ur.getUsers))
r.Get("/", middlewares.ValidatePermissions([]permissions.Permission{permissions.Permission(superPerm)}, ur.getUsers))
r.Post("/", middlewares.ValidatePermissions([]permissions.Permission{permissions.SuperAdmin}, ur.createUser))
r.Post("/", middlewares.ValidatePermissions([]permissions.Permission{permissions.Permission(superPerm)}, ur.createUser))
})
// User
r.Route("/user", func(r chi.Router) {
r.Get("/{id}", middlewares.ValidateOwnerOrPermissions([]permissions.Permission{permissions.SuperAdmin}, ur.getUser))
r.Get("/{id}", middlewares.ValidateOwnerOrPermissions([]permissions.Permission{permissions.Permission(superPerm)}, ur.getUser))
})
}

View file

@ -9,6 +9,7 @@ import (
"recipe-manager/config"
"recipe-manager/data"
"recipe-manager/enums/permissions"
"recipe-manager/helpers"
"recipe-manager/middlewares"
"recipe-manager/models"
"recipe-manager/routers"
@ -90,12 +91,19 @@ func (s *Server) createHandler() {
// User Service
userService := user.NewUserService(s.cfg, s.database, s.taoLogger)
// Generate SuperAdmin permissions for seed
perms := helpers.LoadCountrySettingsWithPermissions()
superPerm := perms[0].CountryPermission
for _, p := range perms {
superPerm = superPerm | p.CountryPermission
}
// Seed
_ = userService.CreateNewUser(context.WithValue(context.Background(), "user", &models.User{Email: "system"}), "kenta420", "poomipat.c@forth.co.th", "", permissions.SuperAdmin)
_ = userService.CreateNewUser(context.WithValue(context.Background(), "user", &models.User{Email: "system"}), "phu", "pakin.t@forth.co.th", "", permissions.SuperAdmin)
_ = userService.CreateNewUser(context.WithValue(context.Background(), "user", &models.User{Email: "system"}), "wanlop", "wanlop.r@forth.co.th", "", permissions.SuperAdmin)
_ = userService.CreateNewUser(context.WithValue(context.Background(), "user", &models.User{Email: "system"}), "dawit", "dawit.o@forth.co.th", "", permissions.SuperAdmin)
_ = userService.CreateNewUser(context.WithValue(context.Background(), "user", &models.User{Email: "system"}), "narisara", "narisara.k@tao-bin.com", "", permissions.SuperAdmin)
_ = userService.CreateNewUser(context.WithValue(context.Background(), "user", &models.User{Email: "system"}), "kenta420", "poomipat.c@forth.co.th", "", permissions.Permission(superPerm))
_ = userService.CreateNewUser(context.WithValue(context.Background(), "user", &models.User{Email: "system"}), "phu", "pakin.t@forth.co.th", "", permissions.Permission(superPerm))
_ = userService.CreateNewUser(context.WithValue(context.Background(), "user", &models.User{Email: "system"}), "wanlop", "wanlop.r@forth.co.th", "", permissions.Permission(superPerm))
_ = userService.CreateNewUser(context.WithValue(context.Background(), "user", &models.User{Email: "system"}), "dawit", "dawit.o@forth.co.th", "", permissions.Permission(superPerm))
_ = userService.CreateNewUser(context.WithValue(context.Background(), "user", &models.User{Email: "system"}), "narisara", "narisara.k@tao-bin.com", "", permissions.Permission(superPerm))
// Auth Router
r.Group(func(r chi.Router) {