A community based topic aggregation platform built on atproto
1package oauth 2 3import ( 4 "log" 5 "net/http" 6 7 oauthCore "Coves/internal/core/oauth" 8) 9 10// LogoutHandler handles user logout 11type LogoutHandler struct { 12 sessionStore oauthCore.SessionStore 13} 14 15// NewLogoutHandler creates a new logout handler 16func NewLogoutHandler(sessionStore oauthCore.SessionStore) *LogoutHandler { 17 return &LogoutHandler{ 18 sessionStore: sessionStore, 19 } 20} 21 22// HandleLogout logs out the current user 23// POST /oauth/logout 24func (h *LogoutHandler) HandleLogout(w http.ResponseWriter, r *http.Request) { 25 if r.Method != http.MethodPost { 26 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) 27 return 28 } 29 30 // Get HTTP session 31 cookieStore := GetCookieStore() 32 httpSession, err := cookieStore.Get(r, sessionName) 33 if err != nil || httpSession.IsNew { 34 // No session to logout 35 http.Redirect(w, r, "/", http.StatusFound) 36 return 37 } 38 39 // Get DID from session 40 did, ok := httpSession.Values[sessionDID].(string) 41 if !ok || did == "" { 42 // No DID in session 43 http.Redirect(w, r, "/", http.StatusFound) 44 return 45 } 46 47 // Delete OAuth session from database 48 if err := h.sessionStore.DeleteSession(did); err != nil { 49 log.Printf("Failed to delete OAuth session for DID %s: %v", did, err) 50 // Continue with logout anyway 51 } 52 53 // Clear HTTP session cookie 54 httpSession.Options.MaxAge = -1 // Delete cookie 55 if err := httpSession.Save(r, w); err != nil { 56 log.Printf("Failed to clear HTTP session: %v", err) 57 } 58 59 // Redirect to home 60 http.Redirect(w, r, "/", http.StatusFound) 61} 62 63// GetCurrentUser returns the currently authenticated user's DID 64// Helper function for other handlers 65func GetCurrentUser(r *http.Request) (string, error) { 66 cookieStore := GetCookieStore() 67 httpSession, err := cookieStore.Get(r, sessionName) 68 if err != nil || httpSession.IsNew { 69 return "", err 70 } 71 72 did, ok := httpSession.Values[sessionDID].(string) 73 if !ok || did == "" { 74 return "", nil 75 } 76 77 return did, nil 78} 79 80// GetCurrentUserOrError returns the current user's DID or sends an error response 81// Helper function for protected handlers 82func GetCurrentUserOrError(w http.ResponseWriter, r *http.Request) (string, bool) { 83 did, err := GetCurrentUser(r) 84 if err != nil || did == "" { 85 http.Error(w, "Unauthorized", http.StatusUnauthorized) 86 return "", false 87 } 88 89 return did, true 90}