-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
119 lines (101 loc) · 2.42 KB
/
main.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
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"github.com/DecentralCardGame/go-faucet/cardchain"
"github.com/DecentralCardGame/go-faucet/cardchain/client"
"github.com/DecentralCardGame/go-faucet/config"
"github.com/DecentralCardGame/go-faucet/payload"
"github.com/DecentralCardGame/go-faucet/token"
"github.com/joho/godotenv"
)
func handleClaimTokens(w http.ResponseWriter, r *http.Request) {
log.Print("Endpoint Hit: ClaimTokens")
w.Header().Set("Content-Type", "application/json")
enableCors(&w)
pl := payload.Payload{}
defer r.Body.Close()
body, err := io.ReadAll(r.Body)
if err != nil {
handleInternalServerError(w, err)
return
}
err = json.Unmarshal(body, &pl)
if err != nil {
http.Error(
w,
"Invalid json",
http.StatusBadRequest,
)
return
}
if !pl.Verify(w) {
return
}
isValid, err := token.ValidateToken(pl.Token)
if err != nil {
handleInternalServerError(w, err)
return
}
if !isValid {
http.Error(
w,
"User failed captcha",
http.StatusForbidden,
)
return
}
cResp, err := cardchain.CreateUser(
config.Config().BlockchainUser,
pl.Alias,
pl.Address,
)
if err != nil {
handleInternalServerError(w, err)
return
}
if cResp.Code != 0 {
http.Error(
w,
fmt.Sprintf(
"Cardchain responded with code %d: %s",
cResp.Code,
cResp.RawLog,
),
http.StatusForbidden,
)
}
}
func handleInternalServerError(w http.ResponseWriter, err error) {
http.Error(w, "Internal server error: "+err.Error(), http.StatusInternalServerError)
log.Printf("Error: %s", err.Error())
}
func handleRequests() {
http.HandleFunc("/claimTokens", handleClaimTokens)
log.Print("Server running at port 4500")
log.Fatal(http.ListenAndServe(":4500", nil))
}
func enableCors(w *http.ResponseWriter) {
(*w).Header().Set("Access-Control-Allow-Origin", "*")
(*w).Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
(*w).Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}
func main() {
err := godotenv.Load(".env")
if err != nil {
log.Fatalf("Some error occured. Err: %s", err)
}
err = config.FromEnv()
if err != nil {
log.Fatalf("Some error occured. Err: %s", err)
}
err = client.WaitForChain(config.Config().ClientConfig())
if err != nil {
log.Fatalf("Some error occured. Err: %s", err)
}
log.Print("Client instanciated")
handleRequests()
}