Adds IsActionAllowed() in common utilities

- Is used only in deleteUser handler function for now
This commit is contained in:
smavros 2019-06-04 18:03:47 +02:00
parent 60d2ee94a2
commit 1a1a3c1876
2 changed files with 24 additions and 3 deletions

View file

@ -27,7 +27,6 @@ func ProvideErrorResponse(c *gin.Context, err error) bool {
return false // No error return false // No error
} }
func GetSimulationID(c *gin.Context) (int, error) { func GetSimulationID(c *gin.Context) (int, error) {
simID, err := strconv.Atoi(c.Param("simulationID")) simID, err := strconv.Atoi(c.Param("simulationID"))
@ -91,3 +90,19 @@ func GetWidgetID(c *gin.Context) (int, error) {
} }
} }
func IsActionAllowed(c *gin.Context, model string, action string) error {
// Get user's role from context
role, exists := c.Get("user_role")
if !exists {
return fmt.Errorf("Request does not contain user's role")
}
// Check if the role can execute the action on the model
if !Roles[role.(string)][model][action] {
return fmt.Errorf("Action not allowed for role %v", role)
}
return nil
}

View file

@ -274,11 +274,17 @@ func getUser(c *gin.Context) {
// @Router /users/{userID} [delete] // @Router /users/{userID} [delete]
func deleteUser(c *gin.Context) { func deleteUser(c *gin.Context) {
err := common.IsActionAllowed(c, "user", "delete")
if err != nil {
c.JSON(http.StatusUnprocessableEntity, fmt.Sprintf("%v", err))
return
}
var user User var user User
id, _ := strconv.ParseInt(c.Param("UserID"), 10, 64) id, _ := strconv.ParseInt(c.Param("UserID"), 10, 64)
// Check that the user exist // Check that the user exist
err := user.byID(uint(id)) err = user.byID(uint(id))
if err != nil { if err != nil {
c.JSON(http.StatusNotFound, fmt.Sprintf("%v", err)) c.JSON(http.StatusNotFound, fmt.Sprintf("%v", err))
return return