BlueGit

timfa bluegit

Files

bluegit / internal / server / server.go

server.go

server.go 29.0 KiB Download Raw
1// Package server is de webinterface, de git-HTTP-server en de API.
2package server
3
4import (
5 "context"
6 "crypto/rand"
7 "embed"
8 "encoding/hex"
9 "fmt"
10 "gitlab.com/Timfa/bluegit/internal/readcache"
11 "html/template"
12 "io/fs"
13 "log/slog"
14 "net/http"
15 "net/url"
16 "strings"
17 "sync"
18 "time"
19 "unicode/utf8"
20
21 "gitlab.com/Timfa/bluegit/internal/access"
22 "gitlab.com/Timfa/bluegit/internal/activity"
23 "gitlab.com/Timfa/bluegit/internal/auth"
24 "gitlab.com/Timfa/bluegit/internal/card"
25 "gitlab.com/Timfa/bluegit/internal/cispec"
26 "gitlab.com/Timfa/bluegit/internal/config"
27 "gitlab.com/Timfa/bluegit/internal/i18n"
28 "gitlab.com/Timfa/bluegit/internal/realip"
29 "gitlab.com/Timfa/bluegit/internal/runner"
30 "gitlab.com/Timfa/bluegit/internal/store"
31)
32
33//go:embed templates/*.html static/*.css static/*.js static/*.svg static/*.ttf static/*.txt
34var webFS embed.FS
35
36// Server bedient BlueGit.
37type Server struct {
38 Cfg config.Config
39 Store *store.Store
40 Auth auth.Provider
41 Mail auth.Mailer
42 Dev bool
43 Git string
44 HookBin string
45 Runner *runner.Runner
46 Log *slog.Logger
47 // hookSink vangt de JSON-body af in tests, vóór het HTTP-verzoek.
48 hookSink func([]byte)
49 // StateDir is de map met database en het bestand storage_path.
50 StateDir string
51 // AfterStorage krijgt het nieuwe datadisk-pad, voor runner en SSH.
52 AfterStorage func(path string)
53 // UpdateStarter start bluegit-update.service. Nil gebruikt systemctl.
54 UpdateStarter UpdateStarter
55 updateHits updateLimiter
56 tmpl *template.Template
57 byLang map[string]*template.Template
58
59 storageMu sync.RWMutex
60 storage string
61 storageSet bool
62 usageMu sync.Mutex
63 usage dirUsage
64 usageDone chan struct{}
65 cards *card.Cache
66 // mergingMR zijn merge requests die opMergeMR nu zelf afrondt.
67 // AfterPush mag hun bronbranch niet alvast verwijderen.
68 mergingMR sync.Map
69
70 cacheMu sync.RWMutex
71 rcache *readcache.Cache
72}
73
74type principal struct {
75 User store.User
76 Session store.Session
77 OK bool
78}
79
80type ctxKey struct{}
81
82// Handler is de HTTP-handler met sessies en koppen.
83func (s *Server) Handler() http.Handler {
84 s.mustTemplates()
85 mux := http.NewServeMux()
86 mux.HandleFunc("GET /assets/{file}", s.asset)
87 mux.HandleFunc("GET /-/info", s.infoPage)
88 mux.HandleFunc("GET /help", s.helpIndex)
89 mux.HandleFunc("GET /help/{doc}", s.helpPage)
90 s.mountRunnerAdmin(mux)
91 mux.HandleFunc("GET /-/card.png", s.cardPNG)
92 mux.HandleFunc("GET /api/v1/oembed", s.oembed)
93 s.mountAPI(mux)
94 mux.HandleFunc("GET /api/v1/admin/self-update", s.selfUpdateStatus)
95 mux.HandleFunc("POST /api/v1/admin/self-update", s.selfUpdate)
96 mux.HandleFunc("GET /api/v1/webhooks/openapi.json", s.webhookSpec)
97 mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
98 w.WriteHeader(http.StatusOK)
99 _, _ = w.Write([]byte("ok\n"))
100 })
101 mux.HandleFunc("GET /login", s.login)
102 mux.HandleFunc("GET /auth/callback", s.callback)
103 mux.HandleFunc("POST /logout", s.logout)
104 mux.HandleFunc("GET /{$}", s.home)
105 mux.HandleFunc("GET /new", s.newPage)
106 mux.HandleFunc("GET /new/slug", s.slugPreview)
107 mux.HandleFunc("POST /new/repo", s.createRepo)
108 mux.HandleFunc("POST /new/group", s.createGroup)
109 mux.HandleFunc("GET /setup", s.setupPage)
110 mux.HandleFunc("POST /setup", s.setupSave)
111 mux.HandleFunc("POST /setup/cache", s.setupCacheSave)
112 mux.HandleFunc("POST /setup/cache/clear", s.setupCacheClear)
113 s.routeRunners(mux)
114 mux.HandleFunc("GET /settings", s.account)
115 mux.HandleFunc("POST /settings/language", s.saveLanguage)
116 mux.HandleFunc("POST /settings/profile", s.saveProfile)
117 mux.HandleFunc("POST /settings/tokens", s.createToken)
118 mux.HandleFunc("POST /settings/tokens/delete", s.deleteToken)
119 mux.HandleFunc("POST /settings/ssh", s.addSSH)
120 mux.HandleFunc("POST /settings/ssh/delete", s.deleteSSH)
121 mux.HandleFunc("GET /settings/export", s.export)
122 mux.HandleFunc("GET /users/{username}", s.profile)
123 mux.HandleFunc("GET /{name}", s.userShort)
124 mux.HandleFunc("GET /groups/{path}", s.groupPage)
125 mux.HandleFunc("GET /groups/{path}/logo", s.groupLogo)
126 mux.HandleFunc("POST /groups/{path}/settings", s.saveGroup)
127 mux.HandleFunc("POST /groups/{path}/approvals", s.saveGroupApproval)
128 mux.HandleFunc("POST /groups/{path}/owner", s.transferGroup)
129 mux.HandleFunc("POST /groups/{path}/logo", s.uploadGroupLogo)
130 mux.HandleFunc("POST /groups/{path}/members", s.groupMember)
131 mux.HandleFunc("POST /groups/{path}/members/remove", s.groupMemberRemove)
132 mux.HandleFunc("POST /groups/{path}/secrets", s.groupSecret)
133 mux.HandleFunc("POST /groups/{path}/secrets/reveal", s.groupSecretReveal)
134 mux.HandleFunc("POST /groups/{path}/secrets/delete", s.groupSecretDelete)
135 mux.HandleFunc("POST /groups/{path}/webhooks", s.groupWebhook)
136 mux.HandleFunc("POST /groups/{path}/webhooks/delete", s.groupWebhookDelete)
137
138 mux.HandleFunc("GET /{owner}/{repo}/info/refs", s.gitHTTP)
139 mux.HandleFunc("POST /{owner}/{repo}/git-upload-pack", s.gitHTTP)
140 mux.HandleFunc("POST /{owner}/{repo}/git-receive-pack", s.gitHTTP)
141 mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/releases", s.createRelease)
142 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log", s.jobLogAPI)
143 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/commits/{sha}/diff", s.commitDiffAPI)
144 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/merge-requests/{number}/diff", s.mrDiffAPI)
145 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/issues", s.issuesAPI)
146 mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/issues", s.issuesAPI)
147 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/issues/{number}", s.issueAPI)
148 mux.HandleFunc("PUT /api/v1/repos/{owner}/{repo}/issues/{number}", s.issueAPI)
149 mux.HandleFunc("DELETE /api/v1/repos/{owner}/{repo}/issues/{number}", s.issueAPI)
150 mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/issues/{number}/notes", s.issueNoteAPI)
151 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/labels", s.labelsAPI)
152 mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/labels", s.labelsAPI)
153 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/milestones", s.milestonesAPI)
154 mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/milestones", s.milestonesAPI)
155 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/webhook-secrets", s.repoWebhookSecrets)
156 mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/webhooks", s.repoWebhookAPI)
157 mux.HandleFunc("PUT /api/v1/repos/{owner}/{repo}/webhooks/{id}", s.repoWebhookUpdate)
158 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/secrets", s.repoSecretsAPI)
159 mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/secrets", s.repoSecretCreateAPI)
160 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/secrets/{name}", s.repoSecretRevealAPI)
161 mux.HandleFunc("PUT /api/v1/repos/{owner}/{repo}/secrets/{name}", s.repoSecretUpdateAPI)
162 mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/secrets/{name}/replace", s.repoSecretReplaceAPI)
163 mux.HandleFunc("DELETE /api/v1/repos/{owner}/{repo}/secrets/{name}", s.repoSecretDeleteAPI)
164 mux.HandleFunc("GET /api/v1/groups/{path}/webhook-secrets", s.groupWebhookSecrets)
165 mux.HandleFunc("POST /api/v1/groups/{path}/hooks", s.groupWebhookAPI)
166 mux.HandleFunc("PUT /api/v1/groups/{path}/hooks/{id}", s.groupWebhookUpdate)
167 mux.HandleFunc("GET /api/v1/groups/{path}/secrets", s.groupSecretsAPI)
168 mux.HandleFunc("POST /api/v1/groups/{path}/secrets", s.groupSecretCreateAPI)
169 mux.HandleFunc("GET /api/v1/groups/{path}/secrets/{name}", s.groupSecretRevealAPI)
170 mux.HandleFunc("PUT /api/v1/groups/{path}/secrets/{name}", s.groupSecretUpdateAPI)
171 mux.HandleFunc("POST /api/v1/groups/{path}/secrets/{name}/replace", s.groupSecretReplaceAPI)
172 mux.HandleFunc("DELETE /api/v1/groups/{path}/secrets/{name}", s.groupSecretDeleteAPI)
173 mux.HandleFunc("GET /{owner}/{repo}", s.repoHome)
174 mux.HandleFunc("GET /{owner}/{repo}/-/tree", s.treeRoot)
175 mux.HandleFunc("GET /{owner}/{repo}/-/tree/{path...}", s.tree)
176 mux.HandleFunc("GET /{owner}/{repo}/-/blob/{path...}", s.blob)
177 mux.HandleFunc("GET /{owner}/{repo}/-/commits", s.commits)
178 mux.HandleFunc("GET /{owner}/{repo}/-/tags", s.tags)
179 mux.HandleFunc("POST /{owner}/{repo}/-/tags", s.createTag)
180 mux.HandleFunc("POST /{owner}/{repo}/-/tags/delete", s.deleteTag)
181 mux.HandleFunc("GET /{owner}/{repo}/-/tags/archive", s.tagArchive)
182 mux.HandleFunc("GET /{owner}/{repo}/-/archive/{rev}/{file}", s.commitArchive)
183 mux.HandleFunc("GET /{owner}/{repo}/-/commit/{sha}", s.commit)
184 mux.HandleFunc("GET /{owner}/{repo}/-/branches/archive", s.branchArchive)
185 mux.HandleFunc("GET /{owner}/{repo}/-/branches", s.branches)
186 mux.HandleFunc("POST /{owner}/{repo}/-/branches", s.createBranch)
187 mux.HandleFunc("POST /{owner}/{repo}/-/branches/delete", s.deleteBranch)
188 mux.HandleFunc("POST /{owner}/{repo}/-/branches/rename", s.renameBranch)
189 mux.HandleFunc("GET /{owner}/{repo}/-/compare", s.compare)
190 mux.HandleFunc("POST /{owner}/{repo}/-/markdown", s.previewMarkdown)
191 mux.HandleFunc("POST /{owner}/{repo}/-/tasks", s.toggleTask)
192 mux.HandleFunc("GET /{owner}/{repo}/-/merge-requests", s.mergeRequests)
193 mux.HandleFunc("GET /{owner}/{repo}/-/merge-requests/new", s.newMR)
194 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests", s.createMR)
195 mux.HandleFunc("GET /{owner}/{repo}/-/merge-requests/{number}", s.showMR)
196 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}", s.updateMR)
197 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/merge", s.mergeMR)
198 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/close", s.closeMR)
199 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/reopen", s.reopenMR)
200 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/reviews", s.postReview)
201 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/reviews/dismiss", s.dismissReview)
202 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/notes", s.createNote)
203 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/suggestions", s.applySuggestions)
204 mux.HandleFunc("GET /{owner}/{repo}/-/issues", s.issuesPage)
205 mux.HandleFunc("GET /{owner}/{repo}/-/issues/new", s.newIssue)
206 mux.HandleFunc("POST /{owner}/{repo}/-/issues", s.createIssue)
207 mux.HandleFunc("POST /{owner}/{repo}/-/issues/labels", s.createIssueLabel)
208 mux.HandleFunc("POST /{owner}/{repo}/-/issues/milestones", s.createIssueMilestone)
209 mux.HandleFunc("GET /{owner}/{repo}/-/issues/{number}", s.showIssue)
210 mux.HandleFunc("POST /{owner}/{repo}/-/issues/{number}", s.postIssue)
211 mux.HandleFunc("GET /{owner}/{repo}/-/pipelines", s.pipelines)
212 mux.HandleFunc("POST /{owner}/{repo}/-/pipelines", s.runPipeline)
213 mux.HandleFunc("GET /{owner}/{repo}/-/pipelines/{id}", s.pipeline)
214 mux.HandleFunc("GET /{owner}/{repo}/-/pipelines/{id}/jobs/{job}", s.showJob)
215 mux.HandleFunc("GET /{owner}/{repo}/-/pipelines/{id}/jobs/{job}/log", s.jobLog)
216 mux.HandleFunc("POST /{owner}/{repo}/-/pipelines/{id}/jobs/{job}/play", s.playJob)
217 mux.HandleFunc("POST /{owner}/{repo}/-/pipelines/{id}/retry", s.retryPipeline)
218 mux.HandleFunc("GET /{owner}/{repo}/-/ci/editor", s.ciEditor)
219 mux.HandleFunc("POST /{owner}/{repo}/-/ci/editor", s.saveCIEditor)
220 mux.HandleFunc("POST /{owner}/{repo}/-/ci/lint", s.lintCI)
221 mux.HandleFunc("GET /{owner}/{repo}/-/releases", s.releases)
222 mux.HandleFunc("GET /{owner}/{repo}/-/releases/{tag}/assets/{name}", s.releaseAsset)
223 mux.HandleFunc("GET /{owner}/{repo}/-/logo", s.repoLogo)
224 mux.HandleFunc("POST /{owner}/{repo}/-/logo", s.uploadRepoLogo)
225 mux.HandleFunc("POST /{owner}/{repo}/-/star", s.toggleStar)
226 mux.HandleFunc("GET /{owner}/{repo}/-/settings", s.settings)
227 mux.HandleFunc("POST /{owner}/{repo}/-/settings", s.updateRepo)
228 mux.HandleFunc("POST /{owner}/{repo}/-/approvals", s.saveRepoApproval)
229 mux.HandleFunc("POST /{owner}/{repo}/-/members", s.repoMember)
230 mux.HandleFunc("POST /{owner}/{repo}/-/members/remove", s.repoMemberRemove)
231 mux.HandleFunc("POST /{owner}/{repo}/-/protected", s.addProtected)
232 mux.HandleFunc("POST /{owner}/{repo}/-/protected/remove", s.removeProtected)
233 mux.HandleFunc("POST /{owner}/{repo}/-/protected-tags", s.addProtectedTag)
234 mux.HandleFunc("POST /{owner}/{repo}/-/protected-tags/remove", s.removeProtectedTag)
235 mux.HandleFunc("POST /{owner}/{repo}/-/secrets", s.repoSecret)
236 mux.HandleFunc("POST /{owner}/{repo}/-/secrets/reveal", s.repoSecretReveal)
237 mux.HandleFunc("POST /{owner}/{repo}/-/secrets/delete", s.repoSecretDelete)
238 mux.HandleFunc("POST /{owner}/{repo}/-/webhooks", s.repoWebhook)
239 mux.HandleFunc("POST /{owner}/{repo}/-/webhooks/delete", s.repoWebhookDelete)
240 mux.HandleFunc("POST /{owner}/{repo}/-/delete", s.deleteRepo)
241
242 return s.realIP(s.withSession(s.secure(s.gate(mux))))
243}
244
245func (s *Server) realIP(next http.Handler) http.Handler {
246 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
247 realip.Apply(r, s.Cfg.ProxySet())
248 next.ServeHTTP(w, r)
249 })
250}
251
252func (s *Server) mustTemplates() {
253 if s.byLang != nil {
254 return
255 }
256 s.byLang = map[string]*template.Template{}
257 for _, lang := range i18n.All() {
258 l := lang
259 s.byLang[string(l)] = template.Must(template.New("web").Funcs(template.FuncMap{
260 "short": func(v string) string {
261 if len(v) > 10 {
262 return v[:10]
263 }
264 return v
265 },
266 "join": strings.Join,
267 "initial": func(s string) string {
268 s = strings.TrimSpace(s)
269 if s == "" {
270 return "?"
271 }
272 r, _ := utf8.DecodeRuneInString(s)
273 return strings.ToUpper(string(r))
274 },
275 "tileHue": tileHue,
276 "splitPath": func(p string) []string {
277 if p == "" {
278 return nil
279 }
280 return strings.Split(p, "/")
281 },
282 "iconOf": func(name string) string { return fileIcon(name, "blob") },
283 "t": func(key string, args ...any) string { return i18n.T(l, key, args...) },
284 "date": func(t time.Time) string { return i18n.FormatDate(l, t) },
285 "tn": func(n int, one, many string) string {
286 key := many
287 if n == 1 {
288 key = one
289 }
290 return i18n.T(l, key, n)
291 },
292 "roleName": func(r access.Role) string { return i18n.T(l, "role."+string(r)) },
293 "visName": func(v string) string { return i18n.T(l, "vis."+v) },
294 "presetName": func(id string) string {
295 label := i18n.T(l, "set.preset."+id)
296 if label == "set.preset."+id {
297 return id
298 }
299 return label
300 },
301 "printf": fmt.Sprintf,
302 "dict": func(kv ...any) (map[string]any, error) {
303 if len(kv)%2 != 0 {
304 return nil, fmt.Errorf("dict")
305 }
306 m := make(map[string]any, len(kv)/2)
307 for i := 0; i < len(kv); i += 2 {
308 key, ok := kv[i].(string)
309 if !ok {
310 return nil, fmt.Errorf("dict")
311 }
312 m[key] = kv[i+1]
313 }
314 return m, nil
315 },
316 }).ParseFS(webFS, "templates/*.html"))
317 }
318 s.tmpl = s.byLang[string(i18n.EN)]
319}
320
321func (s *Server) asset(w http.ResponseWriter, r *http.Request) {
322 name := r.PathValue("file")
323 if name == "" || strings.Contains(name, "/") || strings.Contains(name, "..") {
324 http.NotFound(w, r)
325 return
326 }
327 sub, err := fs.Sub(webFS, "static")
328 if err != nil {
329 http.Error(w, "assets", http.StatusInternalServerError)
330 return
331 }
332 http.ServeFileFS(w, r, sub, name)
333}
334
335func (s *Server) secure(next http.Handler) http.Handler {
336 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
337 w.Header().Set("X-Content-Type-Options", "nosniff")
338 w.Header().Set("X-Frame-Options", "DENY")
339 w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
340 w.Header().Set("Content-Security-Policy", "default-src 'self'; img-src 'self' https://auth.timfalken.com data:; style-src 'self'; form-action 'self'; base-uri 'self'; frame-ancestors 'none'")
341 next.ServeHTTP(w, r)
342 })
343}
344
345func (s *Server) withSession(next http.Handler) http.Handler {
346 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
347 p := principal{}
348 if c, err := r.Cookie("bluegit_session"); err == nil && c.Value != "" {
349 sess, err := s.Store.Session(r.Context(), c.Value)
350 if err == nil && sess.ExpiresAt.After(time.Now()) {
351 p.Session = sess
352 p.User = sess.User
353 p.OK = true
354 s.maybeExtend(r.Context(), sess)
355 }
356 }
357 next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, p)))
358 })
359}
360
361func (s *Server) maybeExtend(ctx context.Context, sess store.Session) {
362 if time.Until(sess.ExpiresAt) > 6*time.Hour {
363 return
364 }
365 sec, err := s.Auth.Extend(ctx, sess.AccessToken)
366 if err != nil || sec <= 0 {
367 return
368 }
369 _ = s.Store.UpdateSessionExpiry(ctx, sess.ID, time.Now().Add(time.Duration(sec)*time.Second))
370}
371
372func (s *Server) who(r *http.Request) principal {
373 p, _ := r.Context().Value(ctxKey{}).(principal)
374 return p
375}
376
377func (s *Server) csrfOK(w http.ResponseWriter, r *http.Request) bool {
378 if err := r.ParseForm(); err != nil {
379 http.Error(w, s.tr(r, "err.badForm"), http.StatusBadRequest)
380 return false
381 }
382 p := s.who(r)
383 if !p.OK || r.FormValue("csrf") == "" || r.FormValue("csrf") != p.Session.CSRF {
384 http.Error(w, s.tr(r, "err.badCSRF"), http.StatusBadRequest)
385 return false
386 }
387 return true
388}
389
390func (s *Server) loginRequired(w http.ResponseWriter, r *http.Request) (store.User, bool) {
391 p := s.who(r)
392 if !p.OK {
393 http.Redirect(w, r, "/login", http.StatusFound)
394 return store.User{}, false
395 }
396 return p.User, true
397}
398
399func (s *Server) setSessionCookie(w http.ResponseWriter, id string, exp time.Time) {
400 http.SetCookie(w, &http.Cookie{
401 Name: "bluegit_session",
402 Value: id,
403 Path: "/",
404 HttpOnly: true,
405 SameSite: http.SameSiteLaxMode,
406 Secure: strings.HasPrefix(s.Cfg.BaseURL, "https://"),
407 Expires: exp,
408 })
409}
410
411func (s *Server) flash(w http.ResponseWriter, notice, problem string) {
412 secure := strings.HasPrefix(s.Cfg.BaseURL, "https://")
413 if notice != "" {
414 http.SetCookie(w, &http.Cookie{Name: "bluegit_notice", Value: url.QueryEscape(notice), Path: "/", MaxAge: 120, HttpOnly: true, Secure: secure, SameSite: http.SameSiteLaxMode})
415 }
416 if problem != "" {
417 http.SetCookie(w, &http.Cookie{Name: "bluegit_error", Value: url.QueryEscape(problem), Path: "/", MaxAge: 120, HttpOnly: true, Secure: secure, SameSite: http.SameSiteLaxMode})
418 }
419}
420
421func (s *Server) takeFlash(w http.ResponseWriter, r *http.Request) (string, string) {
422 notice, problem := flashVal(r, "bluegit_notice"), flashVal(r, "bluegit_error")
423 if notice != "" {
424 http.SetCookie(w, &http.Cookie{Name: "bluegit_notice", Value: "", Path: "/", MaxAge: -1})
425 }
426 if problem != "" {
427 http.SetCookie(w, &http.Cookie{Name: "bluegit_error", Value: "", Path: "/", MaxAge: -1})
428 }
429 return notice, problem
430}
431
432func cookieVal(r *http.Request, name string) string {
433 c, err := r.Cookie(name)
434 if err != nil {
435 return ""
436 }
437 return c.Value
438}
439
440func flashVal(r *http.Request, name string) string {
441 raw := cookieVal(r, name)
442 if raw == "" {
443 return ""
444 }
445 v, err := url.QueryUnescape(raw)
446 if err != nil {
447 return raw
448 }
449 return v
450}
451
452func (s *Server) redirect(w http.ResponseWriter, r *http.Request, path, notice, problem string) {
453 s.flash(w, notice, problem)
454 http.Redirect(w, r, path, http.StatusSeeOther)
455}
456
457func (s *Server) langOf(r *http.Request) i18n.Lang {
458 if p := s.who(r); p.OK {
459 return i18n.Parse(p.User.Language)
460 }
461 return i18n.EN
462}
463
464func (s *Server) tr(r *http.Request, key string, args ...any) string {
465 return i18n.T(s.langOf(r), key, args...)
466}
467
468func (s *Server) trErr(r *http.Request, err error) string {
469 return i18n.Text(s.langOf(r), err)
470}
471
472func (s *Server) view(w http.ResponseWriter, r *http.Request, title string) View {
473 notice, problem := s.takeFlash(w, r)
474 lang := s.langOf(r)
475 if strings.HasPrefix(title, "title.") {
476 title = i18n.T(lang, title)
477 }
478 name := strings.TrimSpace(s.Cfg.Runner.Name)
479 if name == "" {
480 name = "Steve"
481 }
482 v := View{
483 Title: title, BaseURL: s.Cfg.BaseURL, RunnerName: name, Notice: notice, Err: problem,
484 StorageUnset: s.StoragePath() == "", Lang: string(lang), HTMLLang: htmlLang(lang),
485 Cunei: lang == i18n.Cuneiform,
486 }
487 for _, l := range i18n.All() {
488 v.Langs = append(v.Langs, LangChoice{Code: string(l), Label: l.Name()})
489 }
490 if p := s.who(r); p.OK && !isCrawler(r) {
491 u := p.User
492 v.User = &u
493 v.CSRF = p.Session.CSRF
494 }
495 pic := s.cardForPath(r.Context(), r.URL.Path, r.URL.RawQuery, r.URL.Fragment)
496 v.Social = &pic.Meta
497 return v
498}
499
500func htmlLang(l i18n.Lang) string {
501 switch l {
502 case i18n.NL:
503 return "nl"
504 case i18n.DE:
505 return "de"
506 case i18n.FR:
507 return "fr"
508 default:
509 return "en"
510 }
511}
512
513func (s *Server) render(w http.ResponseWriter, name string, v View) {
514 w.Header().Set("Content-Type", "text/html; charset=utf-8")
515 tmpl := s.byLang[v.Lang]
516 if tmpl == nil {
517 tmpl = s.tmpl
518 }
519 if err := tmpl.ExecuteTemplate(w, name, v); err != nil && s.Log != nil {
520 s.Log.Error("sjabloon", "name", name, "err", err)
521 }
522}
523
524func randomState() (string, error) {
525 b := make([]byte, 32)
526 if _, err := rand.Read(b); err != nil {
527 return "", err
528 }
529 return hex.EncodeToString(b), nil
530}
531
532// View is de gegevensset voor elk scherm.
533type View struct {
534 RunnerList []RunnerView
535 RunnerPref string
536 NewRunnerToken string
537 BuiltinFirst bool
538 RunnerOptIn bool
539 OptInNames []string
540 Title string
541 BaseURL string
542 RunnerName string
543 User *store.User
544 CSRF string
545 Notice string
546 Err string
547 Repos []store.Repo
548 Groups []store.Group
549 Repo *store.Repo
550 Role access.Role
551 CanWrite bool
552 CanAdmin bool
553 CanMerge bool
554 CanForce bool
555 CanComment bool
556 CanApply bool
557 Commits []CommitRow
558 CommitDays []CommitDay
559 CommitPrev string
560 CommitNext string
561 Commit *CommitRow
562 CommitDiff *CommitDiff
563 Entries []EntryRow
564 TreePath string
565 Blob string
566 BlobPath string
567 Binary bool
568 Branches []BranchRow
569 Branch *BranchBoard
570 MRs []store.MergeRequest
571 Flow *FlowBoard
572 MR *store.MergeRequest
573 Banner *MRBanner
574 MRPipe *PipeRow
575 MergeBlocks []string
576 Approval *ApprovalView
577 Reviews []ReviewRow
578 CanReview bool
579 CanApprove bool
580 CanDismiss bool
581 CanClose bool
582 CanReopen bool
583 IsOwner bool
584 Candidates []store.Member
585 Diff string
586 DiffFiles []DiffFileView
587 Pipes []store.Pipeline
588 PipeRows []PipeRow
589 Pipe *store.Pipeline
590 PipeSource string
591 PipeStatus string
592 PipeLabel string
593 PipeJobs []JobLink
594 PipeStages []StageView
595 PipeFailed bool
596 Live bool
597 LiveURL string
598 Jobs []store.Job
599 JobPage *JobPage
600 Editor *CIEditor
601 Releases []store.Release
602 Members []store.Member
603 Secrets []store.SecretMeta
604 HookSecrets []SecretChoice
605 Hooks []HookView
606 HookEdit HookDraft
607 Patterns []string
608 TagPatterns []string
609 Tags []TagRow
610 Tokens []store.TokenInfo
611 ShowExpiry bool
612 Keys []store.SSHKey
613 CloneHTTP string
614 CloneSSH string
615 Group *store.Group
616 Tab string
617 Rev string
618 NewToken string
619 StorageUnset bool
620 StoragePath string
621 StorageFree string
622 StorageUsed string
623 StorageTotal string
624 StoragePercent int
625 StorageBlueGit string
626 StoragePartial bool
627 Cache map[string]any
628 StorageReserved string
629 HasReserved bool
630 MinFree string
631 Wide bool
632 Info bool
633 Help bool
634 HelpDocs []HelpDoc
635 HelpDoc *HelpDoc
636 RunnerUI template.HTML
637 ShowUpdate bool
638 Update *UpdateView
639 HookDoc string
640 Spec cispec.Doc
641 SpecJSON template.JS
642 APIJSON template.JS
643 Page string
644 Lang string
645 HTMLLang string
646 Cunei bool
647 Langs []LangChoice
648 Query string
649 SortDir string
650 FlipDir string
651 Cards []RepoCard
652 Head *CommitRow
653 Files []FileRow
654 Tree []FileRow
655 Readme template.HTML
656 ReadmeName string
657 LicensePath string
658 NCommits int
659 NBranches int
660 NTags int
661 NReleases int
662 Created string
663 Lines []CodeLine
664 BlobSize string
665 FileName string
666 RevProtected bool
667 Heat *activity.Calendar
668 Notes []NoteRow
669 Profile *store.User
670 Card *ProfileCard
671 DescHTML template.HTML
672 Timeline []TimelineItem
673 CompareFrom string
674 CompareTo string
675 FormTitle string
676 Labels []string
677 CanEditMR bool
678 Issues *IssueBoard
679 IssueDoc string
680 DescTpls []string
681 TplPick string
682 FormBody string
683 Social *card.Meta
684}
685
686// LangChoice is één taal in de instellingen.
687type LangChoice struct {
688 Code, Label string
689}
690
691// RepoCard is een repository in een groepslijst.
692type RepoCard struct {
693 Repo store.Repo
694 Stars int
695 Starred bool
696 When string
697}
698
699// AccountLink is een naam die naar een profiel wijst.
700type AccountLink struct {
701 Name string
702 URL string
703}
704
705// ProfileCard is het blok over een gebruiker, boven de activiteitenkalender.
706type ProfileCard struct {
707 User store.User
708 Name, Since, Bio, URL string
709 Heading string
710 Repos, Groups, Contrib int
711 Own bool
712}
713
714// NoteRow is een reactie in de interface.
715type NoteRow struct {
716 ID int64
717 Author, AuthorURL, Body, When, Path string
718 Start, End int
719 HasSuggestion bool
720 ParentID int64
721 HTML template.HTML
722 Replies []NoteRow
723 At time.Time
724}
725
726// DiffFileView is één bestand in de merge-request-diff.
727type DiffFileView struct {
728 Path string
729 Lines []DiffLineView
730}
731
732// DiffLineView is één diffregel, met de reacties die op het nieuwe regelnummer eindigen.
733type DiffLineView struct {
734 Kind string
735 Text string
736 Old int
737 New int
738 Notes []NoteRow
739}
740
741// TagRow is één tag op de tagspagina.
742type TagRow struct {
743 Name, Message, SHA, Short, Subject, Date, When string
744 Annotated, Protected, HasRelease, CanDelete bool
745 ZipURL, TarURL string
746}
747
748// FileRow is een rij in de bestandstabel of de boom.
749type FileRow struct {
750 Name, Path, Icon, Subject, When, SHA string
751 Dir bool
752 Depth int
753 Active bool
754 // Open geldt voor een map die het huidige pad bevat. De browser
755 // onthoudt afwijkingen daarvan per repository.
756 Open bool
757}
758
759// CodeLine is één regel broncode.
760type CodeLine struct {
761 N int
762 HTML template.HTML
763}
764
765// CommitRow is een commit in de interface.
766// Author is de gekoppelde gebruiker, of anders de ruwe git-naam.
767// RawName en PushedBy zijn gezet als de pusher de fallback is en de git-naam afwijkt.
768type CommitRow struct {
769 SHA, Short, Author, Who, Date, Subject, Body, When string
770 UserURL, WhoURL, Avatar, Initial, RawName, PushedBy string
771 Ident template.HTML
772 PipeID int64
773 PipeStatus, PipeLabel, PipeDuration string
774 PipeStages []StageView
775 PipeLive, PipeFailed bool
776}
777
778// CommitDay is één dag op de commitlijst, nieuwste dag eerst.
779type CommitDay struct {
780 Label string
781 Items []CommitRow
782}
783
784// EntryRow is een bestand of map.
785type EntryRow struct {
786 Name, Type, Path string
787}
788
789// BranchRow is een branch, met of zonder bescherming.
790type BranchRow struct {
791 Name, SHA, Short, Subject, When, WhenTitle string
792 RepoPath, ZipURL, TarURL string
793 Protected, Default, CanEdit bool
794 Target string
795 Ahead, Behind int
796 Unix int64
797 PipeID int64
798 PipeStatus, PipeLabel string
799 OpenMRs []int64
800}
801
802// BranchBoard is de gegroepeerde branches-pagina.
803type BranchBoard struct {
804 State string
805 ShowActive, ShowStale bool
806 Active, Stale []BranchRow
807}
808
809// TimelineItem is één gebeurtenis of reactie op een merge request.
810type TimelineItem struct {
811 ID int64
812 Kind string
813 Actor, ActorURL, Text string
814 When string
815 Body string
816 HTML template.HTML
817 URL string
818 Replies []TimelineItem
819 At time.Time
820 Rank int
821}
822
823// HookView is een webhook plus de laatste pogingen.
824type HookView struct {
825 ID int64
826 Name string
827 Preset string
828 URL string
829 Method string
830 Filter string
831 Events string
832 Badges []string
833 Deliveries []store.Delivery
834}
835
836// HookDraft vult het webhookformulier bij bewerken. ID 0 is een nieuw formulier.
837type HookDraft struct {
838 ID int64
839 Name string
840 Preset string
841 Filter string
842 URL string
843 Username string
844 Avatar string
845 Icon string
846 Alias string
847 Token string
848 Chat string
849 Server string
850 Topic string
851 Home string
852 Room string
853 Method string
854 CType string
855 Headers string
856 Body string
857 OnPush bool
858 OnMR bool
859 OnOK bool
860 OnFail bool
861 OnRel bool
862 OnIssue bool
863 Extra []HookEventChoice
864}
865
866// HookEventChoice is een fijner event als vinkje in het webhookformulier.
867type HookEventChoice struct {
868 Name string
869 Key string
870 On bool
871}
872
873func repoURL(repo store.Repo) string { return "/" + repo.FullPath() }