| 1 | package server |
| 2 | |
| 3 | import ( |
| 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 | ) |
| 12 | |
| 13 | func (s *Server) slugPreview(w http.ResponseWriter, r *http.Request) { |
| 14 | u, ok := s.loginRequired(w, r) |
| 15 | if !ok { |
| 16 | return |
| 17 | } |
| 18 | kind := r.URL.Query().Get("kind") |
| 19 | raw := r.URL.Query().Get("name") |
| 20 | w.Header().Set("Content-Type", "application/json; charset=utf-8") |
| 21 | slug, err := names.Slug(kind, raw) |
| 22 | if strings.TrimSpace(raw) == "" || err != nil { |
| 23 | _ = json.NewEncoder(w).Encode(map[string]string{"name": "", "url": ""}) |
| 24 | return |
| 25 | } |
| 26 | host := publicHost(s.Cfg.BaseURL, r.Host) |
| 27 | var path string |
| 28 | switch kind { |
| 29 | case "repo": |
| 30 | owner := s.previewOwner(r, u.ID, u.Username) |
| 31 | path = host + "/" + owner + "/" + slug |
| 32 | case "group": |
| 33 | path = host + "/groups/" + slug |
| 34 | default: |
| 35 | _ = json.NewEncoder(w).Encode(map[string]string{"name": "", "url": ""}) |
| 36 | return |
| 37 | } |
| 38 | _ = json.NewEncoder(w).Encode(map[string]string{"name": slug, "url": path}) |
| 39 | } |
| 40 | |
| 41 | func (s *Server) previewOwner(r *http.Request, userID int64, username string) string { |
| 42 | owner := strings.TrimSpace(r.URL.Query().Get("owner")) |
| 43 | if owner == "" || owner == username { |
| 44 | return username |
| 45 | } |
| 46 | g, err := s.Store.GroupByPath(r.Context(), owner) |
| 47 | if err != nil { |
| 48 | return username |
| 49 | } |
| 50 | role, err := s.Store.GroupRole(r.Context(), g.ID, userID) |
| 51 | if err != nil || role == access.RoleNone { |
| 52 | return username |
| 53 | } |
| 54 | return g.Path |
| 55 | } |
| 56 | |
| 57 | func publicHost(base, fallback string) string { |
| 58 | u, err := url.Parse(strings.TrimSpace(base)) |
| 59 | if err != nil || u.Host == "" { |
| 60 | return fallback |
| 61 | } |
| 62 | return u.Host |
| 63 | } |