BlueGit

timfa bluegit

Files

bluegit / internal / server / git_http.go

git_http.go

feat: eerste basis van BlueGit
timfa project_87923614_bot_3aff574f6f98414b945a8799374f9092 · pushed by timfa · 3 weeks ago
151aa352 History
git_http.go 2.5 KiB Download Raw
1package server
2
3import (
4 "net/http"
5 "strings"
6
7 "gitlab.com/Timfa/bluegit/internal/access"
8 "gitlab.com/Timfa/bluegit/internal/gitrepo"
9 "gitlab.com/Timfa/bluegit/internal/store"
10)
11
12func (s *Server) gitHTTP(w http.ResponseWriter, r *http.Request) {
13 owner := r.PathValue("owner")
14 repoSeg := r.PathValue("repo")
15 if !strings.HasSuffix(repoSeg, ".git") {
16 http.NotFound(w, r)
17 return
18 }
19 name := strings.TrimSuffix(repoSeg, ".git")
20 repo, err := s.Store.RepoByPath(r.Context(), owner, name)
21 if err != nil {
22 http.NotFound(w, r)
23 return
24 }
25 service := r.URL.Query().Get("service")
26 write := service == "git-receive-pack" || strings.HasSuffix(r.URL.Path, "/git-receive-pack")
27 user, authed := s.gitUser(r)
28 var role access.Role
29 if authed {
30 role, err = s.Store.EffectiveRole(r.Context(), user.ID, repo.ID)
31 if err != nil {
32 http.Error(w, "rechten", http.StatusInternalServerError)
33 return
34 }
35 }
36 if write {
37 if !authed {
38 s.askAuth(w)
39 return
40 }
41 if !role.CanWriteCode() {
42 http.Error(w, "geen schrijfrechten", http.StatusForbidden)
43 return
44 }
45 } else if !role.CanRead() && repo.Visibility != "public" {
46 if !authed {
47 s.askAuth(w)
48 return
49 }
50 http.Error(w, "geen leesrechten", http.StatusForbidden)
51 return
52 }
53 dir := gitrepo.Dir(s.Cfg.StoragePath, repo.OwnerPath, repo.Name)
54 var before map[string]string
55 var extra []string
56 if write {
57 before, _ = gitrepo.Refs(r.Context(), s.Git, dir)
58 patterns, _ := s.Store.ProtectedPatterns(r.Context(), repo.ID)
59 extra = gitrepo.PushEnv(role, patterns)
60 }
61 rest := strings.TrimPrefix(r.URL.Path, "/"+owner+"/"+repoSeg)
62 pathInfo := gitrepo.PathInfo(owner, repoSeg, rest)
63 if err := gitrepo.ServeSmartHTTP(w, r, s.Git, gitrepo.ProjectRoot(s.Cfg.StoragePath), pathInfo, extra); err != nil && s.Log != nil {
64 s.Log.Error("git http", "err", err, "path", r.URL.Path)
65 }
66 if write {
67 after, err := gitrepo.Refs(r.Context(), s.Git, dir)
68 if err == nil {
69 s.AfterPush(repo, user, before, after)
70 }
71 }
72}
73
74func (s *Server) gitUser(r *http.Request) (store.User, bool) {
75 _, pass, ok := r.BasicAuth()
76 if !ok {
77 h := r.Header.Get("Authorization")
78 if strings.HasPrefix(strings.ToLower(h), "bearer ") {
79 pass = strings.TrimSpace(h[7:])
80 ok = pass != ""
81 }
82 }
83 if !ok || !strings.HasPrefix(pass, "bg_") {
84 return store.User{}, false
85 }
86 u, err := s.Store.UserByToken(r.Context(), pass)
87 return u, err == nil
88}
89
90func (s *Server) askAuth(w http.ResponseWriter) {
91 w.Header().Set("WWW-Authenticate", `Basic realm="BlueGit"`)
92 http.Error(w, "aanmelden met een toegangstoken als wachtwoord", http.StatusUnauthorized)
93}