BlueGit

timfa bluegit

Files

bluegit / internal / server / server.go

server.go

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