feat: add support for checking the user account and storing in a new context
This commit is contained in:
parent
4ae272205a
commit
e31672aad0
|
@ -1,14 +1,20 @@
|
||||||
package s5
|
package s5
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"git.lumeweb.com/LumeWeb/portal/interfaces"
|
"git.lumeweb.com/LumeWeb/portal/interfaces"
|
||||||
"github.com/golang-jwt/jwt/v5"
|
"github.com/golang-jwt/jwt/v5"
|
||||||
"go.sia.tech/jape"
|
"go.sia.tech/jape"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
AuthUserIDKey = "userID"
|
||||||
|
)
|
||||||
|
|
||||||
func AuthMiddleware(handler jape.Handler, portal interfaces.Portal) jape.Handler {
|
func AuthMiddleware(handler jape.Handler, portal interfaces.Portal) jape.Handler {
|
||||||
return jape.Adapt(func(h http.Handler) http.Handler {
|
return jape.Adapt(func(h http.Handler) http.Handler {
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
@ -35,7 +41,29 @@ func AuthMiddleware(handler jape.Handler, portal interfaces.Portal) jape.Handler
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
|
if claim, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
|
||||||
|
subject, err := claim.GetSubject()
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
userID, err := strconv.ParseUint(subject, 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Invalid User ID", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
exists, _ := portal.Accounts().AccountExists(userID)
|
||||||
|
|
||||||
|
if !exists {
|
||||||
|
http.Error(w, "Invalid User ID", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx := context.WithValue(r.Context(), "userId", userID)
|
||||||
|
r = r.WithContext(ctx)
|
||||||
|
|
||||||
h.ServeHTTP(w, r)
|
h.ServeHTTP(w, r)
|
||||||
} else {
|
} else {
|
||||||
http.Error(w, "Invalid JWT", http.StatusUnauthorized)
|
http.Error(w, "Invalid JWT", http.StatusUnauthorized)
|
||||||
|
|
Loading…
Reference in New Issue