GetSession returns the *Session for this request. If the remote user has specified a username and password in the request then it is validated against the user database. If valid it sets a cookie and returns the newly created session object. If the remote user has specified invalid credentials the
(w http.ResponseWriter, r *http.Request, req *saml.IdpAuthnRequest)
| 34 | // If neither credentials nor a valid session cookie exist, this function |
| 35 | // sends a login form and returns nil. |
| 36 | func (s *Server) GetSession(w http.ResponseWriter, r *http.Request, req *saml.IdpAuthnRequest) *saml.Session { |
| 37 | // if we received login credentials then maybe we can create a session |
| 38 | if r.Method == "POST" && r.PostForm.Get("user") != "" { |
| 39 | user := User{} |
| 40 | if err := s.Store.Get(fmt.Sprintf("/users/%s", r.PostForm.Get("user")), &user); err != nil { |
| 41 | s.sendLoginForm(w, r, req, "Invalid username or password") |
| 42 | return nil |
| 43 | } |
| 44 | |
| 45 | if err := bcrypt.CompareHashAndPassword(user.HashedPassword, []byte(r.PostForm.Get("password"))); err != nil { |
| 46 | s.sendLoginForm(w, r, req, "Invalid username or password") |
| 47 | return nil |
| 48 | } |
| 49 | |
| 50 | session := &saml.Session{ |
| 51 | ID: base64.StdEncoding.EncodeToString(randomBytes(32)), |
| 52 | NameID: user.Email, |
| 53 | CreateTime: saml.TimeNow(), |
| 54 | ExpireTime: saml.TimeNow().Add(sessionMaxAge), |
| 55 | Index: hex.EncodeToString(randomBytes(32)), |
| 56 | UserName: user.Name, |
| 57 | Groups: user.Groups[:], |
| 58 | UserEmail: user.Email, |
| 59 | UserCommonName: user.CommonName, |
| 60 | UserSurname: user.Surname, |
| 61 | UserGivenName: user.GivenName, |
| 62 | UserScopedAffiliation: user.ScopedAffiliation, |
| 63 | } |
| 64 | if err := s.Store.Put(fmt.Sprintf("/sessions/%s", session.ID), &session); err != nil { |
| 65 | http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) |
| 66 | return nil |
| 67 | } |
| 68 | |
| 69 | http.SetCookie(w, &http.Cookie{ |
| 70 | Name: "session", |
| 71 | Value: session.ID, |
| 72 | MaxAge: int(sessionMaxAge.Seconds()), |
| 73 | HttpOnly: true, |
| 74 | Secure: r.URL.Scheme == "https", |
| 75 | Path: "/", |
| 76 | }) |
| 77 | return session |
| 78 | } |
| 79 | |
| 80 | if sessionCookie, err := r.Cookie("session"); err == nil { |
| 81 | session := &saml.Session{} |
| 82 | if err := s.Store.Get(fmt.Sprintf("/sessions/%s", sessionCookie.Value), session); err != nil { |
| 83 | if err == ErrNotFound { |
| 84 | s.sendLoginForm(w, r, req, "") |
| 85 | return nil |
| 86 | } |
| 87 | http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) |
| 88 | return nil |
| 89 | } |
| 90 | |
| 91 | if saml.TimeNow().After(session.ExpireTime) { |
| 92 | s.sendLoginForm(w, r, req, "") |
| 93 | return nil |
no test coverage detected