BlueGit

timfa bluegit

Files

bluegit / internal / server / server.go

server.go

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