aboutsummaryrefslogtreecommitdiff
path: root/backend/internal/server/middleware/auth.go
blob: f01e4b949ee679be4f405d387b093ffd8b01f8e6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package middleware

import (
	"context"
	"net/http"
	"time"

	"ibd-trader/internal/database"
)

const SessionCookie = "_session"

func Auth(store database.SessionStore) func(next http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			// Get session cookie
			cookie, err := r.Cookie(SessionCookie)
			if err != nil {
				http.Error(w, "Unauthorized", http.StatusUnauthorized)
				return
			}

			// Check session
			session, err := store.GetSession(r.Context(), cookie.Value)
			if err != nil {
				http.Error(w, "Error getting session", http.StatusInternalServerError)
				return
			}
			if session == nil {
				http.Error(w, "Unauthorized", http.StatusUnauthorized)
				return
			}

			// Check session expiry
			if session.OAuthToken.Expiry.Before(time.Now()) {
				http.Error(w, "Session expired", http.StatusUnauthorized)
				return
			}

			// Add session to context
			ctx := context.WithValue(r.Context(), "session", session)

			next.ServeHTTP(w, r.WithContext(ctx))
		})
	}
}