BlueGit

timfa bluegit

Files

bluegit / internal / server / server.go

server.go

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