BlueGit

timfa bluegit

Files

bluegit / internal / server / slug.go

slug.go

feat: nieuw-formulier, groepsoverzicht, logo's en talen
timfa project_87923614_bot_3aff574f6f98414b945a8799374f9092 · pushed by timfa · 3 weeks ago
Failed d1203d3b History
slug.go 2.1 KiB Download Raw
1package server
2
3import (
4 "encoding/json"
5 "net/http"
6 "net/url"
7 "strings"
8
9 "gitlab.com/Timfa/bluegit/internal/access"
10 "gitlab.com/Timfa/bluegit/internal/names"
11 "gitlab.com/Timfa/bluegit/internal/store"
12)
13
14type slugBody struct {
15 Name string `json:"name"`
16 URL string `json:"url"`
17 Available bool `json:"available"`
18}
19
20func (s *Server) slugPreview(w http.ResponseWriter, r *http.Request) {
21 u, ok := s.loginRequired(w, r)
22 if !ok {
23 return
24 }
25 kind := r.URL.Query().Get("kind")
26 raw := r.URL.Query().Get("name")
27 w.Header().Set("Content-Type", "application/json; charset=utf-8")
28 slug, err := names.Slug(kind, raw)
29 if strings.TrimSpace(raw) == "" || err != nil {
30 _ = json.NewEncoder(w).Encode(slugBody{})
31 return
32 }
33 host := publicHost(s.Cfg.BaseURL, r.Host)
34 var path string
35 ownerKind, ownerID := "user", u.ID
36 switch kind {
37 case "repo":
38 ownerKind, ownerID, path = s.previewOwnerRef(r, u)
39 path = host + "/" + path + "/" + slug
40 case "group":
41 path = host + "/groups/" + slug
42 default:
43 _ = json.NewEncoder(w).Encode(slugBody{})
44 return
45 }
46 taken, err := s.Store.SlugTaken(r.Context(), kind, slug, ownerKind, ownerID)
47 _ = json.NewEncoder(w).Encode(slugBody{Name: slug, URL: path, Available: err == nil && !taken})
48}
49
50func (s *Server) previewOwnerRef(r *http.Request, u store.User) (string, int64, string) {
51 path := s.previewOwner(r, u.ID, u.Username)
52 if path == u.Username {
53 return "user", u.ID, path
54 }
55 g, err := s.Store.GroupByPath(r.Context(), path)
56 if err != nil {
57 return "user", u.ID, u.Username
58 }
59 return "group", g.ID, g.Path
60}
61
62func (s *Server) previewOwner(r *http.Request, userID int64, username string) string {
63 owner := strings.TrimSpace(r.URL.Query().Get("owner"))
64 if owner == "" || owner == username {
65 return username
66 }
67 g, err := s.Store.GroupByPath(r.Context(), owner)
68 if err != nil {
69 return username
70 }
71 role, err := s.Store.GroupRole(r.Context(), g.ID, userID)
72 if err != nil || role == access.RoleNone {
73 return username
74 }
75 return g.Path
76}
77
78func publicHost(base, fallback string) string {
79 u, err := url.Parse(strings.TrimSpace(base))
80 if err != nil || u.Host == "" {
81 return fallback
82 }
83 return u.Host
84}