-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
118 lines (94 loc) · 2.52 KB
/
handlers.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package internal
import (
"fmt"
"log"
"net/http"
"strconv"
"time"
"github.com/pquerna/otp/totp"
)
func LoginHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
w.Header().Set("Content-Type", "text/html")
_, _ = w.Write([]byte(rendorLoginFormTpl("")))
return
}
if r.Method == http.MethodPost {
if time.Since(lastLoginAttemptTime) < time.Duration(LoginStopSeconds) * time.Second {
msg := fmt.Sprintf("Slow down. Hold your horses for %d seconds.", LoginStopSeconds)
log.Print(msg)
w.WriteHeader(http.StatusTooManyRequests)
_, _ = w.Write([]byte(rendorLoginFormTpl(msg)))
return
}
lastLoginAttemptTime = time.Now()
_ = r.ParseForm()
code := r.PostForm.Get("code")
if Password != "" { // check hash with password
hash := r.PostForm.Get("hash")
hash64, _ := strconv.ParseInt(hash, 10, 32)
localHash := simpleHash(Password + code)
if hash64 != localHash {
log.Println("login failed for hash check")
w.Header().Set("Content-Type", "text/html")
_, _ = w.Write([]byte(rendorLoginFormTpl("Login failed")))
return
}
}
originalURI := r.URL.RawQuery
if originalURI == "" {
originalURI = "/"
}
if totp.Validate(code, Secret) {
jwtToken := jwtManager.GenerateToken("0")
http.SetCookie(w, &http.Cookie{
Name: CookieName,
Value: jwtToken,
Path: "/",
Domain: "",
Expires: time.Now().Add(time.Second * time.Duration(MaxAge)),
RawExpires: "",
MaxAge: 0,
Secure: false,
HttpOnly: false,
SameSite: 0,
Raw: "",
Unparsed: nil,
})
log.Print("login success")
http.Redirect(w, r, originalURI, http.StatusFound)
return
}
log.Print("login failed")
w.Header().Set("Content-Type", "text/html")
_, _ = w.Write([]byte(rendorLoginFormTpl("Login failed")))
return
}
w.WriteHeader(http.StatusNotFound)
}
// CheckAuthHandler validate jwt in cookies, response 401 when invalid
func CheckAuthHandler(w http.ResponseWriter, r *http.Request) {
jwtCookie, err := r.Cookie(CookieName)
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
return
}
jwtToken := jwtCookie.Value
ok, err := jwtManager.Valid(jwtToken, "0")
if ok {
w.WriteHeader(http.StatusOK)
return
}
log.Print("auth failed ", err)
w.WriteHeader(http.StatusUnauthorized)
}
// simpleHash
func simpleHash(input string) int64 {
var hash int32 = 0
for i := 0; i < len(input); i++ {
char := input[i]
hash = (hash<<5 + hash) + int32(char)
hash &= hash
}
return int64(hash)
}