BlueGit

timfa bluegit

Files

bluegit / internal / server / server.go

server.go

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