aboutsummaryrefslogtreecommitdiffstats
path: root/api/middleware/auth.go
blob: 438a8a1f407ae06f130a2c6c43448cca22a9a15e (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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package middleware

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"strings"

	"github.com/LMBishop/confplanner/api/dto"
	"github.com/LMBishop/confplanner/pkg/session"
	"github.com/LMBishop/confplanner/pkg/user"
)

func MustAuthenticate(service user.Service, store session.Service) func(http.HandlerFunc) http.HandlerFunc {
	return func(next http.HandlerFunc) http.HandlerFunc {
		return func(w http.ResponseWriter, r *http.Request) {
			authHeader := r.Header.Get("Authorization")
			token, err := extractBearerToken(authHeader)
			if err != nil {
				dto.WriteDto(w, r, &dto.ErrorResponse{
					Code:    http.StatusUnauthorized,
					Message: "Unauthorized",
				})
				return
			}

			s := store.GetByToken(token)
			if s == nil {
				dto.WriteDto(w, r, &dto.ErrorResponse{
					Code:    http.StatusUnauthorized,
					Message: "Unauthorized",
				})
				return
			}

			u, err := service.GetUserByID(s.UserID)
			if err != nil {
				if errors.Is(err, user.ErrUserNotFound) {
					store.Destroy(s.SessionID)
					dto.WriteDto(w, r, &dto.ErrorResponse{
						Code:    http.StatusForbidden,
						Message: "Invalid session",
					})
					return
				}

				return
			}

			s.Username = u.Username
			s.Admin = u.Admin

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

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

func extractBearerToken(header string) (string, error) {
	const prefix = "Bearer "
	if header == "" {
		return "", fmt.Errorf("authorization header missing")
	}
	if !strings.HasPrefix(header, prefix) {
		return "", fmt.Errorf("invalid authorization scheme")
	}
	token := strings.TrimSpace(header[len(prefix):])
	if token == "" {
		return "", fmt.Errorf("token is empty")
	}
	return token, nil
}