knowyt/server/src/handler/private.go

55 lines
1.2 KiB
Go
Raw Normal View History

2021-08-01 17:06:33 +00:00
package handler
import (
"fmt"
"net/http"
"sirlab.de/go/knowyt/user"
"strings"
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) {
authCookie, err := r.Cookie("knowyt-auth")
2021-08-01 17:06:33 +00:00
if err != nil {
2021-08-04 15:10:56 +00:00
return nil, fmt.Errorf("invalid cookie")
2021-08-01 17:06:33 +00:00
}
vals := strings.SplitN(authCookie.Value, ":", 2)
usr, usrErr := authMux.app.GetUserById(vals[0])
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
}
if usr.GetAuthCode() != vals[1] {
return nil, fmt.Errorf("invalid cookie")
}
2022-03-25 19:46:08 +00:00
if usr.IsAdmin() {
if cookieCameo, err := r.Cookie("knowyt-auth-cameo"); err == nil {
if usrNew, err := authMux.app.GetUserById(cookieCameo.Value); err == nil {
usrNew.SetCameo(usr)
return usrNew, nil
}
}
}
2021-08-04 15:10:56 +00:00
return usr, nil
2021-08-01 17:06:33 +00:00
}