Files
omnex/control-plane/api/internal/profile/handler.go
T
Nuxgrid 5d2a132c3c
ci-api / test (push) Successful in 23m32s
ci-web / test (push) Successful in 13m52s
fix: multiple error
2026-08-01 17:24:34 +02:00

113 lines
2.5 KiB
Go

package profile
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/omnex/control-plane/api/internal/auth"
)
type Handler struct {
store Store
}
func NewHandler(store Store) *Handler {
return &Handler{store: store}
}
type newUsername struct {
Username string `json:"username" binding:"required,min=2,max=120"`
}
type newPassword struct {
Password string `json:"password" binding:"required,min=8"`
}
type newTelegram struct {
Telegram string `json:"telegram" binding:"required,min=3,max=64"`
}
func (h *Handler) UpdateUsernameById(c *gin.Context) {
var u newUsername
if err := c.ShouldBindJSON(&u); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "requête invalide"})
return
}
p := auth.PrincipalFrom(c)
if p == nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "non authentifié"})
return
}
user, err := h.store.UpdateUsername(p.UserID, u.Username)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "erreur serveur"})
return
}
c.JSON(http.StatusOK, user)
}
func (h *Handler) UpdatePasswordById(c *gin.Context) {
var u newPassword
if err := c.ShouldBindJSON(&u); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "requête invalide"})
return
}
p := auth.PrincipalFrom(c)
if p == nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "non authentifié"})
return
}
hash, err := auth.HashPassword(u.Password)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "erreur serveur"})
return
}
user, err := h.store.UpdatePassword(p.UserID, hash)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "requête invalide"})
return
}
c.JSON(http.StatusOK, user)
}
func (h *Handler) GetTelegramById(c *gin.Context) {
p := auth.PrincipalFrom(c)
if p == nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "non authentifié"})
return
}
user, err := h.store.GetTelegram(p.UserID)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "requête invalide"})
return
}
c.JSON(http.StatusOK, gin.H{"telegram": user.Telegram})
}
func (h *Handler) SetTelegramById(c *gin.Context) {
var t newTelegram
if err := c.ShouldBindJSON(&t); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "requête invalide"})
return
}
p := auth.PrincipalFrom(c)
if p == nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "non authentifié"})
return
}
user, err := h.store.SetTelegram(p.UserID, t.Telegram)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "erreur serveur"})
return
}
c.JSON(http.StatusOK, gin.H{"telegram": user.Telegram})
}