BlueGit

timfa bluegit

Files

bluegit / internal / server / server.go

server.go

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