-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
75 lines (63 loc) · 1.51 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
package main
import (
"encoding/json"
"io/ioutil"
"net/http"
"github.com/gin-gonic/gin"
"github.com/rishabh625/websocket-example/auth"
)
var dataMap map[string]string
type UserDetails struct {
UserData []User `json:"userdata"`
}
type User struct {
Username string `json:"username"`
Password string `json:"password"`
}
func init() {
if dataMap == nil {
dataMap = make(map[string]string)
}
plan, _ := ioutil.ReadFile("userdetails.json")
var data UserDetails
err := json.Unmarshal(plan, &data)
if err != nil {
panic(err)
}
for _, v := range data.UserData {
dataMap[v.Username] = v.Password
}
}
func main() {
go h.run()
router := gin.New()
router.GET("/token", func(c *gin.Context) {
username := c.Query("username")
password := c.Query("password")
if _, ok := dataMap[username]; !ok {
c.JSON(http.StatusUnauthorized, "{\"message\":\"Incorrect Username and Password\"}")
c.Abort()
} else {
if dataMap[username] != password {
c.JSON(http.StatusUnauthorized, "{\"message\":\"Incorrect Username and Password\"}")
c.Abort()
} else {
c.Next()
}
}
}, func(c *gin.Context) {
username := c.Param("username")
token, err := auth.CreateToken(username)
if err == nil {
c.JSON(http.StatusAccepted, token)
} else {
c.JSON(http.StatusInternalServerError, err)
}
})
router.GET("/ws", auth.AuthenticateHeader, func(c *gin.Context) {
roomId := "1"
clientid := c.MustGet("clientid").(float64)
serveWs(c.Writer, c.Request, roomId, clientid)
})
router.Run("0.0.0.0:8080")
}