-
Notifications
You must be signed in to change notification settings - Fork 4
/
user.go
85 lines (73 loc) · 1.93 KB
/
user.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
package main
import (
"fmt"
"net/http"
"github.com/fnatte/pizza-tribes/internal/game"
"github.com/fnatte/pizza-tribes/internal/game/models"
"github.com/fnatte/pizza-tribes/internal/game/persist"
"github.com/fnatte/pizza-tribes/internal/game/protojson"
"github.com/fnatte/pizza-tribes/internal/game/redis"
"github.com/gorilla/mux"
"github.com/rs/zerolog/log"
)
type UserController struct {
r redis.RedisClient
auth *game.AuthService
gsRepo persist.GameStateRepository
}
func (c *UserController) Handler() http.Handler {
r := mux.NewRouter()
r.HandleFunc("/{userId}", func(w http.ResponseWriter, r *http.Request) {
err := c.auth.Authorize(r)
if err != nil {
log.Error().Err(err).Msg("Failed to authorize")
w.WriteHeader(403)
return
}
params := mux.Vars(r)
userId := params["userId"]
if userId == "" {
w.WriteHeader(400)
return
}
username, err := c.r.HGet(r.Context(), fmt.Sprintf("user:%s", userId), "username").Result()
if err != nil {
w.WriteHeader(404)
return
}
gs, err := c.gsRepo.Get(r.Context(), userId)
if err != nil {
log.Error().Msg("failed to get game state")
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
var ambassador *models.Mouse
if gs.AmbassadorMouseId != "" {
var ok bool
ambassador, ok = gs.Mice[gs.AmbassadorMouseId]
if !ok {
log.Error().Msg("failed to look up ambassador mouse")
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
}
res := &models.ApiUserResponse{
Username: username,
}
if ambassador != nil {
res.Ambassador = &models.ApiUserResponse_Ambassador{
Appearance: ambassador.Appearance,
}
}
b, err := protojson.Marshal(res)
if err != nil {
log.Error().Err(err).Msg("Failed to marshal username struct")
w.WriteHeader(500)
return
}
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(200)
w.Write(b)
})
return r
}