diff options
Diffstat (limited to 'middleware.go')
-rw-r--r-- | middleware.go | 107 |
1 files changed, 107 insertions, 0 deletions
diff --git a/middleware.go b/middleware.go new file mode 100644 index 0000000..33aeae0 --- /dev/null +++ b/middleware.go @@ -0,0 +1,107 @@ +package main + +import ( + "context" + "encoding/base64" + "fmt" + "log" + "net/http" + "strings" + "time" +) + +type User struct { + UserId string + UserName string + DisplayName string + Email string + Active bool + Staff bool +} + +func GetUser(req *http.Request) (*User, error) { + if user_header, ok := req.Header[pwman.RemoteUserHeader]; ok { + // If mre than one header abort + if len(user_header) != 1 { + return nil, fmt.Errorf("Expected one user, but got multiple") + } + // Got user lets go + userid := user_header[0] + //utf8 decode? + first_name := first(req.Header["Givenname"]) + last_name := first(req.Header["Sn"]) + email := first(req.Header["Mail"]) + affiliations := req.Header["Affiliation"] + is_staff := contains(affiliations, "employee@nordu.net") + is_active := is_staff || contains(affiliations, "member@nordu.net") + username := strings.Split(userid, "@")[0] + + return &User{ + userid, + username, + fmt.Sprintf("%v %v", first_name, last_name), + email, + is_active, + is_staff}, nil + } + return nil, fmt.Errorf("No user found") +} + +func RemoteUser(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + + user, err := GetUser(req) + if err != nil { + log.Println("ERROR:", err) + http.Error(w, "Please log in", http.StatusUnauthorized) + return + } + // consider redirect to login with next + + ctx := req.Context() + ctx = context.WithValue(ctx, "user", user) + + next.ServeHTTP(w, req.WithContext(ctx)) + }) +} + +func FlashMessage(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + clear := &http.Cookie{Name: "flashmsg", MaxAge: -1, Expires: time.Unix(1, 0)} + // Get flash from cookie + cookie, err := req.Cookie("flashmsg") + if err != nil { + next.ServeHTTP(w, req) + return + } + + msgB, err := base64.URLEncoding.DecodeString(cookie.Value) + if err != nil { + //unset flash message + http.SetCookie(w, clear) + next.ServeHTTP(w, req) + return + } + + msg := string(msgB) + msg_parts := strings.Split(msg, ";_;") + flash_class := "info" + if len(msg_parts) == 2 { + if msg_parts[1] != "" { + flash_class = msg_parts[1] + } + msg = msg_parts[0] + } + ctx := req.Context() + ctx = context.WithValue(ctx, "flash", msg) + ctx = context.WithValue(ctx, "flash_class", flash_class) + http.SetCookie(w, clear) + next.ServeHTTP(w, req.WithContext(ctx)) + }) +} + +func SetFlashMessage(w http.ResponseWriter, msg, class string) { + enc_message := base64.URLEncoding.EncodeToString([]byte(fmt.Sprintf("%s;_;%s", msg, class))) + flash_cookie := &http.Cookie{Name: "flashmsg", Value: enc_message} + http.SetCookie(w, flash_cookie) +} |