Make it possible to create a user without payment details.
We want a new subscription flow, in which the system (not the user) is
responsible for creating a subscription when a new profile is created. This is
to prevent issues where a user has an account, but no subscription. This is bad
because the free trial starts ticking from the day the subscription is created,
so we should try to make the subscription and account creation get created as
close to each other as possible.
Our plan is to instead have the authd service fire off an NSQ event when an
auth.Profile is created, which a subscription listener will be listening for.
When that happens, the listener will use the subscription API to create a
subscription. Then the user will update the subscription with their payment info
and the plan they want to use.
To accomplish this, we changed the way things were handled. The
SubscriptionRequest type, along with its Validate method, were removed. Instead,
we get the SubscriptionChange type which handles both the creation of a
subscription and the updating of a subscription.
We also added an endpoint for patching subscriptions, useful for adding the
StripeSubscription or updating the plan. By default, every subscription is
created with a "Pending" plan which has a 31 day free trial. This is so we can
detect users that haven't actually set up their subscription yet, but their free
trial is still timed correctly.
We changed the way we handle scopes, creating actual auth.Scope instances
instead of just declaring an ID for them. This is useful when we have a client,
for example.
With this change, we lose all the validation we had on creating a Subscription,
and we need to rewrite that validation logic. This is because we no longer have
a specific type for "creating a subscription", so we can't just call a validate
method. We should have a helper method validateCreateRequest(change
SubscriptionChange) that will return the API errors we want, so it's easier to
unit test.
We should really be restricting the CreateSubscriptionHandler to
ScopeSubscriptionAdmin, anyways, since Subscriptions should only ever be created
by the system tools or administrators.
We created a PatchSubscriptionHandler that exposes an interface to updating
properties of a Subscription. It allows users to update their own Subscriptions
or requires the ScopeSubscriptionAdmin scope before allowing you to update
another user's Subscription. It, likewise, needs validation still. We also added
the concept of "system-controlled properties" of the SubscriptionChange type,
which only admins or the system tools can update.
We updated our planOptions to distinguish between plans that do and do not need
administrative credentials to be chosen. Our free and pending plans are
available to administrators only.
We updated our StripeChange object to be better organised (separating out the
system and user-controlled properties), and we added a StripeSource and Email
property, so the Stripe part can be better managed, and all our requests can be
made using just this type. This required updating our SubscriptionChange.IsEmpty
helper, which has been updated (along with its tests) and it passes all tests.
To replace our SubscriptionRequest.Validate helper, we created a
ChangingSystemProperties helper (which returns the system-controlled properties
being changed as a slice of JSON pointers, fit for use in error messages) and an
IsAcceptablePlan helper, which returns true if the plan exists and the user has
the authority to select it.
We also updated our stripe helpers to remove the CreateStripeSubscription (we
create one when we create the customer) and create an UpdateStripeSubscription
instead. It does what you'd think it does. We also added some comments to New,
so it at least has some notes about how it's meant to be used and why. Now it
just creates the customer in stripe, then creates a Subscription based on that
customer. We also updated our StripeSubscriptionChange helper to detect when the
StripeSubscription property changed.
6 "code.secondbit.org/api.hg"
7 "code.secondbit.org/auth.hg"
8 "code.secondbit.org/trout.hg"
9 "code.secondbit.org/uuid.hg"
11 "code.secondbit.org/ducky/subscriptions.hg"
13 "golang.org/x/net/context"
17 ScopeSubscription = auth.Scope{ID: "subscriptions", Name: "Manage Subscriptions", Description: "Read and update your subscription information."}
18 ScopeSubscriptionAdmin = auth.Scope{ID: "subscriptions_admin", Name: "Administer Subscriptions", Description: "Read and update subscription information, bypassing ACL."}
21 func HandleSubscriptions(router *trout.Router, c context.Context) {
22 router.Endpoint("/subscriptions").Methods("POST", "OPTIONS").Handler(
23 api.CORSMiddleware(api.NegotiateMiddleware(api.ContextWrapper(c, CreateSubscriptionHandler))))
24 router.Endpoint("/subscriptions/{id}").Methods("GET", "OPTIONS").Handler(
25 api.CORSMiddleware(api.NegotiateMiddleware(api.ContextWrapper(c, GetSubscriptionHandler))))
26 router.Endpoint("/subscriptions/{id}").Methods("PATCH", "OPTIONS").Handler(
27 api.CORSMiddleware(api.NegotiateMiddleware(api.ContextWrapper(c, PatchSubscriptionHandler))))
30 func CreateSubscriptionHandler(w http.ResponseWriter, r *http.Request, c context.Context) {
31 store, err := getSubscriptionStore(c)
33 api.Encode(w, r, http.StatusInternalServerError, Response{Errors: api.ActOfGodError})
36 stripe, err := getStripeClient(c)
38 api.Encode(w, r, http.StatusInternalServerError, Response{Errors: api.ActOfGodError})
41 if !api.CheckScopes(r, ScopeSubscriptionAdmin.ID) {
42 api.Encode(w, r, http.StatusUnauthorized, Response{Errors: []api.RequestError{{Slug: api.RequestErrAccessDenied}}})
45 var req subscriptions.SubscriptionChange
46 err = api.Decode(r, &req)
48 api.Encode(w, r, http.StatusBadRequest, Response{Errors: api.InvalidFormatError})
51 // BUG(paddy): Need to validate the request when creating a subscription
52 sub, err := subscriptions.New(req, stripe, store)
54 var rErr api.RequestError
57 case subscriptions.ErrSubscriptionAlreadyExists:
58 rErr = api.RequestError{Slug: api.RequestErrConflict, Field: "/user_id"}
59 code = http.StatusBadRequest
60 case subscriptions.ErrStripeSubscriptionAlreadyExists:
61 rErr = api.RequestError{Slug: api.RequestErrConflict, Field: "/stripe_token"}
62 code = http.StatusBadRequest
64 rErr = api.RequestError{Slug: api.RequestErrActOfGod}
65 code = http.StatusInternalServerError
67 api.Encode(w, r, code, Response{Errors: []api.RequestError{rErr}})
70 resp := Response{Subscriptions: []subscriptions.Subscription{sub}}
71 api.Encode(w, r, http.StatusCreated, resp)
74 func GetSubscriptionHandler(w http.ResponseWriter, r *http.Request, c context.Context) {
75 store, err := getSubscriptionStore(c)
77 api.Encode(w, r, http.StatusInternalServerError, Response{Errors: api.ActOfGodError})
80 vars := trout.RequestVars(r)
81 rawID := vars.Get("id")
83 api.Encode(w, r, http.StatusBadRequest, Response{Errors: []api.RequestError{{Slug: api.RequestErrMissing, Param: "id"}}})
86 id, err := uuid.Parse(rawID)
88 api.Encode(w, r, http.StatusBadRequest, Response{Errors: []api.RequestError{{Slug: api.RequestErrInvalidFormat, Param: "id"}}})
91 if !api.CheckScopes(r, ScopeSubscription.ID) {
92 api.Encode(w, r, http.StatusUnauthorized, Response{Errors: []api.RequestError{{Slug: api.RequestErrAccessDenied}}})
95 userID, err := api.AuthUser(r)
97 api.Encode(w, r, http.StatusUnauthorized, Response{Errors: []api.RequestError{{Slug: api.RequestErrAccessDenied}}})
100 if !id.Equal(userID) && !api.CheckScopes(r, ScopeSubscriptionAdmin.ID) {
101 api.Encode(w, r, http.StatusUnauthorized, Response{Errors: []api.RequestError{{Slug: api.RequestErrAccessDenied}}})
104 subs, err := store.GetSubscriptions([]uuid.ID{id})
106 api.Encode(w, r, http.StatusInternalServerError, Response{Errors: api.ActOfGodError})
109 sub, ok := subs[id.String()]
111 api.Encode(w, r, http.StatusNotFound, Response{Errors: []api.RequestError{{Slug: api.RequestErrNotFound, Param: "id"}}})
114 resp := Response{Subscriptions: []subscriptions.Subscription{sub}}
115 api.Encode(w, r, http.StatusOK, resp)
118 func PatchSubscriptionHandler(w http.ResponseWriter, r *http.Request, c context.Context) {
119 store, err := getSubscriptionStore(c)
121 api.Encode(w, r, http.StatusInternalServerError, Response{Errors: api.ActOfGodError})
124 stripe, err := getStripeClient(c)
126 api.Encode(w, r, http.StatusInternalServerError, Response{Errors: api.ActOfGodError})
129 if !api.CheckScopes(r, ScopeSubscription.ID) {
130 api.Encode(w, r, http.StatusUnauthorized, Response{Errors: []api.RequestError{{Slug: api.RequestErrAccessDenied}}})
133 userID, err := api.AuthUser(r)
135 api.Encode(w, r, http.StatusUnauthorized, Response{Errors: []api.RequestError{{Slug: api.RequestErrAccessDenied}}})
138 vars := trout.RequestVars(r)
139 rawID := vars.Get("id")
141 api.Encode(w, r, http.StatusBadRequest, Response{Errors: []api.RequestError{{Slug: api.RequestErrMissing, Param: "id"}}})
144 id, err := uuid.Parse(rawID)
146 api.Encode(w, r, http.StatusBadRequest, Response{Errors: []api.RequestError{{Slug: api.RequestErrInvalidFormat, Param: "id"}}})
150 var req subscriptions.SubscriptionChange
151 err = api.Decode(r, &req)
153 api.Encode(w, r, http.StatusBadRequest, Response{Errors: api.InvalidFormatError})
156 // BUG(paddy): Need to validate the request when updating a subscription
158 // only admin users can update the system-controlled properties
159 changedSysProps := subscriptions.ChangingSystemProperties(req)
160 if len(changedSysProps) > 0 && !api.CheckScopes(r, ScopeSubscriptionAdmin.ID) {
161 errs := make([]api.RequestError, len(changedSysProps))
162 for pos, prop := range changedSysProps {
163 errs[pos] = api.RequestError{Slug: api.RequestErrAccessDenied, Field: prop}
165 api.Encode(w, r, http.StatusBadRequest, Response{Errors: errs})
169 subs, err := store.GetSubscriptions([]uuid.ID{userID})
171 api.Encode(w, r, http.StatusInternalServerError, Response{Errors: api.ActOfGodError})
174 sub, ok := subs[userID.String()]
176 api.Encode(w, r, http.StatusNotFound, Response{Errors: []api.RequestError{{Slug: api.RequestErrNotFound, Param: "id"}}})
179 stripeSub, err := subscriptions.UpdateStripeSubscription(sub.StripeSubscription, req.Plan, req.StripeSource, stripe)
181 api.Encode(w, r, http.StatusInternalServerError, Response{Errors: api.ActOfGodError})
184 change := subscriptions.StripeSubscriptionChange(sub, *stripeSub)
185 if change.IsEmpty() {
186 resp := Response{Subscriptions: []subscriptions.Subscription{sub}}
187 api.Encode(w, r, http.StatusOK, resp)
190 err = store.UpdateSubscription(id, change)
192 api.Encode(w, r, http.StatusInternalServerError, Response{Errors: api.ActOfGodError})
195 sub.ApplyChange(change)
196 resp := Response{Subscriptions: []subscriptions.Subscription{sub}}
197 api.Encode(w, r, http.StatusOK, resp)