BlueGit

timfa bluegit

Files

bluegit / internal / server / server.go

server.go

feat: lees .bluegit-sjablonen en klikbare takenlijsten
timfa project_87923614_bot_3aff574f6f98414b945a8799374f9092 · pushed by timfa · 3 weeks ago
79722e46 History
server.go 24.7 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("POST /{owner}/{repo}/-/tasks", s.toggleTask)
167 mux.HandleFunc("GET /{owner}/{repo}/-/merge-requests", s.mergeRequests)
168 mux.HandleFunc("GET /{owner}/{repo}/-/merge-requests/new", s.newMR)
169 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests", s.createMR)
170 mux.HandleFunc("GET /{owner}/{repo}/-/merge-requests/{number}", s.showMR)
171 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}", s.updateMR)
172 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/merge", s.mergeMR)
173 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/close", s.closeMR)
174 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/reopen", s.reopenMR)
175 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/reviews", s.postReview)
176 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/reviews/dismiss", s.dismissReview)
177 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/notes", s.createNote)
178 mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/suggestions", s.applySuggestions)
179 mux.HandleFunc("GET /{owner}/{repo}/-/issues", s.issuesPage)
180 mux.HandleFunc("GET /{owner}/{repo}/-/issues/new", s.newIssue)
181 mux.HandleFunc("POST /{owner}/{repo}/-/issues", s.createIssue)
182 mux.HandleFunc("POST /{owner}/{repo}/-/issues/labels", s.createIssueLabel)
183 mux.HandleFunc("POST /{owner}/{repo}/-/issues/milestones", s.createIssueMilestone)
184 mux.HandleFunc("GET /{owner}/{repo}/-/issues/{number}", s.showIssue)
185 mux.HandleFunc("POST /{owner}/{repo}/-/issues/{number}", s.postIssue)
186 mux.HandleFunc("GET /{owner}/{repo}/-/pipelines", s.pipelines)
187 mux.HandleFunc("POST /{owner}/{repo}/-/pipelines", s.runPipeline)
188 mux.HandleFunc("GET /{owner}/{repo}/-/pipelines/{id}", s.pipeline)
189 mux.HandleFunc("GET /{owner}/{repo}/-/pipelines/{id}/jobs/{job}", s.showJob)
190 mux.HandleFunc("GET /{owner}/{repo}/-/pipelines/{id}/jobs/{job}/log", s.jobLog)
191 mux.HandleFunc("POST /{owner}/{repo}/-/pipelines/{id}/jobs/{job}/play", s.playJob)
192 mux.HandleFunc("GET /{owner}/{repo}/-/ci/editor", s.ciEditor)
193 mux.HandleFunc("POST /{owner}/{repo}/-/ci/editor", s.saveCIEditor)
194 mux.HandleFunc("POST /{owner}/{repo}/-/ci/lint", s.lintCI)
195 mux.HandleFunc("GET /{owner}/{repo}/-/releases", s.releases)
196 mux.HandleFunc("GET /{owner}/{repo}/-/releases/{tag}/assets/{name}", s.releaseAsset)
197 mux.HandleFunc("GET /{owner}/{repo}/-/logo", s.repoLogo)
198 mux.HandleFunc("POST /{owner}/{repo}/-/logo", s.uploadRepoLogo)
199 mux.HandleFunc("POST /{owner}/{repo}/-/star", s.toggleStar)
200 mux.HandleFunc("GET /{owner}/{repo}/-/settings", s.settings)
201 mux.HandleFunc("POST /{owner}/{repo}/-/settings", s.updateRepo)
202 mux.HandleFunc("POST /{owner}/{repo}/-/approvals", s.saveRepoApproval)
203 mux.HandleFunc("POST /{owner}/{repo}/-/members", s.repoMember)
204 mux.HandleFunc("POST /{owner}/{repo}/-/members/remove", s.repoMemberRemove)
205 mux.HandleFunc("POST /{owner}/{repo}/-/protected", s.addProtected)
206 mux.HandleFunc("POST /{owner}/{repo}/-/protected/remove", s.removeProtected)
207 mux.HandleFunc("POST /{owner}/{repo}/-/protected-tags", s.addProtectedTag)
208 mux.HandleFunc("POST /{owner}/{repo}/-/protected-tags/remove", s.removeProtectedTag)
209 mux.HandleFunc("POST /{owner}/{repo}/-/secrets", s.repoSecret)
210 mux.HandleFunc("POST /{owner}/{repo}/-/secrets/reveal", s.repoSecretReveal)
211 mux.HandleFunc("POST /{owner}/{repo}/-/secrets/delete", s.repoSecretDelete)
212 mux.HandleFunc("POST /{owner}/{repo}/-/webhooks", s.repoWebhook)
213 mux.HandleFunc("POST /{owner}/{repo}/-/webhooks/delete", s.repoWebhookDelete)
214 mux.HandleFunc("POST /{owner}/{repo}/-/delete", s.deleteRepo)
215
216 return s.realIP(s.withSession(s.secure(s.gate(mux))))
217}
218
219func (s *Server) realIP(next http.Handler) http.Handler {
220 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
221 realip.Apply(r, s.Cfg.ProxySet())
222 next.ServeHTTP(w, r)
223 })
224}
225
226func (s *Server) mustTemplates() {
227 if s.byLang != nil {
228 return
229 }
230 s.byLang = map[string]*template.Template{}
231 for _, lang := range i18n.All() {
232 l := lang
233 s.byLang[string(l)] = template.Must(template.New("web").Funcs(template.FuncMap{
234 "short": func(v string) string {
235 if len(v) > 10 {
236 return v[:10]
237 }
238 return v
239 },
240 "join": strings.Join,
241 "initial": func(s string) string {
242 s = strings.TrimSpace(s)
243 if s == "" {
244 return "?"
245 }
246 r, _ := utf8.DecodeRuneInString(s)
247 return strings.ToUpper(string(r))
248 },
249 "splitPath": func(p string) []string {
250 if p == "" {
251 return nil
252 }
253 return strings.Split(p, "/")
254 },
255 "iconOf": func(name string) string { return fileIcon(name, "blob") },
256 "t": func(key string, args ...any) string { return i18n.T(l, key, args...) },
257 "date": func(t time.Time) string { return i18n.FormatDate(l, t) },
258 "tn": func(n int, one, many string) string {
259 key := many
260 if n == 1 {
261 key = one
262 }
263 return i18n.T(l, key, n)
264 },
265 "roleName": func(r access.Role) string { return i18n.T(l, "role."+string(r)) },
266 "visName": func(v string) string { return i18n.T(l, "vis."+v) },
267 "presetName": func(id string) string {
268 label := i18n.T(l, "set.preset."+id)
269 if label == "set.preset."+id {
270 return id
271 }
272 return label
273 },
274 }).ParseFS(webFS, "templates/*.html"))
275 }
276 s.tmpl = s.byLang[string(i18n.EN)]
277}
278
279func (s *Server) asset(w http.ResponseWriter, r *http.Request) {
280 name := r.PathValue("file")
281 if name == "" || strings.Contains(name, "/") || strings.Contains(name, "..") {
282 http.NotFound(w, r)
283 return
284 }
285 sub, err := fs.Sub(webFS, "static")
286 if err != nil {
287 http.Error(w, "assets", http.StatusInternalServerError)
288 return
289 }
290 http.ServeFileFS(w, r, sub, name)
291}
292
293func (s *Server) secure(next http.Handler) http.Handler {
294 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
295 w.Header().Set("X-Content-Type-Options", "nosniff")
296 w.Header().Set("X-Frame-Options", "DENY")
297 w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
298 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'")
299 next.ServeHTTP(w, r)
300 })
301}
302
303func (s *Server) withSession(next http.Handler) http.Handler {
304 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
305 p := principal{}
306 if c, err := r.Cookie("bluegit_session"); err == nil && c.Value != "" {
307 sess, err := s.Store.Session(r.Context(), c.Value)
308 if err == nil && sess.ExpiresAt.After(time.Now()) {
309 p.Session = sess
310 p.User = sess.User
311 p.OK = true
312 s.maybeExtend(r.Context(), sess)
313 }
314 }
315 next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, p)))
316 })
317}
318
319func (s *Server) maybeExtend(ctx context.Context, sess store.Session) {
320 if time.Until(sess.ExpiresAt) > 6*time.Hour {
321 return
322 }
323 sec, err := s.Auth.Extend(ctx, sess.AccessToken)
324 if err != nil || sec <= 0 {
325 return
326 }
327 _ = s.Store.UpdateSessionExpiry(ctx, sess.ID, time.Now().Add(time.Duration(sec)*time.Second))
328}
329
330func (s *Server) who(r *http.Request) principal {
331 p, _ := r.Context().Value(ctxKey{}).(principal)
332 return p
333}
334
335func (s *Server) csrfOK(w http.ResponseWriter, r *http.Request) bool {
336 if err := r.ParseForm(); err != nil {
337 http.Error(w, s.tr(r, "err.badForm"), http.StatusBadRequest)
338 return false
339 }
340 p := s.who(r)
341 if !p.OK || r.FormValue("csrf") == "" || r.FormValue("csrf") != p.Session.CSRF {
342 http.Error(w, s.tr(r, "err.badCSRF"), http.StatusBadRequest)
343 return false
344 }
345 return true
346}
347
348func (s *Server) loginRequired(w http.ResponseWriter, r *http.Request) (store.User, bool) {
349 p := s.who(r)
350 if !p.OK {
351 http.Redirect(w, r, "/login", http.StatusFound)
352 return store.User{}, false
353 }
354 return p.User, true
355}
356
357func (s *Server) setSessionCookie(w http.ResponseWriter, id string, exp time.Time) {
358 http.SetCookie(w, &http.Cookie{
359 Name: "bluegit_session",
360 Value: id,
361 Path: "/",
362 HttpOnly: true,
363 SameSite: http.SameSiteLaxMode,
364 Secure: strings.HasPrefix(s.Cfg.BaseURL, "https://"),
365 Expires: exp,
366 })
367}
368
369func (s *Server) flash(w http.ResponseWriter, notice, problem string) {
370 secure := strings.HasPrefix(s.Cfg.BaseURL, "https://")
371 if notice != "" {
372 http.SetCookie(w, &http.Cookie{Name: "bluegit_notice", Value: url.QueryEscape(notice), Path: "/", MaxAge: 120, HttpOnly: true, Secure: secure, SameSite: http.SameSiteLaxMode})
373 }
374 if problem != "" {
375 http.SetCookie(w, &http.Cookie{Name: "bluegit_error", Value: url.QueryEscape(problem), Path: "/", MaxAge: 120, HttpOnly: true, Secure: secure, SameSite: http.SameSiteLaxMode})
376 }
377}
378
379func (s *Server) takeFlash(w http.ResponseWriter, r *http.Request) (string, string) {
380 notice, problem := flashVal(r, "bluegit_notice"), flashVal(r, "bluegit_error")
381 if notice != "" {
382 http.SetCookie(w, &http.Cookie{Name: "bluegit_notice", Value: "", Path: "/", MaxAge: -1})
383 }
384 if problem != "" {
385 http.SetCookie(w, &http.Cookie{Name: "bluegit_error", Value: "", Path: "/", MaxAge: -1})
386 }
387 return notice, problem
388}
389
390func cookieVal(r *http.Request, name string) string {
391 c, err := r.Cookie(name)
392 if err != nil {
393 return ""
394 }
395 return c.Value
396}
397
398func flashVal(r *http.Request, name string) string {
399 raw := cookieVal(r, name)
400 if raw == "" {
401 return ""
402 }
403 v, err := url.QueryUnescape(raw)
404 if err != nil {
405 return raw
406 }
407 return v
408}
409
410func (s *Server) redirect(w http.ResponseWriter, r *http.Request, path, notice, problem string) {
411 s.flash(w, notice, problem)
412 http.Redirect(w, r, path, http.StatusSeeOther)
413}
414
415func (s *Server) langOf(r *http.Request) i18n.Lang {
416 if p := s.who(r); p.OK {
417 return i18n.Parse(p.User.Language)
418 }
419 return i18n.EN
420}
421
422func (s *Server) tr(r *http.Request, key string, args ...any) string {
423 return i18n.T(s.langOf(r), key, args...)
424}
425
426func (s *Server) trErr(r *http.Request, err error) string {
427 return i18n.Text(s.langOf(r), err)
428}
429
430func (s *Server) view(w http.ResponseWriter, r *http.Request, title string) View {
431 notice, problem := s.takeFlash(w, r)
432 lang := s.langOf(r)
433 if strings.HasPrefix(title, "title.") {
434 title = i18n.T(lang, title)
435 }
436 name := strings.TrimSpace(s.Cfg.Runner.Name)
437 if name == "" {
438 name = "Steve"
439 }
440 v := View{
441 Title: title, BaseURL: s.Cfg.BaseURL, RunnerName: name, Notice: notice, Err: problem,
442 StorageUnset: s.StoragePath() == "", Lang: string(lang), HTMLLang: htmlLang(lang),
443 Cunei: lang == i18n.Cuneiform,
444 }
445 for _, l := range i18n.All() {
446 v.Langs = append(v.Langs, LangChoice{Code: string(l), Label: l.Name()})
447 }
448 if p := s.who(r); p.OK {
449 u := p.User
450 v.User = &u
451 v.CSRF = p.Session.CSRF
452 }
453 return v
454}
455
456func htmlLang(l i18n.Lang) string {
457 switch l {
458 case i18n.NL:
459 return "nl"
460 case i18n.DE:
461 return "de"
462 case i18n.FR:
463 return "fr"
464 default:
465 return "en"
466 }
467}
468
469func (s *Server) render(w http.ResponseWriter, name string, v View) {
470 w.Header().Set("Content-Type", "text/html; charset=utf-8")
471 tmpl := s.byLang[v.Lang]
472 if tmpl == nil {
473 tmpl = s.tmpl
474 }
475 if err := tmpl.ExecuteTemplate(w, name, v); err != nil && s.Log != nil {
476 s.Log.Error("sjabloon", "name", name, "err", err)
477 }
478}
479
480func randomState() (string, error) {
481 b := make([]byte, 32)
482 if _, err := rand.Read(b); err != nil {
483 return "", err
484 }
485 return hex.EncodeToString(b), nil
486}
487
488// View is de gegevensset voor elk scherm.
489type View struct {
490 Title string
491 BaseURL string
492 RunnerName string
493 User *store.User
494 CSRF string
495 Notice string
496 Err string
497 Repos []store.Repo
498 Groups []store.Group
499 Repo *store.Repo
500 Role access.Role
501 CanWrite bool
502 CanAdmin bool
503 CanMerge bool
504 CanComment bool
505 CanApply bool
506 Commits []CommitRow
507 Commit *CommitRow
508 CommitDiff *CommitDiff
509 Entries []EntryRow
510 TreePath string
511 Blob string
512 BlobPath string
513 Binary bool
514 Branches []BranchRow
515 MRs []store.MergeRequest
516 MR *store.MergeRequest
517 MRPipe *PipeRow
518 MergeBlocks []string
519 Approval *ApprovalView
520 Reviews []ReviewRow
521 CanReview bool
522 CanApprove bool
523 CanDismiss bool
524 CanClose bool
525 CanReopen bool
526 IsOwner bool
527 Candidates []store.Member
528 Diff string
529 DiffFiles []DiffFileView
530 Pipes []store.Pipeline
531 PipeRows []PipeRow
532 Pipe *store.Pipeline
533 PipeStatus string
534 PipeLabel string
535 PipeJobs []JobLink
536 Live bool
537 LiveURL string
538 Jobs []store.Job
539 JobPage *JobPage
540 Editor *CIEditor
541 Releases []store.Release
542 Members []store.Member
543 Secrets []store.SecretMeta
544 HookSecrets []SecretChoice
545 Hooks []HookView
546 HookEdit HookDraft
547 Patterns []string
548 TagPatterns []string
549 Tags []TagRow
550 Tokens []store.TokenInfo
551 ShowExpiry bool
552 Keys []store.SSHKey
553 CloneHTTP string
554 CloneSSH string
555 Group *store.Group
556 Tab string
557 Rev string
558 NewToken string
559 StorageUnset bool
560 StoragePath string
561 StorageFree string
562 StorageTotal string
563 MinFree string
564 Wide bool
565 Info bool
566 ShowUpdate bool
567 Update *UpdateView
568 HookDoc string
569 Spec cispec.Doc
570 SpecJSON template.JS
571 APIJSON template.JS
572 Page string
573 Lang string
574 HTMLLang string
575 Cunei bool
576 Langs []LangChoice
577 Query string
578 SortDir string
579 FlipDir string
580 Cards []RepoCard
581 Head *CommitRow
582 Files []FileRow
583 Tree []FileRow
584 Readme template.HTML
585 ReadmeName string
586 LicensePath string
587 NCommits int
588 NBranches int
589 NTags int
590 NReleases int
591 Created string
592 Lines []CodeLine
593 BlobSize string
594 FileName string
595 RevProtected bool
596 Heat *activity.Calendar
597 Notes []NoteRow
598 Profile *store.User
599 DescHTML template.HTML
600 Timeline []TimelineItem
601 CompareFrom string
602 CompareTo string
603 FormTitle string
604 Labels []string
605 CanEditMR bool
606 Issues *IssueBoard
607 IssueDoc string
608 DescTpls []string
609 TplPick string
610 FormBody string
611}
612
613// LangChoice is één taal in de instellingen.
614type LangChoice struct {
615 Code, Label string
616}
617
618// RepoCard is een repository in een groepslijst.
619type RepoCard struct {
620 Repo store.Repo
621 Stars int
622 Starred bool
623 When string
624}
625
626// NoteRow is een reactie in de interface.
627type NoteRow struct {
628 ID int64
629 Author, Body, When, Path string
630 Start, End int
631 HasSuggestion bool
632 ParentID int64
633 HTML template.HTML
634 Replies []NoteRow
635 At time.Time
636}
637
638// DiffFileView is één bestand in de merge-request-diff.
639type DiffFileView struct {
640 Path string
641 Lines []DiffLineView
642}
643
644// DiffLineView is één diffregel, met de reacties die op het nieuwe regelnummer eindigen.
645type DiffLineView struct {
646 Kind string
647 Text string
648 Old int
649 New int
650 Notes []NoteRow
651}
652
653// TagRow is één tag op de tagspagina.
654type TagRow struct {
655 Name, Message, SHA, Short, Subject, Date string
656 Annotated, Protected, HasRelease, CanDelete bool
657 ZipURL, TarURL string
658}
659
660// FileRow is een rij in de bestandstabel of de boom.
661type FileRow struct {
662 Name, Path, Icon, Subject, When, SHA string
663 Dir bool
664 Depth int
665 Active bool
666}
667
668// CodeLine is één regel broncode.
669type CodeLine struct {
670 N int
671 HTML template.HTML
672}
673
674// CommitRow is een commit in de interface.
675// Author is de gekoppelde gebruiker, of anders de ruwe git-naam.
676// RawName en PushedBy zijn gezet als de pusher de fallback is en de git-naam afwijkt.
677type CommitRow struct {
678 SHA, Short, Author, Date, Subject, Body, When string
679 UserURL, Avatar, Initial, RawName, PushedBy string
680 PipeID int64
681 PipeStatus, PipeLabel string
682}
683
684// EntryRow is een bestand of map.
685type EntryRow struct {
686 Name, Type, Path string
687}
688
689// BranchRow is een branch, met of zonder bescherming.
690type BranchRow struct {
691 Name, SHA, Short, Subject, When string
692 Protected, Default bool
693 Ahead, Behind int
694 PipeID int64
695 PipeStatus, PipeLabel string
696 MRNumber int64
697}
698
699// TimelineItem is één gebeurtenis of reactie op een merge request.
700type TimelineItem struct {
701 ID int64
702 Kind string
703 Actor, Text string
704 When string
705 Body string
706 HTML template.HTML
707 URL string
708 Replies []TimelineItem
709 At time.Time
710 Rank int
711}
712
713// HookView is een webhook plus de laatste pogingen.
714type HookView struct {
715 ID int64
716 Name string
717 Preset string
718 URL string
719 Method string
720 Filter string
721 Events string
722 Badges []string
723 Deliveries []store.Delivery
724}
725
726// HookDraft vult het webhookformulier bij bewerken. ID 0 is een nieuw formulier.
727type HookDraft struct {
728 ID int64
729 Name string
730 Preset string
731 Filter string
732 URL string
733 Username string
734 Avatar string
735 Icon string
736 Alias string
737 Token string
738 Chat string
739 Server string
740 Topic string
741 Home string
742 Room string
743 Method string
744 CType string
745 Headers string
746 Body string
747 OnPush bool
748 OnMR bool
749 OnOK bool
750 OnFail bool
751 OnRel bool
752 OnIssue bool
753}
754
755func repoURL(repo store.Repo) string { return "/" + repo.FullPath() }