-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplayer-id-middleware.go
74 lines (62 loc) · 1.48 KB
/
player-id-middleware.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
package main
import (
"math/rand"
"net/http"
"strconv"
"example.com/minesweeper/logic"
"example.com/minesweeper/repo"
"github.com/labstack/echo/v4"
)
const player_id = "player_id"
// Sets up the middleware for future requests.
func preparePlayerId(e *echo.Echo) {
e.Use(assignPlayerId)
}
// (Middleware function) Keeps the ID consistent
// in cookies and Contexts.
func assignPlayerId(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
cookie, err := c.Cookie(player_id)
if err != nil {
id := generatePlayerId()
cookie = &http.Cookie{
Name: player_id,
Value: id,
Path: "/",
MaxAge: 0,
Secure: false,
HttpOnly: true,
}
c.SetCookie(cookie)
}
c.Set(player_id, cookie.Value)
return next(c)
}
}
// Randomly creates an ID.
// With current implementation, collisions are possible.
func generatePlayerId() string {
n := rand.Intn(100000)
return "P" + strconv.Itoa(n)
}
// Gets the ID from a Context.
func extractPlayerId(c echo.Context) string {
id := c.Get(player_id)
if id == nil {
panic("extractPlayerId: No player ID set.")
}
return id.(string)
}
// Uses the stored ID to get the correct Player.
func extractPlayer(c echo.Context) *logic.Player {
id := c.Get(player_id)
if id == nil {
panic("extractPlayer: No player ID set.")
}
r := repo.ExtractRepository(c)
foundPlayer := r.Player(id.(string))
if foundPlayer == nil {
return &logic.Player{PlayerId: id.(string)}
}
return foundPlayer
}