auth services, middleware, and other stuff
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

This commit is contained in:
2025-05-22 13:55:43 -04:00
parent 70bb4e66b4
commit e55d419d44
22 changed files with 985 additions and 95 deletions

View File

@@ -0,0 +1,60 @@
package middleware
import (
"context"
"log/slog"
"net/http"
"github.com/golang-jwt/jwt/v5"
)
const EmailKey contextKey = "email"
func AuthMiddleware(logger *slog.Logger, jwtKey []byte) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("token")
if err == http.ErrNoCookie {
logger.WarnContext(r.Context(), "token not provided")
w.WriteHeader(http.StatusUnauthorized)
return
}
if err != nil {
logger.ErrorContext(r.Context(), err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
tokenString := cookie.Value
token, err := jwt.Parse(tokenString, func(t *jwt.Token) (any, error) {
return jwtKey, nil
})
if !token.Valid {
logger.WarnContext(r.Context(), err.Error())
w.WriteHeader(http.StatusUnauthorized)
return
}
if err != nil {
logger.ErrorContext(r.Context(), err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
email, err := token.Claims.GetSubject()
if err != nil {
logger.ErrorContext(r.Context(), err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
ctx := context.WithValue(r.Context(), EmailKey, email)
newReq := r.WithContext(ctx)
next.ServeHTTP(w, newReq)
})
}
}

View File

@@ -8,17 +8,16 @@ import (
"github.com/gofrs/uuid/v5"
)
type contextKey string
const TraceIdKey contextKey = "trace_id"
func ContextMiddleware(logger *slog.Logger) func(http.Handler) http.Handler {
func TraceMiddleware(logger *slog.Logger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
traceid, err := uuid.NewV4()
if err != nil {
logger.ErrorContext(r.Context(), err.Error())
}
ctx := context.WithValue(r.Context(), TraceIdKey, traceid)
ctx := context.WithValue(r.Context(), TraceIdKey, traceid.String())
newReq := r.WithContext(ctx)
next.ServeHTTP(w, newReq)

View File

@@ -4,6 +4,8 @@ import "net/http"
type Middleware func(http.Handler) http.Handler
type contextKey string
func CompileMiddleware(h http.Handler, m []Middleware) http.Handler {
if len(m) < 1 {
return h