-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.go
89 lines (79 loc) · 2.34 KB
/
api.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
package main
import (
"encoding/json"
"net/http"
)
// validateJWTAPIEndPoint decodes a JWT token
func validateJWTAPIEndPoint(w http.ResponseWriter, req *http.Request) {
// Setup vars
var (
request = StaticStruct{}
)
// Try to decode the JSON request
err := json.NewDecoder(req.Body).Decode(&request)
if err != nil {
// Log the error
log.Error(err.Error())
response := map[string]string{"error": err.Error()}
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(response)
return
}
// If we didn't return, validate the strings
isValid, err := validateJWT(&request.JWT)
if err != nil {
log.Error(err.Error())
response := map[string]string{"error": err.Error()}
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(response)
return
}
// If the JWT token is no longer valid
if isValid == false {
response := map[string]bool{"jwtValid": isValid}
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(response)
return
}
// If we didn't return anywhere above, then return a successful response
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]bool{"jwtValid": isValid})
}
// generateJWT decodes a JWT token
func generateJWT(w http.ResponseWriter, req *http.Request) {
// Setup vars
var (
request = LoginDataStruct{}
)
// Try to decode the JSON request
err := json.NewDecoder(req.Body).Decode(&request)
if err != nil {
// Log the error
log.Error(err.Error())
response := map[string]string{"error": err.Error()}
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(response)
return
}
// If we didn't return, validate the strings
isValid := validateLoginData(&request.Username, &request.Password)
if isValid == false {
log.Error("Username and password incorrect")
response := map[string]string{"error": "Username and password incorrect"}
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(response)
return
}
// Generate a JWT token
jwtToken, err := generateJWTToken(&request.Username)
if err != nil {
log.Error(err.Error())
response := map[string]string{"error": err.Error()}
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(response)
return
}
// If we didn't return anywhere above, then return a successful response
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]string{"jwt": jwtToken})
}