Michael Thomson e55d419d44
All checks were successful
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
auth services, middleware, and other stuff
2025-05-22 13:55:43 -04:00

67 lines
1.4 KiB
Go

package handler
import (
"context"
"encoding/json"
"log/slog"
"net/http"
"gitea.michaelthomson.dev/mthomson/habits/internal/auth/service"
)
type Loginer interface {
Login(ctx context.Context, email string, password string) (string, error)
}
type LoginRequest struct {
Email string `json:"email"`
Password string `json:"password"`
}
func HandleLogin(logger *slog.Logger, authService Loginer) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
loginRequest := LoginRequest{}
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
err := decoder.Decode(&loginRequest)
if err != nil {
logger.ErrorContext(ctx, err.Error())
http.Error(w, "", http.StatusBadRequest)
return
}
token, err := authService.Login(ctx, loginRequest.Email, loginRequest.Password)
if err == service.ErrUnauthorized {
http.Error(w, "", http.StatusUnauthorized)
return
}
if err == service.ErrNotFound {
http.Error(w, "", http.StatusUnauthorized)
return
}
if err != nil {
logger.ErrorContext(ctx, err.Error())
http.Error(w, "", http.StatusInternalServerError)
return
}
cookie := http.Cookie{
Name: "token",
Value: token,
Path: "/",
MaxAge: 3600,
HttpOnly: true,
Secure: false,
SameSite: http.SameSiteLaxMode,
}
http.SetCookie(w, &cookie)
w.WriteHeader(http.StatusOK)
}
}