This repository has been archived on 2025-08-09. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
web-app-template/api/src/middleware/auth.go
Tim 5883fc0c3a
All checks were successful
Build and Push Docker Image / Explore-Gitea-Actions (push) Successful in 1m15s
add logging for failed auth
2024-07-30 09:30:56 +02:00

37 lines
758 B
Go

package middleware
import (
"api/src/utils"
"context"
"log"
"net/http"
)
type ContextKey string
const TOKEN_KEY ContextKey = "token"
func EnsureAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tokenStr := r.Header.Get("Authorization")
if (tokenStr == "") || (len(tokenStr) < len("Bearer ")) {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
tokenStr = tokenStr[len("Bearer "):]
token, err := utils.VerifyToken(tokenStr)
if err != nil {
log.Println(err)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
var newContext = context.WithValue(r.Context(), TOKEN_KEY, token)
next.ServeHTTP(w, r.WithContext(newContext))
})
}