-
Notifications
You must be signed in to change notification settings - Fork 0
/
routes.go
301 lines (259 loc) · 7.33 KB
/
routes.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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
package controllers
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"strconv"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/gurbaaz27/iitk-coin/database"
"github.com/gurbaaz27/iitk-coin/models"
)
var jwtKey = []byte("gurbaaz")
func checkErr(err error) {
if err != nil {
panic(err)
}
}
func HandleRequests() {
http.HandleFunc("/", homePage)
http.HandleFunc("/signup", signUp)
http.HandleFunc("/login", logIn)
http.Handle("/secretpage", isLogin(secretPage))
http.HandleFunc("/reward", reward)
http.Handle("/transfer", isLogin(transfer))
http.Handle("/balance", isLogin(balance))
log.Println("Serving at 8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
func homePage(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "Welcome to Home Page of IITK Coin. There are 3 useful endpoints are:- /signup, /login, /secretpage\n")
}
func secretPage(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "Congrats! The fact that you have reached here is proof that you are successfully logged in!\n")
}
func signUp(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/signup" {
http.NotFound(w, r)
return
}
fmt.Println(r.URL.Path)
switch r.Method {
case "GET":
w.Write([]byte("Welcome to Signup Page!\nSend a POST request to signup in iitkcoin.\n"))
case "POST":
var newUser models.User
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&newUser)
checkErr(err)
log.Println(newUser)
res := database.AddUser(newUser)
w.Header().Set("Content-Type", "application/json")
if res {
json.NewEncoder(w).Encode("Signup Success")
} else {
json.NewEncoder(w).Encode("Signup Failure")
}
default:
w.WriteHeader(http.StatusNotImplemented)
w.Write([]byte(http.StatusText(http.StatusNotImplemented)))
}
}
func logIn(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/login" {
http.NotFound(w, r)
return
}
fmt.Println(r.URL.Path)
switch r.Method {
case "GET":
//Get(db)
w.Write([]byte("Welcome to Login Page!\nSend a POST request to login into iitkcoin.\n"))
case "POST":
var loginRequest models.LoginRequest
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&loginRequest)
checkErr(err)
log.Println(loginRequest)
log.Println("User valid : ", database.UserValid(loginRequest))
if database.UserValid(loginRequest) {
expirationTime := time.Now().Add(15 * time.Minute)
claims := &models.CustomClaims{
Rollno: loginRequest.Rollno,
StandardClaims: jwt.StandardClaims{
ExpiresAt: expirationTime.Unix(),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString(jwtKey)
checkErr(err)
log.Println("Token is: ", tokenString)
http.SetCookie(w, &http.Cookie{
Name: "token",
Value: tokenString,
Expires: expirationTime,
})
w.Write([]byte("Successfully logged in!\n"))
} else {
w.Write([]byte("Invalid user credentials. Please try again.\n"))
}
default:
w.WriteHeader(http.StatusNotImplemented)
w.Write([]byte(http.StatusText(http.StatusNotImplemented)))
}
}
func isLogin(endpoint func(http.ResponseWriter, *http.Request)) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("token")
if err != nil {
if err == http.ErrNoCookie {
w.WriteHeader(http.StatusUnauthorized)
return
}
w.WriteHeader(http.StatusBadRequest)
return
}
tknStr := cookie.Value
claims := &models.CustomClaims{}
tkn, err := jwt.ParseWithClaims(tknStr, claims, func(token *jwt.Token) (interface{}, error) {
return jwtKey, nil
})
if err != nil {
if err == jwt.ErrSignatureInvalid {
w.WriteHeader(http.StatusUnauthorized)
return
}
w.WriteHeader(http.StatusBadRequest)
return
}
if !tkn.Valid {
w.WriteHeader(http.StatusUnauthorized)
return
}
endpoint(w, r)
})
}
func balance(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/balance" {
http.NotFound(w, r)
return
}
fmt.Println(r.URL.Path)
switch r.Method {
case "GET":
rollnos, ok := r.URL.Query()["rollno"]
if !ok || len(rollnos[0]) < 1 {
log.Println("Url Param 'rollno' is missing")
return
}
rollno := rollnos[0]
cookie, err := r.Cookie("token")
if err != nil {
if err == http.ErrNoCookie {
w.WriteHeader(http.StatusUnauthorized)
return
}
w.WriteHeader(http.StatusBadRequest)
return
}
tknStr := cookie.Value
jwtClaims, _ := extractClaims(tknStr)
if jwtClaims["rollno"] == rollno {
coins := database.ReturnBalance(rollno)
if coins >= 0 {
w.Write([]byte("Rollno : " + rollno + "\n Balance : " + strconv.Itoa(int(coins)) + " coins\n"))
} else {
w.Write([]byte("User does not exist!\n"))
}
}
case "POST":
w.Write([]byte("Try Get Request.\n"))
}
}
func reward(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/reward" {
http.NotFound(w, r)
return
}
fmt.Println(r.URL.Path)
switch r.Method {
case "GET":
w.Write([]byte("Welcome to Reward Page!\nSend a POST request to award coins to user.\n"))
case "POST":
var rewardPayload models.RewardPayload
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&rewardPayload)
checkErr(err)
log.Println(rewardPayload)
res := database.RewardMoney(rewardPayload)
w.Header().Set("Content-Type", "application/json")
if res {
log.Printf("Coins awarded to rollno = %s , amounting = %d", rewardPayload.Rollno, rewardPayload.Coins)
json.NewEncoder(w).Encode("Reward Success")
} else {
log.Printf("Reward coins failed")
json.NewEncoder(w).Encode("Reward Failed")
}
default:
w.WriteHeader(http.StatusNotImplemented)
w.Write([]byte(http.StatusText(http.StatusNotImplemented)))
}
}
func transfer(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/transfer" {
http.NotFound(w, r)
return
}
fmt.Println(r.URL.Path)
switch r.Method {
case "GET":
w.Write([]byte("Welcome to Transfer Page!\nSend a POST request to tranfer coins peer to peer (P2P).\n"))
case "POST":
var transferPayload models.TransferPayload
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&transferPayload)
checkErr(err)
log.Println(transferPayload)
cookie, err := r.Cookie("token")
if err != nil {
if err == http.ErrNoCookie {
w.WriteHeader(http.StatusUnauthorized)
return
}
w.WriteHeader(http.StatusBadRequest)
return
}
tknStr := cookie.Value
jwtClaims, _ := extractClaims(tknStr)
if jwtClaims["rollno"] == transferPayload.SenderRollno {
res := database.TransferCoins(transferPayload)
w.Header().Set("Content-Type", "application/json")
if res {
log.Printf("Coins transfered from rollno = %s to rollno = %s amounting = %d", transferPayload.SenderRollno, transferPayload.ReceiverRollno, transferPayload.Coins)
json.NewEncoder(w).Encode("Transfer Success")
} else {
log.Printf("Transaction failed!")
json.NewEncoder(w).Encode("Transfer Failed")
}
}
default:
w.WriteHeader(http.StatusNotImplemented)
w.Write([]byte(http.StatusText(http.StatusNotImplemented)))
}
}
func extractClaims(tokenStr string) (jwt.MapClaims, bool) {
token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
return jwtKey, nil
})
if err != nil {
return nil, false
}
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
return claims, true
} else {
log.Printf("Invalid JWT Token")
return nil, false
}
}