forked from mtusi2026/mtusi2026lab7
119 lines
3.6 KiB
Go
119 lines
3.6 KiB
Go
package handlers
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"net"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"messenger/src/backend/services"
|
|
)
|
|
|
|
type authenticatedUserKey struct{}
|
|
|
|
func currentUserID(r *http.Request) string {
|
|
id, _ := r.Context().Value(authenticatedUserKey{}).(string)
|
|
return id
|
|
}
|
|
|
|
func authRequired(sessions *services.SessionService, next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
authorization := r.Header.Get("Authorization")
|
|
if !strings.HasPrefix(authorization, "Bearer ") || strings.TrimSpace(strings.TrimPrefix(authorization, "Bearer ")) == "" {
|
|
unauthorized(w, "Bearer", newRequestID())
|
|
return
|
|
}
|
|
user, err := sessions.User(r.Context(), strings.TrimPrefix(authorization, "Bearer "))
|
|
if errors.Is(err, services.ErrInvalidSession) {
|
|
unauthorized(w, "Bearer", newRequestID())
|
|
return
|
|
}
|
|
if err != nil {
|
|
requestID := newRequestID()
|
|
w.Header().Set("X-Request-Id", requestID)
|
|
writeError(w, 503, "unavailable", "dependency unavailable", requestID)
|
|
return
|
|
}
|
|
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), authenticatedUserKey{}, user.ID)))
|
|
})
|
|
}
|
|
|
|
func unauthorized(w http.ResponseWriter, scheme, requestID string) {
|
|
w.Header().Set("X-Request-Id", requestID)
|
|
if scheme == "Basic" {
|
|
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
|
} else {
|
|
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
|
}
|
|
writeError(w, 401, "unauthorized", "invalid credentials", requestID)
|
|
}
|
|
|
|
func sessionHandler(sessions *services.SessionService) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
requestID := newRequestID()
|
|
w.Header().Set("X-Request-Id", requestID)
|
|
if r.Method != http.MethodPost {
|
|
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
|
|
return
|
|
}
|
|
// HAProxy overwrites this header and is the only mTLS identity allowed to reach the API.
|
|
if r.TLS != nil {
|
|
source := net.ParseIP(r.Header.Get("X-Forwarded-For"))
|
|
if source == nil {
|
|
writeError(w, 503, "unavailable", "missing ingress client address", requestID)
|
|
return
|
|
}
|
|
retryAfter, err := sessions.LoginRetryAfter(r.Context(), source.String())
|
|
if err != nil {
|
|
writeError(w, 503, "unavailable", "dependency unavailable", requestID)
|
|
return
|
|
}
|
|
if retryAfter > 0 {
|
|
w.Header().Set("Retry-After", strconv.Itoa(retryAfter))
|
|
writeError(w, 429, "rate_limited", "too many login attempts", requestID)
|
|
return
|
|
}
|
|
}
|
|
username, password, ok := r.BasicAuth()
|
|
if !ok || r.ContentLength > 0 {
|
|
unauthorized(w, "Basic", requestID)
|
|
return
|
|
}
|
|
user, token, expires, valid, err := sessions.Login(r.Context(), username, password)
|
|
if err != nil {
|
|
writeError(w, 503, "unavailable", "dependency unavailable", requestID)
|
|
return
|
|
}
|
|
if !valid {
|
|
unauthorized(w, "Basic", requestID)
|
|
return
|
|
}
|
|
writeJSON(w, 201, struct {
|
|
Token string `json:"token"`
|
|
TokenType string `json:"token_type"`
|
|
ExpiresAt time.Time `json:"expires_at"`
|
|
User any `json:"user"`
|
|
}{token, "Bearer", expires, user})
|
|
}
|
|
}
|
|
|
|
func logoutHandler(sessions *services.SessionService) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
requestID := newRequestID()
|
|
w.Header().Set("X-Request-Id", requestID)
|
|
if r.Method != http.MethodDelete {
|
|
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
|
|
return
|
|
}
|
|
token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
|
|
if err := sessions.Revoke(r.Context(), token); err != nil {
|
|
writeError(w, 503, "unavailable", "dependency unavailable", requestID)
|
|
return
|
|
}
|
|
w.WriteHeader(204)
|
|
}
|
|
}
|