-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
114 lines (87 loc) · 1.89 KB
/
handler.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
package main
import (
"fmt"
"net/http"
"strings"
"time"
"github.com/gin-gonic/contrib/sessions"
"github.com/gin-gonic/gin"
_ "github.com/lib/pq"
)
const (
username = "user"
ucolor = "color"
)
func loadLogin(c *gin.Context) {
c.HTML(
http.StatusOK,
"login.html",
gin.H{},
)
}
func auth(c *gin.Context) {
user := c.PostForm("user")
color := c.PostForm("Color")
if strings.Contains(user, "<") || strings.Contains(user, ">") || user == "" {
c.HTML(
http.StatusOK,
"login.html",
gin.H{
"error": "Use a valid username",
},
)
return
}
session := sessions.Default(c)
session.Set(username, user)
session.Set(ucolor, color)
if err := session.Save(); err != nil {
c.IndentedJSON(http.StatusInternalServerError, gin.H{"Error": "Unable to save session."})
return
} else {
c.Redirect(http.StatusFound, "/u/chat")
}
}
func isLogin(c *gin.Context) {
session := sessions.Default(c)
user := session.Get(username)
if user == nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"Error": "Unauthorized"})
return
}
c.Next()
}
func chatpage(c *gin.Context) {
session := sessions.Default(c)
user := session.Get(username)
color := session.Get(ucolor)
msglist := getAllMsgs()
c.HTML(
http.StatusOK,
"chat.html",
gin.H{
"user": user,
"color": color,
"msgList": msglist,
},
)
}
func postmsg(c *gin.Context) {
session := sessions.Default(c)
user := session.Get(username)
color := session.Get(ucolor)
time := time.Now()
umessage := c.PostForm("usermessage")
data, err := addMsgtoDB(db, fmt.Sprint(user), umessage, fmt.Sprint(color), time.Format("[15:04:05] "))
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"Error": "Unable to add message to database"})
}
addMsg(*data)
c.Redirect(http.StatusFound, "/u/chat")
}
func jsonmsg(c *gin.Context) {
c.IndentedJSON(
http.StatusOK,
globalmsgList,
)
}