-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
59 lines (48 loc) · 1.33 KB
/
auth.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
52
53
54
55
56
57
58
59
package middlewares
import (
"encoding/base64"
"fmt"
"net/http"
"strings"
"github.com/Impisigmatus/service_core/utils"
)
type authorization struct {
next http.Handler
secrets []string
}
func Authorization(secrets []string) Middleware {
return func(next http.Handler) http.Handler {
return &authorization{
next: next,
secrets: secrets,
}
}
}
func (auth *authorization) ServeHTTP(w http.ResponseWriter, r *http.Request) {
const header = "Authorization"
authorization := r.Header.Get(header)
if !strings.HasPrefix(authorization, "Basic") {
utils.WriteString(w, http.StatusUnauthorized, fmt.Errorf("Invalid type"), "Неверный тип авторизации")
return
}
if err := auth.basic(w, authorization); err != nil {
utils.WriteString(w, http.StatusUnauthorized, err, "Неверные логин или пароль")
return
}
auth.next.ServeHTTP(w, r)
}
func (auth *authorization) basic(w http.ResponseWriter, header string) error {
const prefix = "Basic "
authorization := header[len(prefix):]
data, err := base64.StdEncoding.DecodeString(authorization)
if err != nil {
return fmt.Errorf("Invalid decode basic authorization: %s", err)
}
decoded := string(data)
for _, secret := range auth.secrets {
if decoded == secret {
return nil
}
}
return fmt.Errorf("Invalid basic authorization")
}