summaryrefslogtreecommitdiff
path: root/internal/api/middleware/middleware.go
blob: d7c5a30c5f3c2a000049823e7a56d5a9c152d639 (plain)
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
package middleware

import (
	"context"
	"encoding/json"
	"net/http"

	"github.com/boozec/rahanna/internal/api/auth"
)

// AuthMiddleware ensures that the requester has passed the Authorization
// header with a valid JWY token.
// It passes the claims item via context
func AuthMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		tokenString := r.Header.Get("Authorization")

		payloadMap := map[string]string{"error": "unauthorized"}
		payload, _ := json.Marshal(payloadMap)

		if tokenString == "" {
			w.Header().Set("Content-Type", "application/json")
			w.WriteHeader(http.StatusUnauthorized)

			w.Write([]byte(payload))
			return
		}

		claims, err := auth.ValidateJWT(tokenString)
		if err != nil {
			w.WriteHeader(http.StatusUnauthorized)

			payload, _ := json.Marshal(payloadMap)

			w.Write([]byte(payload))
			return
		}

		ctx := context.WithValue(r.Context(), "claims", claims)

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