2021-08-01 17:06:33 +00:00
|
|
|
package handler
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
|
|
|
func (authMux *AuthMux) PrivateHandleFunc(pattern string, handlerFunc HandlerFunc) {
|
|
|
|
authMux.mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
if authMux.isAuthenticated(r) {
|
|
|
|
handlerFunc(w, r)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
authMux.accessDenied(w, r)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func (authMux *AuthMux) PrivateHandle(pattern string, handler http.Handler) {
|
|
|
|
authMux.PrivateHandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
handler.ServeHTTP(w, r)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func (authMux *AuthMux) accessDenied(w http.ResponseWriter, r *http.Request) {
|
|
|
|
w.WriteHeader(http.StatusForbidden)
|
|
|
|
fmt.Fprintf(w, "Forbidden")
|
|
|
|
}
|
|
|
|
|
|
|
|
func (authMux *AuthMux) isAuthenticated(r *http.Request) bool {
|
|
|
|
authCookie, err := r.Cookie("knyt-auth")
|
|
|
|
if err != nil {
|
2021-08-02 18:08:16 +00:00
|
|
|
fmt.Printf("%v\n", err)
|
2021-08-01 17:06:33 +00:00
|
|
|
return false
|
|
|
|
}
|
2021-08-02 18:08:16 +00:00
|
|
|
fmt.Printf("isAuthenticated? %s\n", authCookie.Value)
|
2021-08-01 17:06:33 +00:00
|
|
|
|
|
|
|
usr, usrErr := authMux.app.GetUsers().GetUserById(authCookie.Value)
|
|
|
|
if usrErr != nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2021-08-02 18:08:16 +00:00
|
|
|
fmt.Printf("\"%s\" ?= \"%s\"\n", usr.Id, authCookie.Value)
|
|
|
|
return usr.Id == authCookie.Value
|
2021-08-01 17:06:33 +00:00
|
|
|
}
|