2024-02-14 00:07:24 +00:00
|
|
|
package account
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"git.lumeweb.com/LumeWeb/portal/account"
|
|
|
|
"go.sia.tech/jape"
|
|
|
|
"go.uber.org/fx"
|
2024-02-14 00:28:23 +00:00
|
|
|
"go.uber.org/zap"
|
2024-02-14 00:07:24 +00:00
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
errInvalidLogin = errors.New("invalid login")
|
|
|
|
errFailedToCreateAccount = errors.New("failed to create account")
|
|
|
|
)
|
|
|
|
|
|
|
|
type HttpHandler struct {
|
|
|
|
accounts *account.AccountServiceDefault
|
2024-02-14 00:28:23 +00:00
|
|
|
logger *zap.Logger
|
2024-02-14 00:07:24 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type HttpHandlerParams struct {
|
|
|
|
fx.In
|
|
|
|
Accounts *account.AccountServiceDefault
|
2024-02-14 00:28:23 +00:00
|
|
|
Logger *zap.Logger
|
2024-02-14 00:07:24 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewHttpHandler(params HttpHandlerParams) *HttpHandler {
|
|
|
|
return &HttpHandler{
|
|
|
|
accounts: params.Accounts,
|
2024-02-14 00:28:23 +00:00
|
|
|
logger: params.Logger,
|
2024-02-14 00:07:24 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *HttpHandler) login(jc jape.Context) {
|
|
|
|
var request LoginRequest
|
|
|
|
|
|
|
|
if jc.Decode(&request) != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-02-14 00:28:23 +00:00
|
|
|
exists, _, err := h.accounts.EmailExists(request.Email)
|
2024-02-14 00:07:24 +00:00
|
|
|
|
|
|
|
if !exists {
|
|
|
|
_ = jc.Error(errInvalidLogin, http.StatusUnauthorized)
|
2024-02-14 00:28:23 +00:00
|
|
|
if err != nil {
|
|
|
|
h.logger.Error("failed to check if email exists", zap.Error(err))
|
|
|
|
}
|
2024-02-14 00:07:24 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-02-14 00:58:00 +00:00
|
|
|
jwt, _, err := h.accounts.LoginPassword(request.Email, request.Password, jc.Request.RemoteAddr)
|
2024-02-14 00:07:24 +00:00
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
jc.ResponseWriter.Header().Set("Authorization", "Bearer "+jwt)
|
|
|
|
jc.ResponseWriter.WriteHeader(http.StatusOK)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *HttpHandler) register(jc jape.Context) {
|
|
|
|
var request RegisterRequest
|
|
|
|
|
|
|
|
if jc.Decode(&request) != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
user, err := h.accounts.CreateAccount(request.Email, request.Password)
|
|
|
|
if err != nil {
|
|
|
|
_ = jc.Error(errFailedToCreateAccount, http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
err = h.accounts.UpdateAccountName(user.ID, request.FirstName, request.LastName)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
_ = jc.Error(errors.Join(errFailedToCreateAccount, err), http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|