-
Notifications
You must be signed in to change notification settings - Fork 0
/
24handler.go
459 lines (413 loc) · 11.6 KB
/
24handler.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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
package main
import (
"database/sql"
//"encoding/gob"
"fmt"
"net/http"
"text/template"
"github.com/gorilla/securecookie"
"github.com/gorilla/sessions"
"golang.org/x/crypto/bcrypt"
)
type User struct {
Username interface{}
Authenticated bool
}
var err error
//Session name to store session under
const SessionName = "Voting-Session"
///var sessionStore *sessions.CookieStore
var encryptionKey = securecookie.GenerateRandomKey(32)
var loggeduserSession = sessions.NewCookieStore([]byte(encryptionKey))
//var userMap = make(map[string]interface{})
func Init() {
fmt.Println("Init function called")
loggeduserSession.Options = &sessions.Options{Path: "/", MaxAge: 86400 * 1, HttpOnly: true}
/// gob.Register(User{})
fmt.Println("Init function has been ended")
}
// to handle the error if anything goes wrong
func handleSessionError(w http.ResponseWriter, err error) {
fmt.Println("session handler has invoked the error")
http.Error(w, "Unable to retrieve the session data", http.StatusInternalServerError)
}
func Signup(w http.ResponseWriter, r *http.Request) {
fmt.Println("SignUP Called")
if r.Method != "POST" {
http.ServeFile(w, r, "signup.html")
return
}
username := r.FormValue("username")
password := r.FormValue("password")
var user string
rows, err := db.Query("SELECT username FROM users WHERE username=?", username)
if err != nil {
panic(err.Error())
}
count := 0
for rows.Next() {
count++
}
if count > 0 {
w.Write([]byte("USER already existed"))
return
}
err = db.QueryRow("SELECT username FROM users WHERE username=?", username).Scan(&user)
switch {
case err == sql.ErrNoRows:
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
http.Error(w, "Unable to crate accout right now (ONE)", http.StatusInternalServerError)
return
}
_, err = db.Exec("INSERT INTO users(username,password) VALUES(?,?)", username, hashedPassword)
if err != nil {
http.Error(w, "Unable to create your account (TWO)", http.StatusInternalServerError)
return
}
// fmt.Println("User Account Has been created")
w.Write([]byte("User Accout Created"))
case err != nil:
http.Error(w, "Unable to create your account (THREE)", http.StatusInternalServerError)
return
default:
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
}
http.Redirect(w, r, "/", 301)
fmt.Println("SignUP has been ended")
}
func Login(w http.ResponseWriter, r *http.Request) {
u := User{}
fmt.Println("Login Handler called")
session, err := loggeduserSession.Get(r, SessionName)
fmt.Println("value of Sesion is ", session)
fmt.Println("value of error is ", err)
if err != nil {
handleSessionError(w, err)
return
}
if r.Method != "POST" {
http.ServeFile(w, r, "login.html")
return
}
username := r.FormValue("username")
password := r.FormValue("password")
var dbusername string
var dbpassword string
err = db.QueryRow("SELECT username, password FROM users WHERE username=?", username).Scan(&dbusername, &dbpassword)
if err != nil {
w.Write([]byte("User Does Not Exist"))
session.AddFlash("USER DOES NOT EXIST")
err = session.Save(r, w)
if err != nil {
handleSessionError(w, err)
}
http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
return
}
err = bcrypt.CompareHashAndPassword([]byte(dbpassword), []byte(password))
if err != nil {
w.Write([]byte("Credentials Did not Match!"))
http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
return
}
// Session-handling
/*
user := &User{
Username: username,
Authenticated: true,
}
*/
// a new session will be created when user sucessfully logged IN
session, err = loggeduserSession.New(r, SessionName)
fmt.Println("session values", session)
fmt.Println("error value is ", err)
if err != nil {
handleSessionError(w, err)
}
session.Values["username"] = username //from r.Formvalue
if err := session.Save(r, w); err != nil {
handleSessionError(w, err)
return
}
u = User{Username: session.Values["username"], Authenticated: true}
outputHTML(w, "register.html", u)
//redirect to the next page.
http.Redirect(w, r, "/register", 301)
}
func Logout(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "logout.html")
fmt.Println("LOGOUT HANDLER IS CALLED")
session, err := loggeduserSession.Get(r, SessionName)
fmt.Println("sesion value in LOGOUT HANDLER", session)
if err != nil {
handleSessionError(w, err)
return
}
session.Values["username"] = ""
//loggeduserSession.MaxAge(-1)
if err := session.Save(r, w); err != nil {
handleSessionError(w, err)
return
}
//to check whether any session is ther or not after logout
session, err = loggeduserSession.Get(r, SessionName)
if err != nil {
fmt.Println("error in logout function", err)
}
fmt.Println("LOGOUT HANDLER ENDED")
http.Redirect(w, r, "/logout", 301)
return
}
func Homepage(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "index.html")
}
func Register(w http.ResponseWriter, r *http.Request) {
u := User{}
session, err := loggeduserSession.Get(r, SessionName)
if err != nil {
handleSessionError(w, err)
return
}
if session.Values["username"] == "" {
//NO USER found
http.Redirect(w, r, "/forbidden", 301)
}
if err := session.Save(r, w); err != nil {
handleSessionError(w, err)
return
}
if r.Method != "POST" {
http.ServeFile(w, r, "register.html")
}
u = User{Username: session.Values["username"], Authenticated: true}
outputHTML(w, "db.html", u)
http.Redirect(w, r, "/stored", 301)
}
func TermsandConditions(w http.ResponseWriter, r *http.Request) {
u := User{}
session, err := loggeduserSession.Get(r, SessionName)
if err != nil {
handleSessionError(w, err)
return
}
if session.Values["username"] == "" {
//NO USER found
http.Redirect(w, r, "/forbidden", 301)
}
if err := session.Save(r, w); err != nil {
handleSessionError(w, err)
return
}
u = User{Username: session.Values["username"], Authenticated: true}
outputHTML(w, "terms.html", u)
switch r.Method {
case "GET":
http.ServeFile(w, r, "terms.html")
case "POST":
http.Redirect(w, r, "/", 301)
default:
fmt.Fprintf(w, "Service only Supports GET and POST")
}
}
func Storedb(w http.ResponseWriter, r *http.Request) {
u := User{}
session, err := loggeduserSession.Get(r, SessionName)
if err != nil {
handleSessionError(w, err)
return
}
if session.Values["username"] == "" {
//NO USER found
http.Redirect(w, r, "/forbidden", 301)
}
if err := session.Save(r, w); err != nil {
handleSessionError(w, err)
return
}
var VoterID, LastName, FirstName, Age, Sex, State, City string
switch r.Method {
case "GET":
http.ServeFile(w, r, "db.html")
case "POST":
if err := r.ParseForm(); err != nil {
fmt.Fprintf(w, "ParseForm() err: %v", err)
return
}
VoterID = r.FormValue("VoterID")
LastName = r.FormValue("LastName")
FirstName = r.FormValue("FirstName")
State = r.FormValue("State")
City = r.FormValue("City")
Age = r.FormValue("Age")
Sex = r.FormValue("Sex")
default:
fmt.Fprintf(w, "Service only Supports GET and POST")
}
_, err = db.Exec("INSERT INTO Voters(VoterID,LastName,FirstName,Age,Sex,State,City)VALUES(?,?,?,?,?,?,?)", VoterID, LastName, FirstName, Age, Sex, State, City)
if err != nil {
panic(err.Error())
}
u = User{Username: session.Values["username"], Authenticated: true}
outputHTML(w, "vote.html", u)
http.Redirect(w, r, "/vote", 301)
}
func Vote(w http.ResponseWriter, r *http.Request) {
u := User{}
session, err := loggeduserSession.Get(r, SessionName)
if err != nil {
handleSessionError(w, err)
return
}
fmt.Println("Before POST VOTE check username is present or not")
fmt.Println("Value of Signed-IN user", session.Values["username"])
if session.Values["username"] == "" {
//NO USER
fmt.Println("Redirecting to forbidden page as no user found")
http.Redirect(w, r, "/forbidden", 301)
return
}
if err := session.Save(r, w); err != nil {
handleSessionError(w, err)
return
}
var Party_Name string
switch r.Method {
case "GET":
http.ServeFile(w, r, "vote.html")
case "POST":
/*
if session.Values["username"] == "" {
fmt.Println("Value of Logged in User is", session.Values["username"])
http.Redirect(w, r, "/forbidden", 301)
}*/
if err := r.ParseForm(); err != nil {
fmt.Fprintf(w, "ParseForm() err: %v", err)
return
}
Party_Name = r.FormValue("Party")
default:
fmt.Fprintf(w, "Service only Supports GET and POST")
}
/*
fmt.Println("before taking the vote check the user session again")
fmt.Println("Value of Logged in User is", session.Values["username"])
if session.Values["username"] == "" {
http.Redirect(w, r, "/forbidden", 301)
} */
_, err = db.Exec("INSERT INTO parties(Party_Name)VALUES(?)", Party_Name)
if err != nil {
panic(err.Error())
}
u = User{Username: session.Values["username"], Authenticated: true}
outputHTML(w, "result.html", u)
http.Redirect(w, r, "/result", 301)
}
func outputHTML(w http.ResponseWriter, filename string, data interface{}) {
t, err := template.ParseFiles(filename)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
if err := t.Execute(w, data); err != nil {
http.Error(w, err.Error(), 500)
return
}
}
func Result(w http.ResponseWriter, r *http.Request) {
u := User{}
session, err := loggeduserSession.Get(r, SessionName)
if err != nil {
handleSessionError(w, err)
return
}
if session.Values["username"] == "" {
//NO USER found
http.Redirect(w, r, "/forbidden", 301)
}
if err := session.Save(r, w); err != nil {
handleSessionError(w, err)
return
}
var count1, count2, count3 int
type sample struct {
Myvar string
Votes int
}
switch r.Method {
case "GET":
fmt.Println("RESULT GET METHOD")
http.ServeFile(w, r, "result.html")
case "POST":
username := r.FormValue("username")
password := r.FormValue("password")
var dbusername string
var dbpassword string
err = db.QueryRow("SELECT username, password FROM users WHERE username=?", username).Scan(&dbusername, &dbpassword)
if err != nil {
w.Write([]byte("User Does Not Exist"))
http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
return
}
err = bcrypt.CompareHashAndPassword([]byte(dbpassword), []byte(password))
if err != nil {
w.Write([]byte("Credentials Did not Match!"))
http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
return
}
rows, err := db.Query("SELECT Party_Name FROM parties WHERE Party_Name=?", "BJP")
if err != nil {
panic(err.Error())
}
for rows.Next() {
count1++
}
rows_MNS, err1 := db.Query("SELECT Party_Name FROM parties WHERE Party_Name=?", "MNS")
if err1 != nil {
panic(err.Error())
}
count2 = 0
for rows_MNS.Next() {
count2++
}
rows_INC, err2 := db.Query("SELECT Party_Name FROM parties WHERE Party_Name=?", "INC")
if err2 != nil {
panic(err.Error())
}
count3 = 0
for rows_INC.Next() {
count3++
}
s := sample{Myvar: "BJP received :-", Votes: count1}
outputHTML(w, "final.html", s)
default:
fmt.Fprintf(w, "Service only Supports GET and POST")
}
u = User{Username: session.Values["username"], Authenticated: true}
outputHTML(w, "final.html", u)
http.Redirect(w, r, "/final", 301)
}
func Final(w http.ResponseWriter, r *http.Request) {
session, err := loggeduserSession.Get(r, SessionName)
if err != nil {
handleSessionError(w, err)
return
}
if session.Values["username"] == "" {
//NO USER found
http.Redirect(w, r, "/forbidden", 301)
}
if err := session.Save(r, w); err != nil {
handleSessionError(w, err)
return
}
if r.Method == "GET" {
http.ServeFile(w, r, "final.html")
}
}
func forbidden(w http.ResponseWriter, r *http.Request) {
fmt.Println("forbidden handler is called")
fmt.Println("r.method is", r.Method)
http.ServeFile(w, r, "forbidden.html")
return
}