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