/
handlers.go
167 lines (125 loc) · 3.67 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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
package main
import (
"crypto/rand"
"crypto/sha512"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"strconv"
"sync"
"time"
"github.com/gorilla/mux"
)
var HashRequests = make(map[int]HashResponse)
var Mutex sync.RWMutex
var IsShuttingDown = false
func OnShuttingDown(shuttingDown bool) {
IsShuttingDown = shuttingDown
}
func CreateHashPasswordRequest(writer http.ResponseWriter, request *http.Request) {
if IsShuttingDown {
handleShuttingDown(writer)
}
cleanupRequests()
var req HashRequest
decoder := json.NewDecoder(request.Body)
decoder.Decode(&req)
if len(req.Password) == 0 {
writer.Header().Add("Content-type", "application/json")
writer.WriteHeader(http.StatusBadRequest)
json.NewEncoder(writer).Encode("{message: Password is a required input}")
return
}
numRequests := len(HashRequests)
numRequests++
Mutex.Lock()
HashRequests[numRequests] = HashResponse{
numRequests,
time.Now(),
time.Time{},
req.Password,
"",
}
Mutex.Unlock()
writer.Header().Add("Content-type", "application/json")
writer.WriteHeader(http.StatusAccepted)
json.NewEncoder(writer).Encode(fmt.Sprintf(`{requestNumber: %d}`, (numRequests)))
}
func GetHashStats(writer http.ResponseWriter, request *http.Request) {
if IsShuttingDown {
handleShuttingDown(writer)
}
cleanupRequests()
count := len(HashRequests)
if count <= 0 {
writer.Header().Add("Content-type", "application/json")
writer.WriteHeader(http.StatusBadRequest)
json.NewEncoder(writer).Encode("{message: No password requests have been submitted and no stats are available}")
return
}
var avg int64
for _, val := range HashRequests {
avg += val.initiatedOn.Sub(val.hashedOn).Microseconds()
}
avg = (avg / int64(count))
writer.Header().Add("Content-type", "application/json")
json.NewEncoder(writer).Encode(fmt.Sprintf(`{total: %d, average: %d}`, count, avg))
}
func GetHashedPassword(writer http.ResponseWriter, request *http.Request) {
if IsShuttingDown {
handleShuttingDown(writer)
}
cleanupRequests()
params := mux.Vars(request)
reqNum := params["requestNum"]
num, parsed := strconv.Atoi(reqNum)
if parsed != nil {
panic(parsed)
}
item, ok := HashRequests[num]
if !ok {
writer.Header().Add("Content-type", "application/json")
writer.WriteHeader(http.StatusNotFound)
json.NewEncoder(writer).Encode(fmt.Sprintf(`{message: Request #%d was not found}`, num))
return
} else {
t := item.initiatedOn.Add(time.Second * 5)
diff := time.Now().Sub(t)
if diff.Seconds() >= 5 {
Mutex.Lock()
var salt = generateRandomSalt(10)
var hash = createPasswordHash(item.clearPassword, salt)
item.hashedPassword = hash
writer.Header().Add("Content-type", "application/json")
json.NewEncoder(writer).Encode(fmt.Sprintf(`{hashedPassword: %s}`, item.hashedPassword))
item.hashedOn = time.Now()
Mutex.Unlock()
} else {
writer.WriteHeader(http.StatusAccepted)
}
}
}
func createPasswordHash(password string, salt []byte) string {
var passwordBytes = []byte(password)
var sha512Hasher = sha512.New()
passwordBytes = append(passwordBytes, salt...)
sha512Hasher.Write(passwordBytes)
var hashedPasswordBytes = sha512Hasher.Sum(nil)
var base64EncodedPasswordHash = base64.URLEncoding.EncodeToString(hashedPasswordBytes)
return base64EncodedPasswordHash
}
func generateRandomSalt(saltSize int) []byte {
var salt = make([]byte, saltSize)
_, err := rand.Read(salt[:])
if err != nil {
panic(err)
}
return salt
}
func handleShuttingDown(writer http.ResponseWriter) {
writer.WriteHeader(http.StatusAccepted)
}
func cleanupRequests() {
//Not implemented but handle cleaning up requests over a certain threshold to prevent server memory leaks - currently list is infitinite
}