aboutsummaryrefslogtreecommitdiffstats
path: root/api/middleware/auth.go
blob: eb362b09edcf49c0b87d2b50c4275f1814bf51d3 (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
package middleware

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

	"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) {
			var sessionToken string
			for _, cookie := range r.Cookies() {
				if cookie.Name == "confplanner_session" {
					sessionToken = cookie.Value
					break
				}
			}

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

			_, 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
			}

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

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