diff options
Diffstat (limited to 'cmd/web/middleware')
| -rw-r--r-- | cmd/web/middleware/auth.go | 67 |
1 files changed, 66 insertions, 1 deletions
diff --git a/cmd/web/middleware/auth.go b/cmd/web/middleware/auth.go index b53980a..911eb44 100644 --- a/cmd/web/middleware/auth.go +++ b/cmd/web/middleware/auth.go @@ -12,12 +12,74 @@ type AuthMiddleware struct { Db *sql.DB } +func (auth *AuthMiddleware) CheckAndInvalidate(next http.HandlerFunc) http.HandlerFunc { + return http.HandlerFunc( + func (w http.ResponseWriter, r *http.Request) { + cookie, err := r.Cookie("paterissa_session_token") + if err != nil { + next.ServeHTTP(w, r) + return + } + + stmt, err := auth.Db.Prepare("SELECT * FROM cookies WHERE content = $1;") + if err != nil { + cookie = &http.Cookie{ + Name: "paterissa_session_token", + Value: "", + Path: "/", + MaxAge: -1, + HttpOnly: true, + } + http.SetCookie(w, cookie) + http.Redirect(w, r, "/", http.StatusFound) + return + } + defer stmt.Close() + + var id int + var content string + var userId int + var expiration time.Time + + row := stmt.QueryRow(cookie.Value) + err = row.Scan(&id, &content, &userId, &expiration) + if err != nil { + cookie = &http.Cookie{ + Name: "paterissa_session_token", + Value: "", + Path: "/", + MaxAge: -1, + HttpOnly: true, + } + http.SetCookie(w, cookie) + http.Redirect(w, r, "/", http.StatusFound) + return + } + + if time.Now().After(expiration) { + cookie = &http.Cookie{ + Name: "paterissa_session_token", + Value: "", + Path: "/", + MaxAge: -1, + HttpOnly: true, + } + http.SetCookie(w, cookie) + http.Redirect(w, r, "/", http.StatusFound) + return + } + + next.ServeHTTP(w, r) + return + }) +} + func (auth *AuthMiddleware) Resolve(next http.HandlerFunc) http.HandlerFunc { return http.HandlerFunc( func (w http.ResponseWriter, r *http.Request) { cookie, err := r.Cookie("paterissa_session_token") if err != nil { - w.WriteHeader(401) + w.WriteHeader(http.StatusUnauthorized) w.Write([]byte("Unauthorized")) return } @@ -35,6 +97,7 @@ func (auth *AuthMiddleware) Resolve(next http.HandlerFunc) http.HandlerFunc { w.Write([]byte("Unauthorized")) auth.Err.Printf("Could not retrieve cookie from DB: %v\n", err) + http.Redirect(w, r, "/", http.StatusUnauthorized) return } defer stmt.Close() @@ -58,6 +121,7 @@ func (auth *AuthMiddleware) Resolve(next http.HandlerFunc) http.HandlerFunc { w.Write([]byte("Unauthorized")) auth.Err.Printf("Could not retrieve cookie from DB: %v\n", err) + http.Redirect(w, r, "/", http.StatusUnauthorized) return } @@ -72,6 +136,7 @@ func (auth *AuthMiddleware) Resolve(next http.HandlerFunc) http.HandlerFunc { http.SetCookie(w, cookie) w.Write([]byte("Expired")) + http.Redirect(w, r, "/", http.StatusUnauthorized) return } |
