-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
101 lines (94 loc) · 3.29 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package main
import (
"context"
"encoding/base64"
"errors"
"net/http"
"regexp"
"strings"
"time"
"github.com/patrickmn/go-cache"
"github.com/thecsw/katya/storage"
"github.com/thecsw/katya/utils"
)
var (
// attemptCooldown is how many times you have between bad logins
attemptCooldown = 14 * time.Minute
// badLoginAttempts caches users' bad login attempts
badLoginAttempts = cache.New(attemptCooldown, attemptCooldown)
// usernameRegexp is a regex that every username should follow
usernameRegexp = regexp.MustCompile(`^[-a-zA-Z0-9]{3,16}$`)
// passwordRegexp is a regex that every password should follow
passwordRegexp = regexp.MustCompile(`^[^ ]{2,32}$`)
)
// ContextKey is a type alias to string
type ContextKey string
// loggingMiddleware does a full validation AND authentication for a Basic Auth attempt
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ipAddr, err := utils.ExtractIP(r)
if err != nil {
httpJSON(w, nil, http.StatusBadRequest, errors.New("unknown origin"))
return
}
if number, found := badLoginAttempts.Get(ipAddr); found && number.(uint) >= 4 {
httpJSON(w, nil, http.StatusForbidden, errors.New("origin blocked"))
return
}
tokens := strings.Split(r.Header.Get("Authorization"), "Basic ")
if len(tokens) != 2 {
httpJSON(w, nil, http.StatusBadRequest, errors.New("no basic auth provided"))
return
}
decoded, err := base64.StdEncoding.DecodeString(tokens[1])
if err != nil {
httpJSON(w, nil, http.StatusBadRequest, errors.New("base64 decoding failed"))
return
}
credentials := strings.Split(string(decoded), ":")
if len(credentials) != 2 {
httpJSON(w, nil, http.StatusBadRequest, errors.New("basic auth is malformed"))
return
}
user, pass := credentials[0], credentials[1]
if user == "" {
httpJSON(w, nil, http.StatusBadRequest, errors.New("bad user credentials"))
return
}
// Quickly sanitize the username and the password
if !usernameRegexp.MatchString(user) || !passwordRegexp.MatchString(pass) {
httpJSON(w, nil, http.StatusBadRequest, errors.New("bad user credentials"))
return
}
foundUser, err := storage.GetUser(user, true)
if err != nil || foundUser.Name == "" {
httpJSON(w, nil, http.StatusForbidden, errors.New("bad user credentials"))
return
}
if foundUser.Password != utils.ShaEncode(pass) {
httpJSON(w, nil, http.StatusForbidden, errors.New("bad user credentials"))
// Someone is maybe trying to guess the password
_ = badLoginAttempts.Add(ipAddr, uint(0), cache.DefaultExpiration)
_, _ = badLoginAttempts.IncrementUint(ipAddr, 1)
return
}
foundUser.BasicToken = string(r.Header.Get("Authorization"))
newContext := context.WithValue(context.TODO(), ContextKey("user"), *foundUser)
next.ServeHTTP(w, r.WithContext(newContext))
})
}
// verifyAuth verifies that the credentials are OK
func verifyAuth(w http.ResponseWriter, r *http.Request) {
user := r.Context().Value(ContextKey("user")).(storage.User)
userCookie := http.Cookie{
Name: "user",
Path: "/",
Value: user.BasicToken,
Domain: "sandyuraz.com",
Expires: time.Now().Add(7 * 24 * time.Hour),
Secure: true,
HttpOnly: true,
}
http.SetCookie(w, &userCookie)
httpJSON(w, httpMessageReturn{Message: "OK"}, http.StatusOK, nil)
}