package api import ( "encoding/json" "net/http" "gitea.qpismont.fr/qpismont/trepa/internal/accounts/domain" "gitea.qpismont.fr/qpismont/trepa/internal/core" "github.com/go-playground/validator/v10" ) var validate *validator.Validate type Controller struct { service domain.AccountService } func NewController(service domain.AccountService) Controller { validate = validator.New() return Controller{service: service} } func (c Controller) GetAccount(w *core.Response, r *http.Request) { claims := r.Context().Value("claims").(core.JWTClaims) account, httpErr := c.service.GetAccount(claims.AccountId) if httpErr != nil { w.WriteError(httpErr) return } response := GetAccountResponse{ Id: account.Id, Username: account.Username, RoleId: account.RoleId, CreatedAt: account.CreatedAt, UpdatedAt: account.UpdatedAt, } responseJson, err := json.Marshal(response) if err != nil { w.WriteError(core.NewInternalServerError(err)) return } w.Json(responseJson) } func (c Controller) Login(w *core.Response, r *http.Request) { var request LoginAccountRequest if err := json.NewDecoder(r.Body).Decode(&request); err != nil { w.WriteError(core.ErrInvalidStruct) return } if err := validate.Struct(request); err != nil { w.WriteError(core.ErrInvalidStruct) return } result, httpErr := c.service.Login(domain.AccountLogin{ Username: request.Username, Password: request.Password, }) if httpErr != nil { w.WriteError(httpErr) return } response := LoginAccountResponse{ Account: Account{ Id: result.Account.Id, Username: result.Account.Username, RoleId: result.Account.RoleId, CreatedAt: result.Account.CreatedAt, UpdatedAt: result.Account.UpdatedAt, }, Token: result.Token, } responseJson, err := json.Marshal(response) if err != nil { w.WriteError(core.NewInternalServerError(err)) return } w.Json(responseJson) }