Create ValidateSession() to not have unwanted side effects when validating session

This commit is contained in:
Jason Streifling 2025-01-19 20:10:51 +01:00
parent 7b04149a28
commit f99358729c
2 changed files with 22 additions and 14 deletions

View File

@ -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
}

View File

@ -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))