BlueGit

timfa bluegit

Files

bluegit / internal / server / server.go

server.go

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