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

import (
	"crypto/subtle"
	"fmt"
	"net/http"
	"strings"

	"git.leonardobishop.net/stash/api/dto"
)

func MustAuthenticate(token string) 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")
			givenToken, err := extractBearerToken(authHeader)
			if err != nil {
				dto.WriteDto(w, r, &dto.ErrorResponse{
					Code:    http.StatusUnauthorized,
					Message: "Unauthorized",
				})
				return
			}

			if subtle.ConstantTimeCompare([]byte(token), []byte(givenToken)) != 1 {
				dto.WriteDto(w, r, &dto.ErrorResponse{
					Code:    http.StatusForbidden,
					Message: "Forbidden",
				})
				return
			}

			next(w, r)
		}
	}
}

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
}