This commit is contained in:
38
handler/middleware/authenticate.go
Normal file
38
handler/middleware/authenticate.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"me-fit/service"
|
||||
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type ContextKey string
|
||||
|
||||
var SessionKey ContextKey = "session"
|
||||
|
||||
func Authenticate(service service.Auth) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
sessionId := getSessionID(r)
|
||||
session, _ := service.SignInSession(sessionId)
|
||||
|
||||
if session != nil {
|
||||
ctx := context.WithValue(r.Context(), SessionKey, session)
|
||||
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
} else {
|
||||
next.ServeHTTP(w, r)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func getSessionID(r *http.Request) string {
|
||||
cookie, err := r.Cookie("id")
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
return cookie.Name
|
||||
}
|
||||
@@ -1,16 +1,20 @@
|
||||
package middleware
|
||||
|
||||
import "net/http"
|
||||
import (
|
||||
"me-fit/service"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func CrossSiteRequestForgery() func(http.Handler) http.Handler {
|
||||
func CrossSiteRequestForgery(auth *service.Auth) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// session := r.Context().Value(SessionKey)
|
||||
|
||||
if r.Method == "POST" {
|
||||
// Check the CSRF token
|
||||
csrfToken := r.Header.Get("X-CSRF-Token")
|
||||
sessionToken := r.Header.Get("X-Session-Token")
|
||||
if csrfToken != sessionToken {
|
||||
http.Error(w, "CSRF token mismatch", http.StatusForbidden)
|
||||
csrfToken := r.FormValue("csrf-token")
|
||||
if csrfToken == "" {
|
||||
http.Error(w, "", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"me-fit/service"
|
||||
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func UserAuth(service *service.AuthService) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Check the user is logged in
|
||||
sessionToken := r.Header.Get("X-Session-Token")
|
||||
if sessionToken == "" {
|
||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user