oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1package docs
2
3import (
4 "errors"
5 "net/http"
6
7 "amadan.net/rastrillo/rastrillo"
8 "gorm.io/gorm"
9)
10
11// sharePage is the share screen's view data, resolved in the handler rather
12// than in the template, as every other page here does it.
13type sharePage struct {
14 Frame Frame
15 Title string
16 DocTitle string
17 Sqid string
18 Heading string
19 AddressLabel string
20 RoleLabel string
21 RoleReader string
22 RoleWriter string
23 ShareButton string
24 RevokeButton string
25 BackLabel string
26 EmptyBody string
27 Error string
28 Grants []shareRow
29 SignOutLabel string
30
31 // The public link, the third rung of ruling 15. PublicURL is empty
32 // when the document is not published, and that emptiness is the
33 // switch's state — one field rather than a bool beside a string that
34 // could disagree with it.
35 PublicHeading string
36 PublicBody string
37
38 // Published is whether a link exists; PublicURL is the link itself and
39 // is set only in the render immediately after publishing.
40 //
41 // Two fields rather than one because they are two different facts now:
42 // under ruling 16 the app knows a document is published without being
43 // able to say what its URL is. Collapsing them would make "published"
44 // unrepresentable whenever the URL is unavailable — which is almost
45 // always.
46 Published bool
47 PublicURL string
48 PublishButton string
49 UnpublishBtn string
50 ReplaceButton string
51 CopyHint string
52 OnceWarning string
53 PublishedBody string
54
55 // The role picker's option cards (rastrillo's choice-field), the
56 // one-time link's accessible name, and the Copy button with the
57 // status it announces (fixtures/share-link.mjs).
58 RoleChoices []roleChoice
59 URLLabel string
60 CopyButton string
61 CopiedLabel string
62 ShareScript string
63
64 // The team rung (spec §8.2.1). Team is the switch's state, and TeamBody
65 // says it in words; the one form posts the other direction.
66 Team bool
67 TeamHeading string
68 TeamBody string
69 TeamButton string
70 TeamDestination Visibility
71
72 // The popover's panel (share_panel.go): who is signed in, for the
73 // owner's row, its own labels, and the grants as the panel draws them.
74 Me string
75 MeInitial string
76 Panel sharePanelLabels
77 PanelGrants []sharePanelGrant
78}
79
80// roleChoice is one option card: rastrillo's choice-field reads Value,
81// Title, Desc and Checked.
82type roleChoice struct {
83 Value, Title, Desc string
84 Checked bool
85}
86
87// shareRow is one person who reaches this document.
88type shareRow struct {
89 Address string
90 Role string
91}
92
93// shareGet serves GET /d/{sqid}/share: who reaches this document, and the
94// form that adds somebody.
95//
96// Owner-only, through Store.ListGrants, which goes through the owner-scoped
97// Get. A grantee — even a writer — gets the 404 a stranger gets: re-sharing
98// is not something a grant carries, and a document you may not share does not
99// announce itself as one you may not share (spec §4.2).
100func (h *handlers) shareGet(w http.ResponseWriter, r *http.Request) {
101 owner, err := h.owner(r)
102 if err != nil {
103 h.logger.Error("docs: resolve owner for share", "err", err)
104 h.fail(w, r, h.internalFailureStatus(), failStatus)
105 return
106 }
107 sqid := r.PathValue("sqid")
108
109 doc, err := h.store.Get(r.Context(), owner, sqid)
110 if err != nil {
111 h.ownerLookupFailure(w, r, err)
112 return
113 }
114 grants, err := h.store.ListGrants(r.Context(), owner, sqid)
115 if err != nil {
116 h.logger.Error("docs: list grants", "sqid", sqid, "err", err)
117 h.fail(w, r, h.internalFailureStatus(), failStatus)
118 return
119 }
120
121 h.renderShare(w, r, doc, grants, "", http.StatusOK)
122}
123
124func (h *handlers) renderShare(w http.ResponseWriter, r *http.Request, doc *Document, grants []*Grant, errKey string, status int) {
125 // A failure to read the published state is logged and then rendered as
126 // "not published" rather than failing the page: the grant list above it
127 // is the part somebody came here for, and a 500 over the switch would
128 // take the working half of the screen down with it.
129 published, err := h.store.IsPublished(r.Context(), doc.OwnerID, doc.Sqid)
130 if err != nil {
131 h.logger.Error("docs: read published state", "sqid", doc.Sqid, "err", err)
132 if wantsNative(r) {
133 h.fail(w, r, http.StatusServiceUnavailable, failStatus)
134 return
135 }
136 if h.store.team != nil {
137 h.ownerLookupFailure(w, r, err)
138 return
139 }
140 }
141
142 // The URL appears only in the render that follows the publish that
143 // minted it (ruling 16: the database holds a hash and cannot produce a
144 // URL). Collected here, once; a reload shows the published state
145 // without it, exactly as a visit tomorrow would.
146 publicURL := h.oneShots.take(oneShotKey(doc.OwnerID, doc.Sqid))
147
148 if wantsNative(r) {
149 type grant struct {
150 Address string `json:"address"`
151 Role Role `json:"role"`
152 }
153 rows := make([]grant, 0, len(grants))
154 for _, g := range grants {
155 rows = append(rows, grant{g.Subject, g.Role})
156 }
157 nativeJSON(w, r, status, map[string]any{"sqid": doc.Sqid, "title": doc.Title, "grants": rows, "published": published, "public_url": publicURL, "visibility": doc.Visibility, "error": errKey})
158 return
159 }
160 rows := make([]shareRow, 0, len(grants))
161 for _, g := range grants {
162 label := "docs.share.role.reader"
163 if g.Role == RoleWriter {
164 label = "docs.share.role.writer"
165 }
166 rows = append(rows, shareRow{Address: g.Subject, Role: rastrillo.T(r, label)})
167 }
168
169 page := sharePage{
170 Title: rastrillo.T(r, "docs.share.title"),
171 DocTitle: doc.Title,
172 Sqid: doc.Sqid,
173 Heading: rastrillo.T(r, "docs.share.heading"),
174 AddressLabel: rastrillo.T(r, "docs.share.address"),
175 RoleLabel: rastrillo.T(r, "docs.share.role"),
176 RoleReader: rastrillo.T(r, "docs.share.role.reader"),
177 RoleWriter: rastrillo.T(r, "docs.share.role.writer"),
178 ShareButton: rastrillo.T(r, "docs.share.submit"),
179 RevokeButton: rastrillo.T(r, "docs.share.revoke"),
180 BackLabel: rastrillo.T(r, "docs.share.back"),
181 EmptyBody: rastrillo.T(r, "docs.share.empty"),
182 Grants: rows,
183 SignOutLabel: rastrillo.T(r, "docs.signout.label"),
184
185 PublicHeading: rastrillo.T(r, "docs.share.public.heading"),
186 PublicBody: rastrillo.T(r, "docs.share.public.body"),
187 Published: published,
188 PublicURL: publicURL,
189 PublishButton: rastrillo.T(r, "docs.share.public.on"),
190 UnpublishBtn: rastrillo.T(r, "docs.share.public.off"),
191 ReplaceButton: rastrillo.T(r, "docs.share.public.replace"),
192 CopyHint: rastrillo.T(r, "docs.share.public.hint"),
193 OnceWarning: rastrillo.T(r, "docs.share.public.once"),
194 PublishedBody: rastrillo.T(r, "docs.share.public.published"),
195
196 RoleChoices: []roleChoice{
197 {Value: "reader", Title: rastrillo.T(r, "docs.share.role.reader"), Checked: true},
198 {Value: "writer", Title: rastrillo.T(r, "docs.share.role.writer")},
199 },
200 URLLabel: rastrillo.T(r, "docs.share.public.url"),
201 CopyButton: rastrillo.T(r, "docs.share.public.copy"),
202 CopiedLabel: rastrillo.T(r, "docs.share.public.copied"),
203 ShareScript: shareScriptPath(),
204 }
205 page.Team = doc.Visibility == VisibilityTeam
206 page.TeamHeading = rastrillo.T(r, "docs.share.team.heading")
207 if page.Team {
208 page.EmptyBody = rastrillo.T(r, "docs.share.empty.team")
209 page.TeamBody = rastrillo.T(r, "docs.share.team.body.team")
210 page.TeamButton = rastrillo.T(r, "docs.share.team.make_private")
211 page.TeamDestination = VisibilityPrivate
212 } else if published {
213 page.TeamBody = rastrillo.T(r, "docs.share.team.body.private_published")
214 page.TeamButton = rastrillo.T(r, "docs.share.team.make_team")
215 page.TeamDestination = VisibilityTeam
216 } else {
217 page.TeamBody = rastrillo.T(r, "docs.share.team.body.private")
218 page.TeamButton = rastrillo.T(r, "docs.share.team.make_team")
219 page.TeamDestination = VisibilityTeam
220 }
221 if errKey != "" {
222 page.Error = rastrillo.T(r, errKey)
223 }
224 // "Share · {document} · Docs"; the bar names the document, read-only.
225 page.Frame = h.frame(r, frameOptions{titleParts: []string{page.Title, doc.Title}, context: doc.Title})
226
227 // no-store whenever this render carries the plaintext capability.
228 // "Shown once" was a server-side truth only: the browser's disk cache
229 // and bfcache would keep the URL, and any intermediary might, so on a
230 // shared machine the next person could page back to it.
231 // (Re-review, finding 5.)
232 if page.PublicURL != "" {
233 w.Header().Set("Cache-Control", "no-store")
234 }
235 // The same URL answers a page or the popover's panel, by who asks.
236 w.Header().Add("Vary", "Sec-Fetch-Dest")
237 if sharePanelRequest(r) {
238 h.panelData(r, &page, grants)
239 if err := h.render.fragmentStatus(w, r, "share", "docs-share-panel", page, status); err != nil {
240 h.logger.Error("docs: render share panel", "sqid", doc.Sqid, "err", err)
241 h.fail(w, r, h.internalFailureStatus(), failStatus)
242 }
243 return
244 }
245 if err := h.render.pageStatus(w, r, "share", page, status); err != nil {
246 h.logger.Error("docs: render share", "sqid", doc.Sqid, "err", err)
247 h.fail(w, r, h.internalFailureStatus(), failStatus)
248 }
249}
250
251// sharePost serves POST /d/{sqid}/share: grant an address access.
252//
253// Scriptless: a plain form with a named address field and a role radio, and a
254// 303 back to this page afterwards so a reload does not re-post.
255func (h *handlers) sharePost(w http.ResponseWriter, r *http.Request) {
256 // Member-only, on top of the owner check below: changing who reaches
257 // a document is a member power. A guest owns no documents (create is
258 // closed to them), so this is belt and braces — and it is the brace
259 // that holds if a guest ever acquires one.
260 if !h.requireMemberRequest(w, r, true) {
261 return
262 }
263 owner, err := h.owner(r)
264 if err != nil {
265 h.logger.Error("docs: resolve owner for share", "err", err)
266 h.fail(w, r, h.internalFailureStatus(), failStatus)
267 return
268 }
269 sqid := r.PathValue("sqid")
270
271 doc, err := h.store.Get(r.Context(), owner, sqid)
272 if err != nil {
273 h.ownerLookupFailure(w, r, err)
274 return
275 }
276
277 role := RoleReader
278 if r.PostFormValue("role") == string(RoleWriter) {
279 role = RoleWriter
280 }
281
282 err = h.store.Grant(r.Context(), owner, sqid, r.PostFormValue("address"), role)
283 switch {
284 case err == nil:
285 if wantsNative(r) {
286 nativeJSON(w, r, 200, map[string]bool{"ok": true})
287 return
288 }
289 http.Redirect(w, r, shareBack(r, sqid), http.StatusSeeOther)
290 case errors.Is(err, errEmptyAddress):
291 // Re-render with the message rather than redirecting, so the person
292 // sees what was wrong beside the field they typed it into.
293 grants, listErr := h.store.ListGrants(r.Context(), owner, sqid)
294 if listErr != nil {
295 h.logger.Error("docs: list grants after refusal", "sqid", sqid, "err", listErr)
296 h.fail(w, r, h.internalFailureStatus(), failStatus)
297 return
298 }
299 h.renderShare(w, r, doc, grants, "docs.share.error.address", http.StatusBadRequest)
300 default:
301 h.logger.Error("docs: grant", "sqid", sqid, "err", err)
302 h.fail(w, r, h.internalFailureStatus(), failStatus)
303 }
304}
305
306// shareRevoke serves POST /d/{sqid}/share/revoke.
307func (h *handlers) shareRevoke(w http.ResponseWriter, r *http.Request) {
308 // Member-only, on top of the owner check below: changing who reaches
309 // a document is a member power. A guest owns no documents (create is
310 // closed to them), so this is belt and braces — and it is the brace
311 // that holds if a guest ever acquires one.
312 if !h.requireMemberRequest(w, r, true) {
313 return
314 }
315 owner, err := h.owner(r)
316 if err != nil {
317 h.logger.Error("docs: resolve owner for revoke", "err", err)
318 h.fail(w, r, h.internalFailureStatus(), failStatus)
319 return
320 }
321 sqid := r.PathValue("sqid")
322
323 if _, err := h.store.Get(r.Context(), owner, sqid); err != nil {
324 h.ownerLookupFailure(w, r, err)
325 return
326 }
327 if err := h.store.Revoke(r.Context(), owner, sqid, r.PostFormValue("address")); err != nil {
328 h.logger.Error("docs: revoke", "sqid", sqid, "err", err)
329 h.fail(w, r, h.internalFailureStatus(), failStatus)
330 return
331 }
332 if wantsNative(r) {
333 nativeJSON(w, r, 200, map[string]bool{"ok": true})
334 return
335 }
336 http.Redirect(w, r, shareBack(r, sqid), http.StatusSeeOther)
337}
338
339func (h *handlers) ownerLookupFailure(w http.ResponseWriter, r *http.Request, err error) {
340 if h.store.team != nil && errors.Is(err, errTeamUnavailable) {
341 h.fail(w, r, http.StatusServiceUnavailable, failStatus)
342 return
343 }
344 h.fail(w, r, http.StatusNotFound, failDocument)
345}
346
347// shareTeam serves POST /d/{sqid}/share/team: move a document between the
348// private and team rungs (spec §8.2.1). Owner- and member-only, exactly as
349// granting is, and answering 404 to anybody else. Scriptless: the direction
350// rides a hidden field, so a page left open cannot flip the switch the
351// wrong way from a stale label, and a 303 comes back here.
352func (h *handlers) shareTeam(w http.ResponseWriter, r *http.Request) {
353 if !h.requireMemberRequest(w, r, true) {
354 return
355 }
356 owner, err := h.owner(r)
357 if err != nil {
358 h.logger.Error("docs: resolve owner for visibility", "err", err)
359 h.fail(w, r, h.internalFailureStatus(), failStatus)
360 return
361 }
362 sqid := r.PathValue("sqid")
363 err = h.store.SetVisibility(r.Context(), owner, sqid, Visibility(r.PostFormValue("visibility")))
364 switch {
365 case err == nil:
366 if wantsNative(r) {
367 nativeJSON(w, r, 200, map[string]bool{"ok": true})
368 return
369 }
370 http.Redirect(w, r, shareBack(r, sqid), http.StatusSeeOther)
371 case errors.Is(err, errUnknownVisibility):
372 h.fail(w, r, http.StatusBadRequest, failStatus)
373 default:
374 h.ownerLookupFailureOrStatus(w, r, err)
375 }
376}
377
378// ownerLookupFailureOrStatus is ownerLookupFailure for an error that may also
379// be a storage failure: not-found and team-unavailable answer as a lookup
380// does, and anything else is logged and is the internal failure status.
381func (h *handlers) ownerLookupFailureOrStatus(w http.ResponseWriter, r *http.Request, err error) {
382 if errors.Is(err, gorm.ErrRecordNotFound) || errors.Is(err, errTeamUnavailable) {
383 h.ownerLookupFailure(w, r, err)
384 return
385 }
386 h.logger.Error("docs: owner mutation failed", "path", r.URL.Path, "sqid", r.PathValue("sqid"), "err", err)
387 h.fail(w, r, h.internalFailureStatus(), failStatus)
388}
389