BlueGit

timfa bluegit

Files

bluegit / internal / server / server.go

server.go

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