@@ -0,0 +1,370 @@ |
| 1 | +// SPDX-License-Identifier: AGPL-3.0-or-later |
| 2 | + |
| 3 | +// Package orgs wires the S30 organization web surface: |
| 4 | +// |
| 5 | +// GET /organizations/new create form |
| 6 | +// POST /organizations create submit |
| 7 | +// GET /{org}/people members + pending invites + invite form |
| 8 | +// POST /{org}/people/invite invite by username or email |
| 9 | +// POST /{org}/people/{user}/role change role |
| 10 | +// POST /{org}/people/{user}/remove remove member |
| 11 | +// GET /invitations/{token} accept/decline view |
| 12 | +// POST /invitations/{token}/accept accept |
| 13 | +// POST /invitations/{token}/decline decline |
| 14 | +// |
| 15 | +// Profile rendering for /{org} is dispatched from the existing |
| 16 | +// /{username} catch-all in internal/web/handlers/profile via the |
| 17 | +// principals.Resolve lookup; this handler set only owns the org- |
| 18 | +// specific surfaces. |
| 19 | +package orgs |
| 20 | + |
| 21 | +import ( |
| 22 | + "errors" |
| 23 | + "log/slog" |
| 24 | + "net/http" |
| 25 | + "strconv" |
| 26 | + "strings" |
| 27 | + |
| 28 | + "github.com/go-chi/chi/v5" |
| 29 | + "github.com/jackc/pgx/v5/pgxpool" |
| 30 | + |
| 31 | + authemail "github.com/tenseleyFlow/shithub/internal/auth/email" |
| 32 | + "github.com/tenseleyFlow/shithub/internal/orgs" |
| 33 | + orgsdb "github.com/tenseleyFlow/shithub/internal/orgs/sqlc" |
| 34 | + "github.com/tenseleyFlow/shithub/internal/web/middleware" |
| 35 | + "github.com/tenseleyFlow/shithub/internal/web/render" |
| 36 | +) |
| 37 | + |
| 38 | +// Deps wires the handler set. |
| 39 | +type Deps struct { |
| 40 | + Logger *slog.Logger |
| 41 | + Render *render.Renderer |
| 42 | + Pool *pgxpool.Pool |
| 43 | + EmailSender authemail.Sender |
| 44 | + EmailFrom string |
| 45 | + SiteName string |
| 46 | + BaseURL string |
| 47 | +} |
| 48 | + |
| 49 | +// Handlers groups the org surface handlers. |
| 50 | +type Handlers struct { |
| 51 | + d Deps |
| 52 | +} |
| 53 | + |
| 54 | +// New constructs the handler set, validating Deps. |
| 55 | +func New(d Deps) (*Handlers, error) { |
| 56 | + if d.Render == nil { |
| 57 | + return nil, errors.New("orgs handlers: nil Render") |
| 58 | + } |
| 59 | + if d.Pool == nil { |
| 60 | + return nil, errors.New("orgs handlers: nil Pool") |
| 61 | + } |
| 62 | + return &Handlers{d: d}, nil |
| 63 | +} |
| 64 | + |
| 65 | +// MountCreate registers /organizations/new + POST /organizations. |
| 66 | +// Caller wraps these in RequireUser since both require a logged-in |
| 67 | +// creator. The /organizations prefix is on the auth-reserved list so |
| 68 | +// it never shadows a user/org slug. |
| 69 | +func (h *Handlers) MountCreate(r chi.Router) { |
| 70 | + r.Get("/organizations/new", h.newForm) |
| 71 | + r.Post("/organizations", h.createSubmit) |
| 72 | +} |
| 73 | + |
| 74 | +// MountOrgRoutes registers the per-org surface under /{org}/people |
| 75 | +// and /{org}/settings. Caller MUST register this before the |
| 76 | +// /{username} catch-all so the `people` segment matches. |
| 77 | +// |
| 78 | +// Member-management routes live behind RequireUser at the wiring |
| 79 | +// layer (server.go); profile-style reads stay public. |
| 80 | +func (h *Handlers) MountOrgRoutes(r chi.Router) { |
| 81 | + r.Get("/{org}/people", h.peoplePage) |
| 82 | + r.Post("/{org}/people/invite", h.invite) |
| 83 | + r.Post("/{org}/people/{userID}/role", h.changeRole) |
| 84 | + r.Post("/{org}/people/{userID}/remove", h.removeMember) |
| 85 | +} |
| 86 | + |
| 87 | +// MountInvitations registers /invitations/{token}* — accept/decline. |
| 88 | +// Authed-only; the page also shows a hint when the viewer's logged-in |
| 89 | +// user doesn't match the invite's target email. |
| 90 | +func (h *Handlers) MountInvitations(r chi.Router) { |
| 91 | + r.Get("/invitations/{token}", h.invitationView) |
| 92 | + r.Post("/invitations/{token}/accept", h.invitationAccept) |
| 93 | + r.Post("/invitations/{token}/decline", h.invitationDecline) |
| 94 | +} |
| 95 | + |
| 96 | +// ─── helpers ─────────────────────────────────────────────────────── |
| 97 | + |
| 98 | +func (h *Handlers) deps() orgs.Deps { |
| 99 | + return orgs.Deps{ |
| 100 | + Pool: h.d.Pool, |
| 101 | + Logger: h.d.Logger, |
| 102 | + EmailSender: h.d.EmailSender, |
| 103 | + EmailFrom: h.d.EmailFrom, |
| 104 | + SiteName: h.d.SiteName, |
| 105 | + BaseURL: h.d.BaseURL, |
| 106 | + } |
| 107 | +} |
| 108 | + |
| 109 | +// orgFromSlug resolves the org from a {org} URL param, with an |
| 110 | +// existence-leak-safe 404 path. |
| 111 | +func (h *Handlers) orgFromSlug(w http.ResponseWriter, r *http.Request) (orgsdb.Org, bool) { |
| 112 | + slug := chi.URLParam(r, "org") |
| 113 | + row, err := orgsdb.New().GetOrgBySlug(r.Context(), h.d.Pool, slug) |
| 114 | + if err != nil { |
| 115 | + h.d.Render.HTTPError(w, r, http.StatusNotFound, "") |
| 116 | + return orgsdb.Org{}, false |
| 117 | + } |
| 118 | + return row, true |
| 119 | +} |
| 120 | + |
| 121 | +func parseUserIDParam(s string) (int64, error) { |
| 122 | + return strconv.ParseInt(s, 10, 64) |
| 123 | +} |
| 124 | + |
| 125 | +// ─── create ──────────────────────────────────────────────────────── |
| 126 | + |
| 127 | +func (h *Handlers) newForm(w http.ResponseWriter, r *http.Request) { |
| 128 | + viewer := middleware.CurrentUserFromContext(r.Context()) |
| 129 | + if viewer.IsAnonymous() { |
| 130 | + http.Redirect(w, r, "/login?next=/organizations/new", http.StatusSeeOther) |
| 131 | + return |
| 132 | + } |
| 133 | + h.renderNewForm(w, r, "", "") |
| 134 | +} |
| 135 | + |
| 136 | +func (h *Handlers) createSubmit(w http.ResponseWriter, r *http.Request) { |
| 137 | + viewer := middleware.CurrentUserFromContext(r.Context()) |
| 138 | + if viewer.IsAnonymous() { |
| 139 | + http.Redirect(w, r, "/login?next=/organizations/new", http.StatusSeeOther) |
| 140 | + return |
| 141 | + } |
| 142 | + if err := r.ParseForm(); err != nil { |
| 143 | + h.d.Render.HTTPError(w, r, http.StatusBadRequest, "") |
| 144 | + return |
| 145 | + } |
| 146 | + slug := strings.TrimSpace(r.PostFormValue("slug")) |
| 147 | + displayName := strings.TrimSpace(r.PostFormValue("display_name")) |
| 148 | + billingEmail := strings.TrimSpace(r.PostFormValue("billing_email")) |
| 149 | + |
| 150 | + row, err := orgs.Create(r.Context(), h.deps(), orgs.CreateParams{ |
| 151 | + Slug: slug, |
| 152 | + DisplayName: displayName, |
| 153 | + BillingEmail: billingEmail, |
| 154 | + CreatedByUserID: viewer.ID, |
| 155 | + }) |
| 156 | + if err != nil { |
| 157 | + h.renderNewForm(w, r, slug, friendlyOrgErr(err)) |
| 158 | + return |
| 159 | + } |
| 160 | + http.Redirect(w, r, "/"+row.Slug, http.StatusSeeOther) |
| 161 | +} |
| 162 | + |
| 163 | +func (h *Handlers) renderNewForm(w http.ResponseWriter, r *http.Request, slug, errMsg string) { |
| 164 | + _ = h.d.Render.RenderPage(w, r, "orgs/new", map[string]any{ |
| 165 | + "Title": "New organization", |
| 166 | + "CSRFToken": middleware.CSRFTokenForRequest(r), |
| 167 | + "Slug": slug, |
| 168 | + "Error": errMsg, |
| 169 | + }) |
| 170 | +} |
| 171 | + |
| 172 | +// ─── people ──────────────────────────────────────────────────────── |
| 173 | + |
| 174 | +func (h *Handlers) peoplePage(w http.ResponseWriter, r *http.Request) { |
| 175 | + org, ok := h.orgFromSlug(w, r) |
| 176 | + if !ok { |
| 177 | + return |
| 178 | + } |
| 179 | + viewer := middleware.CurrentUserFromContext(r.Context()) |
| 180 | + q := orgsdb.New() |
| 181 | + members, err := q.ListOrgMembers(r.Context(), h.d.Pool, org.ID) |
| 182 | + if err != nil { |
| 183 | + h.d.Logger.ErrorContext(r.Context(), "orgs: list members", "error", err) |
| 184 | + h.d.Render.HTTPError(w, r, http.StatusInternalServerError, "") |
| 185 | + return |
| 186 | + } |
| 187 | + var pending []orgsdb.ListPendingInvitationsForOrgRow |
| 188 | + isOwner := false |
| 189 | + if !viewer.IsAnonymous() { |
| 190 | + isOwner, _ = orgs.IsOwner(r.Context(), h.deps(), org.ID, viewer.ID) |
| 191 | + if isOwner { |
| 192 | + pending, _ = q.ListPendingInvitationsForOrg(r.Context(), h.d.Pool, org.ID) |
| 193 | + } |
| 194 | + } |
| 195 | + _ = h.d.Render.RenderPage(w, r, "orgs/people", map[string]any{ |
| 196 | + "Title": org.Slug + " · people", |
| 197 | + "CSRFToken": middleware.CSRFTokenForRequest(r), |
| 198 | + "Org": org, |
| 199 | + "Members": members, |
| 200 | + "Pending": pending, |
| 201 | + "IsOwner": isOwner, |
| 202 | + }) |
| 203 | +} |
| 204 | + |
| 205 | +func (h *Handlers) invite(w http.ResponseWriter, r *http.Request) { |
| 206 | + org, ok := h.orgFromSlug(w, r) |
| 207 | + if !ok { |
| 208 | + return |
| 209 | + } |
| 210 | + viewer := middleware.CurrentUserFromContext(r.Context()) |
| 211 | + if viewer.IsAnonymous() { |
| 212 | + h.d.Render.HTTPError(w, r, http.StatusUnauthorized, "") |
| 213 | + return |
| 214 | + } |
| 215 | + owner, err := orgs.IsOwner(r.Context(), h.deps(), org.ID, viewer.ID) |
| 216 | + if err != nil || !owner { |
| 217 | + h.d.Render.HTTPError(w, r, http.StatusForbidden, "") |
| 218 | + return |
| 219 | + } |
| 220 | + if err := r.ParseForm(); err != nil { |
| 221 | + h.d.Render.HTTPError(w, r, http.StatusBadRequest, "") |
| 222 | + return |
| 223 | + } |
| 224 | + target := strings.TrimSpace(r.PostFormValue("target")) |
| 225 | + role := r.PostFormValue("role") |
| 226 | + if role == "" { |
| 227 | + role = "member" |
| 228 | + } |
| 229 | + p := orgs.InviteParams{ |
| 230 | + OrgID: org.ID, |
| 231 | + InvitedByUserID: viewer.ID, |
| 232 | + Role: role, |
| 233 | + } |
| 234 | + if strings.Contains(target, "@") { |
| 235 | + p.TargetEmail = target |
| 236 | + } else { |
| 237 | + p.TargetUsername = target |
| 238 | + } |
| 239 | + if _, err := orgs.Invite(r.Context(), h.deps(), p); err != nil { |
| 240 | + h.d.Logger.WarnContext(r.Context(), "orgs: invite failed", |
| 241 | + "org", org.Slug, "target", target, "error", err) |
| 242 | + } |
| 243 | + http.Redirect(w, r, "/"+org.Slug+"/people", http.StatusSeeOther) |
| 244 | +} |
| 245 | + |
| 246 | +func (h *Handlers) changeRole(w http.ResponseWriter, r *http.Request) { |
| 247 | + h.memberMutate(w, r, func(orgID, userID int64) error { |
| 248 | + role := r.PostFormValue("role") |
| 249 | + return orgs.ChangeRole(r.Context(), h.deps(), orgID, userID, role) |
| 250 | + }) |
| 251 | +} |
| 252 | + |
| 253 | +func (h *Handlers) removeMember(w http.ResponseWriter, r *http.Request) { |
| 254 | + h.memberMutate(w, r, func(orgID, userID int64) error { |
| 255 | + return orgs.RemoveMember(r.Context(), h.deps(), orgID, userID) |
| 256 | + }) |
| 257 | +} |
| 258 | + |
| 259 | +// memberMutate is the shared owner-check + redirect wrapper for the |
| 260 | +// member-management POSTs. Centralizes the policy gate so each route |
| 261 | +// is one line. |
| 262 | +func (h *Handlers) memberMutate(w http.ResponseWriter, r *http.Request, action func(orgID, userID int64) error) { |
| 263 | + org, ok := h.orgFromSlug(w, r) |
| 264 | + if !ok { |
| 265 | + return |
| 266 | + } |
| 267 | + viewer := middleware.CurrentUserFromContext(r.Context()) |
| 268 | + if viewer.IsAnonymous() { |
| 269 | + h.d.Render.HTTPError(w, r, http.StatusUnauthorized, "") |
| 270 | + return |
| 271 | + } |
| 272 | + owner, _ := orgs.IsOwner(r.Context(), h.deps(), org.ID, viewer.ID) |
| 273 | + if !owner { |
| 274 | + h.d.Render.HTTPError(w, r, http.StatusForbidden, "") |
| 275 | + return |
| 276 | + } |
| 277 | + if err := r.ParseForm(); err != nil { |
| 278 | + h.d.Render.HTTPError(w, r, http.StatusBadRequest, "") |
| 279 | + return |
| 280 | + } |
| 281 | + uid, err := parseUserIDParam(chi.URLParam(r, "userID")) |
| 282 | + if err != nil { |
| 283 | + h.d.Render.HTTPError(w, r, http.StatusBadRequest, "") |
| 284 | + return |
| 285 | + } |
| 286 | + if err := action(org.ID, uid); err != nil { |
| 287 | + h.d.Logger.WarnContext(r.Context(), "orgs: member mutation", |
| 288 | + "org", org.Slug, "user_id", uid, "error", err) |
| 289 | + } |
| 290 | + http.Redirect(w, r, "/"+org.Slug+"/people", http.StatusSeeOther) |
| 291 | +} |
| 292 | + |
| 293 | +// ─── invitations ─────────────────────────────────────────────────── |
| 294 | + |
| 295 | +func (h *Handlers) invitationView(w http.ResponseWriter, r *http.Request) { |
| 296 | + tok := chi.URLParam(r, "token") |
| 297 | + inv, err := orgs.LookupInvitationByToken(r.Context(), h.deps(), tok) |
| 298 | + if err != nil { |
| 299 | + h.d.Render.HTTPError(w, r, http.StatusNotFound, "") |
| 300 | + return |
| 301 | + } |
| 302 | + org, err := orgsdb.New().GetOrgByID(r.Context(), h.d.Pool, inv.OrgID) |
| 303 | + if err != nil { |
| 304 | + h.d.Render.HTTPError(w, r, http.StatusNotFound, "") |
| 305 | + return |
| 306 | + } |
| 307 | + _ = h.d.Render.RenderPage(w, r, "orgs/invitation", map[string]any{ |
| 308 | + "Title": "Organization invitation", |
| 309 | + "CSRFToken": middleware.CSRFTokenForRequest(r), |
| 310 | + "Org": org, |
| 311 | + "Invitation": inv, |
| 312 | + "Token": tok, |
| 313 | + }) |
| 314 | +} |
| 315 | + |
| 316 | +func (h *Handlers) invitationAccept(w http.ResponseWriter, r *http.Request) { |
| 317 | + h.invitationAction(w, r, true) |
| 318 | +} |
| 319 | + |
| 320 | +func (h *Handlers) invitationDecline(w http.ResponseWriter, r *http.Request) { |
| 321 | + h.invitationAction(w, r, false) |
| 322 | +} |
| 323 | + |
| 324 | +func (h *Handlers) invitationAction(w http.ResponseWriter, r *http.Request, accept bool) { |
| 325 | + viewer := middleware.CurrentUserFromContext(r.Context()) |
| 326 | + if viewer.IsAnonymous() { |
| 327 | + http.Redirect(w, r, "/login?next="+r.URL.Path, http.StatusSeeOther) |
| 328 | + return |
| 329 | + } |
| 330 | + tok := chi.URLParam(r, "token") |
| 331 | + inv, err := orgs.LookupInvitationByToken(r.Context(), h.deps(), tok) |
| 332 | + if err != nil { |
| 333 | + h.d.Render.HTTPError(w, r, http.StatusNotFound, "") |
| 334 | + return |
| 335 | + } |
| 336 | + if accept { |
| 337 | + if err := orgs.AcceptInvitation(r.Context(), h.deps(), inv, viewer.ID); err != nil { |
| 338 | + h.d.Logger.WarnContext(r.Context(), "orgs: accept invitation", |
| 339 | + "id", inv.ID, "error", err) |
| 340 | + h.d.Render.HTTPError(w, r, http.StatusForbidden, "") |
| 341 | + return |
| 342 | + } |
| 343 | + } else { |
| 344 | + if err := orgs.DeclineInvitation(r.Context(), h.deps(), inv, viewer.ID); err != nil { |
| 345 | + h.d.Logger.WarnContext(r.Context(), "orgs: decline invitation", |
| 346 | + "id", inv.ID, "error", err) |
| 347 | + } |
| 348 | + } |
| 349 | + org, _ := orgsdb.New().GetOrgByID(r.Context(), h.d.Pool, inv.OrgID) |
| 350 | + http.Redirect(w, r, "/"+org.Slug, http.StatusSeeOther) |
| 351 | +} |
| 352 | + |
| 353 | +// friendlyOrgErr maps orchestrator errors to user-facing strings. |
| 354 | +// Unknown errors collapse to a generic message — the underlying err |
| 355 | +// is logged at the call site. |
| 356 | +func friendlyOrgErr(err error) string { |
| 357 | + switch { |
| 358 | + case errors.Is(err, orgs.ErrEmptySlug): |
| 359 | + return "Slug is required." |
| 360 | + case errors.Is(err, orgs.ErrSlugTooLong): |
| 361 | + return "Slug too long (max 39 characters)." |
| 362 | + case errors.Is(err, orgs.ErrSlugInvalid): |
| 363 | + return "Slug must be lowercase letters, digits, or hyphens; cannot start or end with a hyphen." |
| 364 | + case errors.Is(err, orgs.ErrSlugReserved): |
| 365 | + return "That slug is reserved. Try another." |
| 366 | + case errors.Is(err, orgs.ErrSlugTaken): |
| 367 | + return "That slug is already in use. Try another." |
| 368 | + } |
| 369 | + return "Something went wrong creating the organization." |
| 370 | +} |