-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
443 lines (382 loc) · 11.5 KB
/
server.go
File metadata and controls
443 lines (382 loc) · 11.5 KB
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
package main
import (
"crypto/rand"
"database/sql"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"github.com/go-sql-driver/mysql"
_ "github.com/go-sql-driver/mysql"
"html/template"
"net/http"
"strconv"
"time"
)
var (
sessionKeyLength int = 50 //In bytes
sessionExpiry int
db *sql.DB
user string
password string
database string = "QuestionWriter"
)
type MessageModel struct {
Message string
}
type RegisterRequest struct {
RegisterNumber string
Name string
AcademicYear string
Department string
Year string
Semester string
}
type RegisterResponse struct {
SessionId string
}
type QuestionUpdateRequest struct {
QuestionId int
Answer string
}
type SubQuestionModel struct {
QuestionId int
Question string
Choice []string
}
type QuestionModel struct {
File string
Description string
SubQuestion []SubQuestionModel
}
type QuestionListResponse struct {
Expiry string
Question []QuestionModel
}
type SubQuestionResultModel struct {
QuestionId int
Question string
Answer string
CorrectAnswer string
Reason string
}
type ResultAnalysisResponse struct {
SubQuestion []SubQuestionResultModel
}
func writeJson(w http.ResponseWriter, jsonData interface{}) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(jsonData)
}
func fixTimeZone(errTime time.Time) time.Time {
location := time.Now().Location()
fixedTime, _ := time.ParseInLocation(time.ANSIC, errTime.Format(time.ANSIC), location) //fixes timezone bug where mysql returns Local time as UTC
return fixedTime
}
func isValidSession(sessionId string, isTimeoutConsidered bool) bool {
now := time.Now()
var timeout mysql.NullTime
dbSession := db.QueryRow("SELECT SessionId, Timeout FROM Session WHERE SessionId=?", sessionId)
err := dbSession.Scan(&sessionId, &timeout)
if err == nil && len(sessionId) != 0 {
if isTimeoutConsidered {
timeout.Time = fixTimeZone(timeout.Time)
if timeout.Valid && now.Before(timeout.Time) {
return true
} else {
return false
}
} else {
return true
}
} else {
return false
}
}
func displayWebPage(w http.ResponseWriter, file string) {
t, _ := template.ParseFiles(file)
t.Execute(w, nil)
}
func registerHandler(w http.ResponseWriter, _ *http.Request) {
displayWebPage(w, "Register.html")
}
func dashboardHandler(w http.ResponseWriter, _ *http.Request) {
displayWebPage(w, "dashboard.html")
}
func resultsHandler(w http.ResponseWriter, _ *http.Request) {
displayWebPage(w, "Result.html")
}
func getQuestion(question string, file string, data QuestionListResponse) (int, error) {
for i := 0; i < len(data.Question); i++ {
if data.Question[i].Description == question && data.Question[i].File == file {
return i, nil
}
}
return -1, errors.New("not found")
}
func generateSubQuestion(questionId int, subQuestion string) (SubQuestionModel, error) {
var subQuestionObject SubQuestionModel
dbChoices, err := db.Query("SELECT Choice FROM Choices WHERE QuestionId=?", questionId)
defer dbChoices.Close()
if err == nil {
subQuestionObject.QuestionId = questionId
subQuestionObject.Question = subQuestion
hasChoices := false
for dbChoices.Next() {
hasChoices = true
var choice string
dbChoices.Scan(&choice)
subQuestionObject.Choice = append(subQuestionObject.Choice, choice)
}
if hasChoices == false {
subQuestionObject.Choice = nil
}
return subQuestionObject, nil
} else {
return subQuestionObject, err
}
}
func loginHandler(w http.ResponseWriter, r *http.Request) {
studentJson := r.FormValue("studentJson")
data := []byte(studentJson)
var student RegisterRequest
var reply RegisterResponse
err := json.Unmarshal(data, &student)
if err == nil {
b := make([]byte, sessionKeyLength)
_, err = rand.Read(b)
if err == nil {
reply.SessionId = base64.URLEncoding.EncodeToString(b)
_, err = db.Exec("INSERT INTO Session VALUES (?, ?, ?, ?, ?, ?, ?, NOW() + INTERVAL ? MINUTE)", reply.SessionId, student.RegisterNumber, student.Name, student.AcademicYear, student.Department, student.Year, student.Semester, sessionExpiry)
if err == nil {
writeJson(w, reply)
} else {
writeJson(w, MessageModel{
Message: "Error"})
}
} else {
writeJson(w, MessageModel{
Message: "Error creating Session ID"})
}
} else {
writeJson(w, MessageModel{
Message: "Error: Invalid JSON format"})
}
}
func getQuestionsHandler(w http.ResponseWriter, r *http.Request) {
sessionId := r.FormValue("sessionId")
if isValidSession(sessionId, true) {
dbQuestions, err := db.Query("SELECT QuestionId, Question, File, SubQuestion FROM Questions")
dbTimeout := db.QueryRow("SELECT Timeout FROM Session WHERE SessionId=?", sessionId)
var timeout mysql.NullTime
errTimeout := dbTimeout.Scan(&timeout)
defer dbQuestions.Close()
if err == nil && errTimeout == nil && timeout.Valid {
var reply QuestionListResponse
timeout.Time = fixTimeZone(timeout.Time)
reply.Expiry = timeout.Time.Format(time.RFC3339)
for dbQuestions.Next() {
var questionId int
var data [3]string
dbQuestions.Scan(&questionId, &data[0], &data[1], &data[2])
i, err := getQuestion(data[0], data[1], reply)
if err == nil {
subQuestion, err := generateSubQuestion(questionId, data[2])
if err == nil {
reply.Question[i].SubQuestion = append(reply.Question[i].SubQuestion, subQuestion)
} else {
writeJson(w, MessageModel{
Message: "Error"})
}
} else {
question := QuestionModel{Description: data[0], File: data[1]}
subQuestion, err := generateSubQuestion(questionId, data[2])
if err == nil {
question.SubQuestion = append(question.SubQuestion, subQuestion)
reply.Question = append(reply.Question, question)
} else {
writeJson(w, MessageModel{
Message: "Error"})
}
}
}
writeJson(w, reply)
} else {
writeJson(w, MessageModel{
Message: "Error getting questions"})
}
} else {
writeJson(w, MessageModel{
Message: "Error: Invalid Session"})
}
}
func updateQuestionHandler(w http.ResponseWriter, r *http.Request) {
sessionId := r.FormValue("sessionId")
updateJson := r.FormValue("updateJson")
if isValidSession(sessionId, true) {
data := []byte(updateJson)
var update QuestionUpdateRequest
err := json.Unmarshal(data, &update)
if err == nil {
var temp int
dbQuestion := db.QueryRow("SELECT QuestionId FROM Questions WHERE QuestionId=?", update.QuestionId)
err = dbQuestion.Scan(&temp)
if err == nil {
dbStudentAnswer := db.QueryRow("SELECT QuestionId FROM StudentAnswers WHERE SessionId=? AND QuestionId=?", sessionId, update.QuestionId)
err = dbStudentAnswer.Scan(&temp)
if err == nil {
_, err = db.Exec("UPDATE StudentAnswers SET Answer=? WHERE SessionId=? AND QuestionId=?", update.Answer, sessionId, update.QuestionId)
if err == nil {
writeJson(w, MessageModel{
Message: "Success"})
} else {
writeJson(w, MessageModel{
Message: "Error"})
}
} else {
_, err = db.Exec("INSERT INTO StudentAnswers VALUES(?,?,?)", sessionId, update.QuestionId, update.Answer)
if err == nil {
writeJson(w, MessageModel{
Message: "Success"})
} else {
writeJson(w, MessageModel{
Message: "Error"})
}
}
} else {
writeJson(w, MessageModel{
Message: "Error getting question"})
}
} else {
writeJson(w, MessageModel{
Message: "Error: Invalid JSON format"})
}
} else {
writeJson(w, MessageModel{
Message: "Error: Invalid Session"})
}
}
func getAnswerHandler(w http.ResponseWriter, r *http.Request) {
sessionId := r.FormValue("sessionId")
questionId := r.FormValue("questionId")
if isValidSession(sessionId, true) {
question, err := strconv.Atoi(questionId)
if err == nil {
var answer string
row := db.QueryRow("SELECT Answer FROM StudentAnswers WHERE SessionId=? AND QuestionId=?", sessionId, question)
err = row.Scan(&answer)
if err == nil {
writeJson(w, QuestionUpdateRequest{
QuestionId: question,
Answer: answer})
} else {
writeJson(w, MessageModel{
Message: "Error"})
}
} else {
writeJson(w, MessageModel{
Message: "Error: Invalid Question ID"})
}
} else {
writeJson(w, MessageModel{
Message: "Error: Invalid Session"})
}
}
func reportHandler(w http.ResponseWriter, r *http.Request) {
sessionId := r.FormValue("sessionId")
if isValidSession(sessionId, false) {
var questionLength int
row := db.QueryRow("SELECT COUNT(QuestionId) FROM Questions")
err := row.Scan(&questionLength)
if err == nil {
var subQuestionArray []SubQuestionResultModel
for i := 1; i <= questionLength; i++ {
var subQuestion, answer, reason string
row = db.QueryRow("SELECT SubQuestion, Answer, AnswerReason FROM Questions WHERE QuestionId=?", i)
err = row.Scan(&subQuestion, &answer, &reason)
if err == nil {
var studentAnswer string
row = db.QueryRow("SELECT Answer FROM StudentAnswers WHERE SessionId=? AND QuestionId=?", sessionId, i)
err = row.Scan(&studentAnswer)
if err == nil {
subQuestionArray = append(subQuestionArray, SubQuestionResultModel{
QuestionId: i,
Question: subQuestion,
Answer: studentAnswer,
CorrectAnswer: answer,
Reason: reason})
} else {
subQuestionArray = append(subQuestionArray, SubQuestionResultModel{
QuestionId: i,
Question: subQuestion,
Answer: "",
CorrectAnswer: answer,
Reason: reason})
}
} else {
writeJson(w, MessageModel{
Message: "Error"})
}
}
writeJson(w, ResultAnalysisResponse{
SubQuestion: subQuestionArray})
} else {
writeJson(w, MessageModel{
Message: "Error"})
}
} else {
writeJson(w, MessageModel{
Message: "Error: Invalid Session"})
}
}
func studentDetailsHandler(w http.ResponseWriter, r *http.Request) {
sessionId := r.FormValue("sessionId")
if isValidSession(sessionId, false) {
var data [6]string
row := db.QueryRow("SELECT StudentId, Name, AcademicYear, Department, Year, Semester FROM Session WHERE SessionId=?", sessionId)
err := row.Scan(&data[0], &data[1], &data[2], &data[3], &data[4], &data[5])
if err == nil {
writeJson(w, RegisterRequest{
RegisterNumber: data[0],
Name: data[1],
AcademicYear: data[2],
Department: data[3],
Year: data[4],
Semester: data[5]})
} else {
writeJson(w, MessageModel{
Message: "Error"})
}
} else {
writeJson(w, MessageModel{
Message: "Error: Invalid Session"})
}
}
func main() {
fmt.Print("Enter user name: ")
fmt.Scanln(&user)
fmt.Print("Enter password: ")
fmt.Scanln(&password)
fmt.Print("Enter length of examination [In Minutes]: ")
fmt.Scanln(&sessionExpiry)
fmt.Println("Starting up server")
var dbErr error
db, dbErr = sql.Open("mysql", user+":"+password+"@/"+database)
defer db.Close()
if dbErr == nil {
fmt.Println("Server is running")
http.Handle("/", http.FileServer(http.Dir("./static")))
http.HandleFunc("/register", registerHandler)
http.HandleFunc("/dashboard", dashboardHandler)
http.HandleFunc("/results", resultsHandler)
http.HandleFunc("/login", loginHandler)
http.HandleFunc("/questions", getQuestionsHandler)
http.HandleFunc("/update", updateQuestionHandler)
http.HandleFunc("/getanswer", getAnswerHandler)
http.HandleFunc("/studentDetails", studentDetailsHandler)
http.HandleFunc("/report", reportHandler)
http.ListenAndServe(":8000", nil)
} else {
fmt.Println("Error: Invalid login details")
panic(dbErr)
}
}