diff --git a/cmd/calls/images.go b/cmd/calls/images.go index de316b0..ea0504a 100644 --- a/cmd/calls/images.go +++ b/cmd/calls/images.go @@ -10,7 +10,7 @@ import ( func ServeImage(c *b.Config, s map[string]*f.Session) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - if _, err := f.ManageSession(w, r, c, s); err != nil { + if _, err := f.ValidateSession(w, r, c, s); err != nil { if !tokenIsVerified(w, r, c) { return } diff --git a/cmd/frontend/sessions.go b/cmd/frontend/sessions.go index 2a4b59d..71c7d94 100644 --- a/cmd/frontend/sessions.go +++ b/cmd/frontend/sessions.go @@ -64,31 +64,39 @@ func StartSessions() (map[string]*Session, chan string) { return sessions, sessionExpiryChan } -// ManageSession is used for verifying that the user is logged in and returns -// their session and an error. It also handles cases where the user is not -// logged in. -func ManageSession(w http.ResponseWriter, r *http.Request, c *b.Config, s map[string]*Session) (*Session, error) { - tmpl, tmplErr := template.ParseFiles(filepath.Join(c.WebDir, "templates", "index.html"), filepath.Join(c.WebDir, "templates", "login.html")) - +// ValidateSession is used for verifying that the user is logged in and returns +// their session and an error. +func ValidateSession(w http.ResponseWriter, r *http.Request, c *b.Config, s map[string]*Session) (*Session, error) { cookie, err := r.Cookie("cpolis_session") if err != nil { - if err = template.Must(tmpl, tmplErr).ExecuteTemplate(w, "page-content", nil); err != nil { - return nil, fmt.Errorf("error executing template: %v", err) - } - return nil, errors.New("no cookie set") } session, ok := s[cookie.Value] if !ok { - cookie.Expires = time.Now() - http.SetCookie(w, cookie) + return nil, errors.New("session does not exist") + } + return session, nil +} + +// ManageSession is used for verifying that the user is logged in and returns +// their session and an error. It also handles cases where the user is not +// logged in. +func ManageSession(w http.ResponseWriter, r *http.Request, c *b.Config, s map[string]*Session) (*Session, error) { + session, err := ValidateSession(w, r, c, s) + if err != nil { + if session.cookie != nil { + session.cookie.Expires = time.Now() + http.SetCookie(w, session.cookie) + } + + tmpl, tmplErr := template.ParseFiles(filepath.Join(c.WebDir, "templates", "index.html"), filepath.Join(c.WebDir, "templates", "login.html")) if err = template.Must(tmpl, tmplErr).ExecuteTemplate(w, "page-content", nil); err != nil { return nil, fmt.Errorf("error executing template: %v", err) } - return nil, errors.New("session does not exist") + return nil, err } session.cookie.Expires = time.Now().Add(time.Hour * time.Duration(c.CookieExpiryHours))