BlueGit

timfa bluegit

Files

bluegit / internal / server / server.go

server.go

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