package server import ( "net/http" "time" ) const sessionMaxAge = 7 * 86400 func (s *Server) requireAuth(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { cookie, err := r.Cookie("ydropbox_session") if err != nil { http.Error(w, "Unauthorized", http.StatusUnauthorized) return } s.mu.Lock() createdAt, exists := s.sessions[cookie.Value] if exists && time.Now().Unix()-createdAt > sessionMaxAge { delete(s.sessions, cookie.Value) exists = false } if exists { s.sessions[cookie.Value] = time.Now().Unix() } s.mu.Unlock() if !exists { http.Error(w, "Unauthorized", http.StatusUnauthorized) return } next(w, r) } } func (s *Server) requireAuthPage(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { cookie, err := r.Cookie("ydropbox_session") if err != nil { http.Redirect(w, r, "/login", http.StatusFound) return } s.mu.Lock() createdAt, exists := s.sessions[cookie.Value] if exists && time.Now().Unix()-createdAt > sessionMaxAge { delete(s.sessions, cookie.Value) exists = false } if exists { s.sessions[cookie.Value] = time.Now().Unix() } s.mu.Unlock() if !exists { http.Redirect(w, r, "/login", http.StatusFound) return } next(w, r) } }