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/middleware/auth.go
2024-07-27 21:10:31 +02:00

34 lines
726 B
Go

package middleware
import (
"api/utils"
"context"
"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 {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
var newContext = context.WithValue(r.Context(), TOKEN_KEY, token)
next.ServeHTTP(w, r.WithContext(newContext))
})
}