62 lines
1.3 KiB
Go
62 lines
1.3 KiB
Go
package users
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
|
|
core "fr.latosa-escrima/core"
|
|
"fr.latosa-escrima/core/models"
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
func HandleAddRole(w http.ResponseWriter, r *http.Request) {
|
|
ctx := context.Background()
|
|
user_id := r.PathValue("user_uuid")
|
|
role_id := r.PathValue("role_id")
|
|
var user models.User
|
|
count, err := core.DB.NewSelect().Model(&user).
|
|
Where("user_id = ?", user_id).
|
|
Limit(1).ScanAndCount(ctx)
|
|
if count == 0 {
|
|
core.JSONError{
|
|
Status: core.Error,
|
|
Message: "User doesn't exist.",
|
|
}.Respond(w, http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
var role models.Role
|
|
count, err = core.DB.NewSelect().Model(&role).
|
|
Where("id = ?", role_id).
|
|
Limit(1).ScanAndCount(ctx)
|
|
|
|
if count == 0 {
|
|
core.JSONError{
|
|
Status: core.Error,
|
|
Message: "Role doesn't exist.",
|
|
}.Respond(w, http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
uid, err := uuid.Parse(user_id)
|
|
rid, err := uuid.Parse(role_id)
|
|
userRole := models.UserToRole{
|
|
UserID: uid,
|
|
RoleID: rid,
|
|
}
|
|
_, err = core.DB.NewInsert().Model(&userRole).Ignore().
|
|
Exec(ctx)
|
|
if err != nil {
|
|
core.JSONError{
|
|
Status: core.Error,
|
|
Message: err.Error(),
|
|
}.Respond(w, http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
core.JSONSuccess{
|
|
Status: core.Success,
|
|
Message: "Role added.",
|
|
}.Respond(w, http.StatusCreated)
|
|
}
|