|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto/rand" |
| 5 | + "encoding/base64" |
| 6 | + "fmt" |
| 7 | + "log" |
| 8 | + "net/http" |
| 9 | + "os" |
| 10 | + "strings" |
| 11 | + "sync" |
| 12 | + "time" |
| 13 | +) |
| 14 | + |
| 15 | +// Session represents a user session |
| 16 | +type Session struct { |
| 17 | + Email string |
| 18 | + CreatedAt time.Time |
| 19 | + ExpiresAt time.Time |
| 20 | +} |
| 21 | + |
| 22 | +// SessionStore manages active sessions |
| 23 | +type SessionStore struct { |
| 24 | + sessions map[string]*Session |
| 25 | + mu sync.RWMutex |
| 26 | +} |
| 27 | + |
| 28 | +var sessionStore = &SessionStore{ |
| 29 | + sessions: make(map[string]*Session), |
| 30 | +} |
| 31 | + |
| 32 | +// generateSessionID creates a random session ID |
| 33 | +func generateSessionID() (string, error) { |
| 34 | + b := make([]byte, 32) |
| 35 | + if _, err := rand.Read(b); err != nil { |
| 36 | + return "", err |
| 37 | + } |
| 38 | + return base64.URLEncoding.EncodeToString(b), nil |
| 39 | +} |
| 40 | + |
| 41 | +// CreateSession creates a new session for the user |
| 42 | +func (s *SessionStore) CreateSession(email string) (string, error) { |
| 43 | + s.mu.Lock() |
| 44 | + defer s.mu.Unlock() |
| 45 | + |
| 46 | + sessionID, err := generateSessionID() |
| 47 | + if err != nil { |
| 48 | + return "", err |
| 49 | + } |
| 50 | + |
| 51 | + session := &Session{ |
| 52 | + Email: email, |
| 53 | + CreatedAt: time.Now(), |
| 54 | + ExpiresAt: time.Now().Add(24 * time.Hour), // 24 hour session |
| 55 | + } |
| 56 | + |
| 57 | + s.sessions[sessionID] = session |
| 58 | + return sessionID, nil |
| 59 | +} |
| 60 | + |
| 61 | +// GetSession retrieves a session by ID |
| 62 | +func (s *SessionStore) GetSession(sessionID string) (*Session, bool) { |
| 63 | + s.mu.RLock() |
| 64 | + defer s.mu.RUnlock() |
| 65 | + |
| 66 | + session, exists := s.sessions[sessionID] |
| 67 | + if !exists { |
| 68 | + return nil, false |
| 69 | + } |
| 70 | + |
| 71 | + // Check if session has expired |
| 72 | + if time.Now().After(session.ExpiresAt) { |
| 73 | + return nil, false |
| 74 | + } |
| 75 | + |
| 76 | + return session, true |
| 77 | +} |
| 78 | + |
| 79 | +// DeleteSession removes a session |
| 80 | +func (s *SessionStore) DeleteSession(sessionID string) { |
| 81 | + s.mu.Lock() |
| 82 | + defer s.mu.Unlock() |
| 83 | + delete(s.sessions, sessionID) |
| 84 | +} |
| 85 | + |
| 86 | +// CleanupExpiredSessions removes expired sessions |
| 87 | +func (s *SessionStore) CleanupExpiredSessions() { |
| 88 | + s.mu.Lock() |
| 89 | + defer s.mu.Unlock() |
| 90 | + |
| 91 | + now := time.Now() |
| 92 | + for id, session := range s.sessions { |
| 93 | + if now.After(session.ExpiresAt) { |
| 94 | + delete(s.sessions, id) |
| 95 | + } |
| 96 | + } |
| 97 | +} |
| 98 | + |
| 99 | +// AuthenticateUser validates email and API key against the database |
| 100 | +func AuthenticateUser(email, apiKey string) (bool, error) { |
| 101 | + email = strings.TrimSpace(email) |
| 102 | + apiKey = strings.TrimSpace(apiKey) |
| 103 | + |
| 104 | + if email == "" || apiKey == "" { |
| 105 | + return false, fmt.Errorf("email and API key are required") |
| 106 | + } |
| 107 | + |
| 108 | + if db == nil { |
| 109 | + return false, fmt.Errorf("database not connected") |
| 110 | + } |
| 111 | + |
| 112 | + accessTbl := os.Getenv("ACCESS_TB") |
| 113 | + if accessTbl == "" { |
| 114 | + accessTbl = "access" |
| 115 | + } |
| 116 | + |
| 117 | + var count int |
| 118 | + query := fmt.Sprintf("SELECT COUNT(*) FROM %s WHERE email = $1 AND api_key = $2", accessTbl) |
| 119 | + err := db.QueryRow(query, email, apiKey).Scan(&count) |
| 120 | + if err != nil { |
| 121 | + return false, fmt.Errorf("authentication query failed: %v", err) |
| 122 | + } |
| 123 | + |
| 124 | + return count > 0, nil |
| 125 | +} |
| 126 | + |
| 127 | +// RequireAuth is middleware that checks if user is authenticated |
| 128 | +func RequireAuth(next http.HandlerFunc) http.HandlerFunc { |
| 129 | + return func(w http.ResponseWriter, r *http.Request) { |
| 130 | + cookie, err := r.Cookie("session_id") |
| 131 | + if err != nil { |
| 132 | + http.Redirect(w, r, "/login", http.StatusSeeOther) |
| 133 | + return |
| 134 | + } |
| 135 | + |
| 136 | + _, exists := sessionStore.GetSession(cookie.Value) |
| 137 | + if !exists { |
| 138 | + http.Redirect(w, r, "/login", http.StatusSeeOther) |
| 139 | + return |
| 140 | + } |
| 141 | + |
| 142 | + next(w, r) |
| 143 | + } |
| 144 | +} |
| 145 | + |
| 146 | +// StartSessionCleanup starts a goroutine to periodically clean up expired sessions |
| 147 | +func StartSessionCleanup() { |
| 148 | + ticker := time.NewTicker(1 * time.Hour) |
| 149 | + go func() { |
| 150 | + for range ticker.C { |
| 151 | + sessionStore.CleanupExpiredSessions() |
| 152 | + log.Println("Cleaned up expired sessions") |
| 153 | + } |
| 154 | + }() |
| 155 | +} |
0 commit comments