-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.go
More file actions
36 lines (32 loc) · 1015 Bytes
/
middleware.go
File metadata and controls
36 lines (32 loc) · 1015 Bytes
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
package gobaserver
import (
"errors"
"github.com/valyala/fasthttp"
)
// ErrInvalidCredentials occurs when credentials have been
// provided to an endpoint that are not known to the server.
var ErrInvalidCredentials = errors.New("invalid credentials")
// authMiddleware validates the request's authorization
// header and calls the given handler if they are valid.
func (s Server) authMiddleware(handler handlerFunc) handlerFunc {
return func(ctx *fasthttp.RequestCtx) error {
authHeader := ctx.Request.Header.Peek("Authorization")
creds, err := credentialsFromHeader(string(authHeader))
if err != nil {
return err
}
if !s.credentialsValid(*creds) {
return ErrInvalidCredentials
}
return handler(ctx)
}
}
// credentialsValid reports whether the given credentials are known to the server.
func (s Server) credentialsValid(creds Credentials) bool {
for _, c := range s.credentials {
if c.Username == creds.Username && c.Password == creds.Password {
return true
}
}
return false
}