forked from StevenWeathers/thunderdome-planning-poker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.go
236 lines (207 loc) · 7.7 KB
/
http.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
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
package main
import (
"bytes"
"context"
"embed"
"html/template"
"image"
"image/png"
"io/fs"
"net/http"
"os"
"strconv"
api "github.com/StevenWeathers/thunderdome-planning-poker/api"
"github.com/anthonynsimon/bild/transform"
"github.com/gorilla/mux"
"github.com/ipsn/go-adorable"
"github.com/o1egl/govatar"
"github.com/spf13/viper"
)
//go:embed dist
var f embed.FS
func (s *server) getFileSystem(useOS bool) (http.FileSystem, fs.FS) {
if useOS {
s.logger.Info("using live mode")
return http.FS(os.DirFS("dist")), fs.FS(os.DirFS("dist"))
}
fsys, err := fs.Sub(f, "dist")
if err != nil {
panic(err)
}
return http.FS(fsys), fs.FS(fsys)
}
func (s *server) routes() {
HFS, FSS := s.getFileSystem(embedUseOS)
staticHandler := http.FileServer(HFS)
// api (used by the webapp but can be enabled for external use)
apiConfig := &api.Config{
AppDomain: s.config.AppDomain,
FrontendCookieName: s.config.FrontendCookieName,
SecureCookieName: viper.GetString("http.backend_cookie_name"),
SecureCookieFlag: viper.GetBool("http.secure_cookie"),
SessionCookieName: viper.GetString("http.session_cookie_name"),
PathPrefix: s.config.PathPrefix,
ExternalAPIEnabled: s.config.ExternalAPIEnabled,
UserAPIKeyLimit: s.config.UserAPIKeyLimit,
LdapEnabled: s.config.LdapEnabled,
FeaturePoker: viper.GetBool("feature.poker"),
FeatureRetro: viper.GetBool("feature.retro"),
FeatureStoryboard: viper.GetBool("feature.storyboard"),
OrganizationsEnabled: viper.GetBool("config.organizations_enabled"),
}
api.Init(apiConfig, s.router, s.db, s.email, s.cookie, s.logger)
// static assets
s.router.PathPrefix("/static/").Handler(http.StripPrefix(s.config.PathPrefix, staticHandler))
s.router.PathPrefix("/img/").Handler(http.StripPrefix(s.config.PathPrefix, staticHandler))
s.router.PathPrefix("/lang/").Handler(http.StripPrefix(s.config.PathPrefix, staticHandler))
// user avatar generation
if s.config.AvatarService == "goadorable" || s.config.AvatarService == "govatar" {
s.router.PathPrefix("/avatar/{width}/{id}/{avatar}").Handler(s.handleUserAvatar()).Methods("GET")
s.router.PathPrefix("/avatar/{width}/{id}").Handler(s.handleUserAvatar()).Methods("GET")
}
// handle index.html
s.router.PathPrefix("/").HandlerFunc(s.handleIndex(FSS))
}
// get the index template from embedded filesystem
func (s *server) getIndexTemplate(FSS fs.FS) *template.Template {
ctx := context.Background()
// get the html template from dist, have it ready for requests
tmplContent, ioErr := fs.ReadFile(FSS, "static/index.html")
if ioErr != nil {
s.logger.Ctx(ctx).Error("Error opening index template")
if !embedUseOS {
s.logger.Ctx(ctx).Fatal(ioErr.Error())
}
}
tmplString := string(tmplContent)
tmpl, tmplErr := template.New("index").Parse(tmplString)
if tmplErr != nil {
s.logger.Ctx(ctx).Error("Error parsing index template")
if !embedUseOS {
s.logger.Ctx(ctx).Fatal(tmplErr.Error())
}
}
return tmpl
}
/*
Handlers
*/
// handleIndex parses the index html file, injecting any relevant data
func (s *server) handleIndex(FSS fs.FS) http.HandlerFunc {
type AppConfig struct {
AllowedPointValues []string
DefaultPointValues []string
ShowWarriorRank bool
AvatarService string
ToastTimeout int
AllowGuests bool
AllowRegistration bool
AllowJiraImport bool
DefaultLocale string
FriendlyUIVerbs bool
OrganizationsEnabled bool
AppVersion string
CookieName string
PathPrefix string
ExternalAPIEnabled bool
UserAPIKeyLimit int
CleanupGuestsDaysOld int
CleanupBattlesDaysOld int
CleanupRetrosDaysOld int
CleanupStoryboardsDaysOld int
ShowActiveCountries bool
LdapEnabled bool
FeaturePoker bool
FeatureRetro bool
FeatureStoryboard bool
RequireTeams bool
}
type UIConfig struct {
AnalyticsEnabled bool
AnalyticsID string
AppConfig AppConfig
ActiveAlerts []interface{}
}
tmpl := s.getIndexTemplate(FSS)
appConfig := AppConfig{
AllowedPointValues: viper.GetStringSlice("config.allowedPointValues"),
DefaultPointValues: viper.GetStringSlice("config.defaultPointValues"),
ShowWarriorRank: viper.GetBool("config.show_warrior_rank"),
AvatarService: viper.GetString("config.avatar_service"),
ToastTimeout: viper.GetInt("config.toast_timeout"),
AllowGuests: viper.GetBool("config.allow_guests"),
AllowRegistration: viper.GetBool("config.allow_registration") && viper.GetString("auth.method") == "normal",
AllowJiraImport: viper.GetBool("config.allow_jira_import"),
DefaultLocale: viper.GetString("config.default_locale"),
FriendlyUIVerbs: viper.GetBool("config.friendly_ui_verbs"),
OrganizationsEnabled: viper.GetBool("config.organizations_enabled"),
ExternalAPIEnabled: s.config.ExternalAPIEnabled,
UserAPIKeyLimit: s.config.UserAPIKeyLimit,
AppVersion: s.config.Version,
CookieName: s.config.FrontendCookieName,
PathPrefix: s.config.PathPrefix,
CleanupGuestsDaysOld: viper.GetInt("config.cleanup_guests_days_old"),
CleanupBattlesDaysOld: viper.GetInt("config.cleanup_battles_days_old"),
CleanupRetrosDaysOld: viper.GetInt("config.cleanup_retros_days_old"),
CleanupStoryboardsDaysOld: viper.GetInt("config.cleanup_storyboards_days_old"),
ShowActiveCountries: viper.GetBool("config.show_active_countries"),
LdapEnabled: s.config.LdapEnabled,
FeaturePoker: viper.GetBool("feature.poker"),
FeatureRetro: viper.GetBool("feature.retro"),
FeatureStoryboard: viper.GetBool("feature.storyboard"),
RequireTeams: viper.GetBool("config.require_teams"),
}
data := UIConfig{
AnalyticsEnabled: s.config.AnalyticsEnabled,
AnalyticsID: s.config.AnalyticsID,
AppConfig: appConfig,
}
api.ActiveAlerts = s.db.GetActiveAlerts(context.Background()) // prime the active alerts cache
return func(w http.ResponseWriter, r *http.Request) {
data.ActiveAlerts = api.ActiveAlerts // get latest alerts from memory
if embedUseOS {
tmpl = s.getIndexTemplate(FSS)
}
tmpl.Execute(w, data)
}
}
// handleUserAvatar creates an avatar for the given user by ID
func (s *server) handleUserAvatar() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
ctx := r.Context()
Width, _ := strconv.Atoi(vars["width"])
UserID := vars["id"]
AvatarGender := govatar.MALE
userGender, ok := vars["avatar"]
if ok {
if userGender == "female" {
AvatarGender = govatar.FEMALE
}
}
var avatar image.Image
if s.config.AvatarService == "govatar" {
avatar, _ = govatar.GenerateForUsername(AvatarGender, UserID)
} else { // must be goadorable
var err error
avatar, _, err = image.Decode(bytes.NewReader(adorable.PseudoRandom([]byte(UserID))))
if err != nil {
s.logger.Ctx(ctx).Fatal(err.Error())
}
}
img := transform.Resize(avatar, Width, Width, transform.Linear)
buffer := new(bytes.Buffer)
if err := png.Encode(buffer, img); err != nil {
s.logger.Ctx(ctx).Error("unable to encode image.")
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "image/png")
w.Header().Set("Content-Length", strconv.Itoa(len(buffer.Bytes())))
if _, err := w.Write(buffer.Bytes()); err != nil {
s.logger.Ctx(ctx).Error("unable to write image.")
w.WriteHeader(http.StatusInternalServerError)
return
}
}
}