Skip to content

Commit

Permalink
Addind roles to user function
Browse files Browse the repository at this point in the history
  • Loading branch information
AriaFantom committed Oct 4, 2024
1 parent 2d10016 commit 8857c7c
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
19 changes: 19 additions & 0 deletions backend/handler/rbac.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,25 @@ import (
"github.com/gofiber/fiber/v3"
)

func UpdateRoleToUser(c fiber.Ctx) error {
role := new(models.RoleUser)
if err := c.Bind().Body(role); err != nil {
return c.Status(400).JSON(fiber.Map{
"error": err.Error(),
})
}

err := repository.AssignRoleToUser(role.Email, role.RoleID)
if err != nil {
return c.Status(500).JSON(fiber.Map{
"error": err.Error(),
})
}
return c.Status(200).JSON(fiber.Map{
"message": "Role assigned to user successfully",
})
}

func InsertRoles(c fiber.Ctx) error {
role := new(models.Role)
if err := c.Bind().Body(role); err != nil {
Expand Down
5 changes: 5 additions & 0 deletions backend/models/rbac.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ var Permissions = []string{
"delete:role",
}

type RoleUser struct {
Email string `json:"email" validate:"required,email"`
RoleID string `json:"role_id" validate:"required"`
}

type Role struct {
ID int
Name string `json:"name" validate:"required"`
Expand Down
14 changes: 14 additions & 0 deletions backend/repository/rbac.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,20 @@ func AddRoles(role *models.Role) error {
return nil
}

func AssignRoleToUser(email string, id string) error {
conn, err := database.Connect()
if err != nil {
return err
}

_, err = conn.Exec(context.Background(), "UPDATE users SET role = (SELECT id FROM roles WHERE id = $1) WHERE email = $2", id, email)
if err != nil {
return err
}

return nil
}

func FetchRoles(name string) ([]models.Role, error) {
conn, err := database.Connect()
if err != nil {
Expand Down

0 comments on commit 8857c7c

Please sign in to comment.