BlueGit

timfa bluegit

Files

bluegit / internal / server / server.go

server.go

fix: verwijder slash-branches en de bron na een push-merge
timfa project_87923614_bot_3aff574f6f98414b945a8799374f9092 · pushed by timfa · 3 weeks ago
Passed cfe6072c History
server.go 25.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 "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 PipeStatus string
544 PipeLabel string
545 PipeJobs []JobLink
546 Live bool
547 LiveURL string
548 Jobs []store.Job
549 JobPage *JobPage
550 Editor *CIEditor
551 Releases []store.Release
552 Members []store.Member
553 Secrets []store.SecretMeta
554 HookSecrets []SecretChoice
555 Hooks []HookView
556 HookEdit HookDraft
557 Patterns []string
558 TagPatterns []string
559 Tags []TagRow
560 Tokens []store.TokenInfo
561 ShowExpiry bool
562 Keys []store.SSHKey
563 CloneHTTP string
564 CloneSSH string
565 Group *store.Group
566 Tab string
567 Rev string
568 NewToken string
569 StorageUnset bool
570 StoragePath string
571 StorageFree string
572 StorageTotal string
573 MinFree string
574 Wide bool
575 Info bool
576 ShowUpdate bool
577 Update *UpdateView
578 HookDoc string
579 Spec cispec.Doc
580 SpecJSON template.JS
581 APIJSON template.JS
582 Page string
583 Lang string
584 HTMLLang string
585 Cunei bool
586 Langs []LangChoice
587 Query string
588 SortDir string
589 FlipDir string
590 Cards []RepoCard
591 Head *CommitRow
592 Files []FileRow
593 Tree []FileRow
594 Readme template.HTML
595 ReadmeName string
596 LicensePath string
597 NCommits int
598 NBranches int
599 NTags int
600 NReleases int
601 Created string
602 Lines []CodeLine
603 BlobSize string
604 FileName string
605 RevProtected bool
606 Heat *activity.Calendar
607 Notes []NoteRow
608 Profile *store.User
609 DescHTML template.HTML
610 Timeline []TimelineItem
611 CompareFrom string
612 CompareTo string
613 FormTitle string
614 Labels []string
615 CanEditMR bool
616 Issues *IssueBoard
617 IssueDoc string
618 DescTpls []string
619 TplPick string
620 FormBody string
621 Social *card.Meta
622}
623
624// LangChoice is één taal in de instellingen.
625type LangChoice struct {
626 Code, Label string
627}
628
629// RepoCard is een repository in een groepslijst.
630type RepoCard struct {
631 Repo store.Repo
632 Stars int
633 Starred bool
634 When string
635}
636
637// NoteRow is een reactie in de interface.
638type NoteRow struct {
639 ID int64
640 Author, Body, When, Path string
641 Start, End int
642 HasSuggestion bool
643 ParentID int64
644 HTML template.HTML
645 Replies []NoteRow
646 At time.Time
647}
648
649// DiffFileView is één bestand in de merge-request-diff.
650type DiffFileView struct {
651 Path string
652 Lines []DiffLineView
653}
654
655// DiffLineView is één diffregel, met de reacties die op het nieuwe regelnummer eindigen.
656type DiffLineView struct {
657 Kind string
658 Text string
659 Old int
660 New int
661 Notes []NoteRow
662}
663
664// TagRow is één tag op de tagspagina.
665type TagRow struct {
666 Name, Message, SHA, Short, Subject, Date string
667 Annotated, Protected, HasRelease, CanDelete bool
668 ZipURL, TarURL string
669}
670
671// FileRow is een rij in de bestandstabel of de boom.
672type FileRow struct {
673 Name, Path, Icon, Subject, When, SHA string
674 Dir bool
675 Depth int
676 Active bool
677}
678
679// CodeLine is één regel broncode.
680type CodeLine struct {
681 N int
682 HTML template.HTML
683}
684
685// CommitRow is een commit in de interface.
686// Author is de gekoppelde gebruiker, of anders de ruwe git-naam.
687// RawName en PushedBy zijn gezet als de pusher de fallback is en de git-naam afwijkt.
688type CommitRow struct {
689 SHA, Short, Author, Date, Subject, Body, When string
690 UserURL, Avatar, Initial, RawName, PushedBy string
691 PipeID int64
692 PipeStatus, PipeLabel string
693}
694
695// EntryRow is een bestand of map.
696type EntryRow struct {
697 Name, Type, Path string
698}
699
700// BranchRow is een branch, met of zonder bescherming.
701type BranchRow struct {
702 Name, SHA, Short, Subject, When, WhenTitle string
703 Protected, Default bool
704 Ahead, Behind int
705 PipeID int64
706 PipeStatus, PipeLabel string
707 OpenMRs []int64
708}
709
710// TimelineItem is één gebeurtenis of reactie op een merge request.
711type TimelineItem struct {
712 ID int64
713 Kind string
714 Actor, Text string
715 When string
716 Body string
717 HTML template.HTML
718 URL string
719 Replies []TimelineItem
720 At time.Time
721 Rank int
722}
723
724// HookView is een webhook plus de laatste pogingen.
725type HookView struct {
726 ID int64
727 Name string
728 Preset string
729 URL string
730 Method string
731 Filter string
732 Events string
733 Badges []string
734 Deliveries []store.Delivery
735}
736
737// HookDraft vult het webhookformulier bij bewerken. ID 0 is een nieuw formulier.
738type HookDraft struct {
739 ID int64
740 Name string
741 Preset string
742 Filter string
743 URL string
744 Username string
745 Avatar string
746 Icon string
747 Alias string
748 Token string
749 Chat string
750 Server string
751 Topic string
752 Home string
753 Room string
754 Method string
755 CType string
756 Headers string
757 Body string
758 OnPush bool
759 OnMR bool
760 OnOK bool
761 OnFail bool
762 OnRel bool
763 OnIssue bool
764}
765
766func repoURL(repo store.Repo) string { return "/" + repo.FullPath() }