knowyt/server/src/handler/private.go

40 lines
891 B
Go
Raw Normal View History

2021-08-01 17:06:33 +00:00
package handler
import (
"fmt"
"net/http"
2021-08-04 15:10:56 +00:00
"sirlab.de/go/knyt/user"
2021-08-01 17:06:33 +00:00
)
2021-08-05 13:35:39 +00:00
func (authMux *AuthMux) PrivateHandleFunc(pattern string, handlerFunc PrivateHandlerFunc) {
2021-08-01 17:06:33 +00:00
authMux.mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
2021-08-05 13:35:39 +00:00
usr, err := authMux.getUserFromSession(r)
if err != nil {
authMux.accessDenied(w, r)
2021-08-01 17:06:33 +00:00
return
}
2021-08-05 13:35:39 +00:00
handlerFunc(usr, w, r)
2021-08-01 17:06:33 +00:00
})
}
func (authMux *AuthMux) accessDenied(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusForbidden)
fmt.Fprintf(w, "Forbidden")
}
2021-08-04 15:10:56 +00:00
func (authMux *AuthMux) getUserFromSession(r *http.Request) (*user.User, error) {
2021-08-01 17:06:33 +00:00
authCookie, err := r.Cookie("knyt-auth")
if err != nil {
2021-08-02 18:08:16 +00:00
fmt.Printf("%v\n", err)
2021-08-04 15:10:56 +00:00
return nil, fmt.Errorf("invalid cookie")
2021-08-01 17:06:33 +00:00
}
2021-08-04 22:12:28 +00:00
usr, usrErr := authMux.app.GetUserById(authCookie.Value)
2021-08-01 17:06:33 +00:00
if usrErr != nil {
2021-08-04 15:10:56 +00:00
return nil, fmt.Errorf("invalid cookie")
2021-08-01 17:06:33 +00:00
}
2021-08-04 15:10:56 +00:00
return usr, nil
2021-08-01 17:06:33 +00:00
}