-
Notifications
You must be signed in to change notification settings - Fork 158
/
auth.go
66 lines (51 loc) · 1.25 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
package httpjson
import (
"crypto/sha256"
"crypto/subtle"
"net/http"
"strings"
)
type RPCAuthType byte
const (
UsernamePassword RPCAuthType = 0x01
)
type Authorization interface {
GetAuthType() RPCAuthType
CheckAuth(s *RPCServer, r *http.Request) bool
}
type UserPassword struct {
Username string
PasswordHash string
}
func NewUserPassword(username string, passwordHash string) Authorization {
return &UserPassword{
Username: username,
PasswordHash: passwordHash,
}
}
func (up *UserPassword) GetAuthType() RPCAuthType {
return UsernamePassword
}
func (up *UserPassword) CheckAuth(s *RPCServer, r *http.Request) bool {
target := up.Username + ":" + up.PasswordHash
targetHash := sha256.Sum256([]byte(target))
metadata := r.Header["Authorization"]
if len(metadata) <= 0 {
return false
}
metadataSlice := strings.Split(metadata[0], ":")
if len(metadataSlice) != 2 {
return false
}
username := metadataSlice[0]
password := metadataSlice[1]
pwdHash := sha256.Sum256([]byte(password))
pwdHash2 := sha256.Sum256([]byte(pwdHash[:]))
login := username + ":" + string(pwdHash2[:])
loginHash := sha256.Sum256([]byte(login))
cmp := subtle.ConstantTimeCompare(loginHash[:], targetHash[:])
if cmp == 1 {
return true
}
return false
}