/
authmiddleware.go
51 lines (43 loc) · 1.15 KB
/
authmiddleware.go
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 main
import (
"net/http"
"strings"
"github.com/app-nerds/fireplace/v2/pkg"
"github.com/app-nerds/nerdweb/v2"
"github.com/sirupsen/logrus"
)
type authMiddleware struct {
logger *logrus.Entry
password string
}
/*
NewAuthMiddleware creates a new authentication middleware struct
*/
func NewAuthMiddleware(logger *logrus.Entry, password string) *authMiddleware {
return &authMiddleware{
logger: logger.WithField("who", "Authentication Middleware"),
password: password,
}
}
/*
Middleware is a middleware that authorizes Fireplace requests
*/
func (m *authMiddleware) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
authHeaderSplit := strings.Split(authHeader, " ")
if len(authHeaderSplit) < 2 {
nerdweb.WriteJSON(m.logger, w, http.StatusBadRequest, pkg.GenericResponse{
Message: "Invalid authorization header",
})
return
}
if authHeaderSplit[1] != m.password {
nerdweb.WriteJSON(m.logger, w, http.StatusForbidden, pkg.GenericResponse{
Message: "Forbidden",
})
return
}
next.ServeHTTP(w, r)
})
}