2021-07-14 15:32:09 +03:00
|
|
|
const {Router} = require('express');
|
|
|
|
const body = require('body-parser');
|
|
|
|
const MagicLink = require('@tryghost/magic-link');
|
2021-12-02 17:46:58 +03:00
|
|
|
const errors = require('@tryghost/errors');
|
|
|
|
const logging = require('@tryghost/logging');
|
2021-07-14 15:32:09 +03:00
|
|
|
|
2021-09-21 14:37:24 +03:00
|
|
|
const MemberAnalyticsService = require('@tryghost/member-analytics-service');
|
2021-09-22 14:21:03 +03:00
|
|
|
const MembersAnalyticsIngress = require('@tryghost/members-analytics-ingress');
|
2021-10-21 14:35:29 +03:00
|
|
|
const PaymentsService = require('@tryghost/members-payments');
|
2021-09-21 14:37:24 +03:00
|
|
|
|
2021-07-15 19:54:24 +03:00
|
|
|
const StripeWebhookService = require('./services/stripe-webhook');
|
|
|
|
const TokenService = require('./services/token');
|
|
|
|
const GeolocationSerice = require('./services/geolocation');
|
2021-08-25 14:30:49 +03:00
|
|
|
const MemberBREADService = require('./services/member-bread');
|
2021-07-15 19:54:24 +03:00
|
|
|
const MemberRepository = require('./repositories/member');
|
|
|
|
const EventRepository = require('./repositories/event');
|
|
|
|
const ProductRepository = require('./repositories/product');
|
|
|
|
const RouterController = require('./controllers/router');
|
|
|
|
const MemberController = require('./controllers/member');
|
2021-07-19 15:02:45 +03:00
|
|
|
const WellKnownController = require('./controllers/well-known');
|
2021-07-15 19:54:24 +03:00
|
|
|
const StripeMigrations = require('./migrations');
|
2021-07-14 15:32:09 +03:00
|
|
|
|
|
|
|
module.exports = function MembersAPI({
|
|
|
|
tokenConfig: {
|
|
|
|
issuer,
|
|
|
|
privateKey,
|
|
|
|
publicKey
|
|
|
|
},
|
|
|
|
auth: {
|
|
|
|
allowSelfSignup = true,
|
|
|
|
getSigninURL,
|
|
|
|
tokenProvider
|
|
|
|
},
|
|
|
|
paymentConfig,
|
|
|
|
mail: {
|
|
|
|
transporter,
|
|
|
|
getText,
|
|
|
|
getHTML,
|
|
|
|
getSubject
|
|
|
|
},
|
|
|
|
models: {
|
|
|
|
StripeWebhook,
|
|
|
|
StripeCustomer,
|
|
|
|
StripeCustomerSubscription,
|
|
|
|
Member,
|
|
|
|
MemberSubscribeEvent,
|
|
|
|
MemberLoginEvent,
|
|
|
|
MemberPaidSubscriptionEvent,
|
|
|
|
MemberPaymentEvent,
|
|
|
|
MemberStatusEvent,
|
2021-08-23 13:00:19 +03:00
|
|
|
MemberProductEvent,
|
2021-07-14 15:32:09 +03:00
|
|
|
MemberEmailChangeEvent,
|
2021-09-21 14:37:24 +03:00
|
|
|
MemberAnalyticEvent,
|
2021-10-20 15:40:34 +03:00
|
|
|
Offer,
|
2021-10-18 16:27:17 +03:00
|
|
|
OfferRedemption,
|
2021-07-14 15:32:09 +03:00
|
|
|
StripeProduct,
|
|
|
|
StripePrice,
|
|
|
|
Product,
|
|
|
|
Settings
|
|
|
|
},
|
2021-10-04 14:34:17 +03:00
|
|
|
stripeAPIService,
|
2021-10-13 12:11:12 +03:00
|
|
|
offersAPI,
|
2021-09-14 14:18:34 +03:00
|
|
|
labsService
|
2021-07-14 15:32:09 +03:00
|
|
|
}) {
|
2021-09-17 12:25:57 +03:00
|
|
|
const tokenService = new TokenService({
|
|
|
|
privateKey,
|
|
|
|
publicKey,
|
|
|
|
issuer
|
|
|
|
});
|
|
|
|
|
2021-07-14 15:32:09 +03:00
|
|
|
const stripeConfig = paymentConfig && paymentConfig.stripe || {};
|
|
|
|
|
2021-09-21 14:37:24 +03:00
|
|
|
const memberAnalyticsService = MemberAnalyticsService.create(MemberAnalyticEvent);
|
|
|
|
memberAnalyticsService.eventHandler.setupSubscribers();
|
|
|
|
|
2021-07-14 15:32:09 +03:00
|
|
|
const stripeMigrations = new StripeMigrations({
|
|
|
|
stripeAPIService,
|
|
|
|
StripeCustomerSubscription,
|
|
|
|
StripeProduct,
|
|
|
|
StripePrice,
|
|
|
|
Product,
|
2021-12-02 17:46:58 +03:00
|
|
|
Settings
|
2021-07-14 15:32:09 +03:00
|
|
|
});
|
|
|
|
|
|
|
|
const productRepository = new ProductRepository({
|
|
|
|
Product,
|
|
|
|
StripeProduct,
|
|
|
|
StripePrice,
|
|
|
|
stripeAPIService
|
|
|
|
});
|
|
|
|
|
|
|
|
const memberRepository = new MemberRepository({
|
|
|
|
stripeAPIService,
|
2021-09-17 12:25:57 +03:00
|
|
|
tokenService,
|
2021-07-14 15:32:09 +03:00
|
|
|
productRepository,
|
|
|
|
Member,
|
|
|
|
MemberSubscribeEvent,
|
|
|
|
MemberPaidSubscriptionEvent,
|
|
|
|
MemberEmailChangeEvent,
|
|
|
|
MemberStatusEvent,
|
2021-08-23 13:00:19 +03:00
|
|
|
MemberProductEvent,
|
2021-10-18 16:27:17 +03:00
|
|
|
OfferRedemption,
|
2021-07-14 15:32:09 +03:00
|
|
|
StripeCustomer,
|
|
|
|
StripeCustomerSubscription
|
|
|
|
});
|
|
|
|
|
|
|
|
const eventRepository = new EventRepository({
|
|
|
|
MemberSubscribeEvent,
|
|
|
|
MemberPaidSubscriptionEvent,
|
|
|
|
MemberPaymentEvent,
|
|
|
|
MemberStatusEvent,
|
|
|
|
MemberLoginEvent
|
|
|
|
});
|
|
|
|
|
2021-08-25 14:30:49 +03:00
|
|
|
const memberBREADService = new MemberBREADService({
|
2021-10-20 15:32:41 +03:00
|
|
|
offersAPI,
|
2021-09-14 14:18:34 +03:00
|
|
|
memberRepository,
|
|
|
|
emailService: {
|
2021-11-02 13:37:07 +03:00
|
|
|
async sendEmailWithMagicLink({email, requestedType}) {
|
|
|
|
return sendEmailWithMagicLink({
|
|
|
|
email,
|
|
|
|
requestedType,
|
|
|
|
options: {
|
|
|
|
forceEmailType: true
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
2021-09-14 14:18:34 +03:00
|
|
|
},
|
|
|
|
labsService,
|
|
|
|
stripeService: stripeAPIService
|
2021-08-25 14:30:49 +03:00
|
|
|
});
|
|
|
|
|
2021-07-14 15:32:09 +03:00
|
|
|
const stripeWebhookService = new StripeWebhookService({
|
|
|
|
StripeWebhook,
|
|
|
|
stripeAPIService,
|
|
|
|
productRepository,
|
|
|
|
memberRepository,
|
|
|
|
eventRepository,
|
2021-12-01 14:00:25 +03:00
|
|
|
/**
|
|
|
|
* @param {string} email
|
|
|
|
*/
|
|
|
|
async sendSignupEmail(email) {
|
2022-01-04 17:50:24 +03:00
|
|
|
const requestedType = 'signup-paid';
|
2021-12-01 14:00:25 +03:00
|
|
|
await sendEmailWithMagicLink({
|
|
|
|
email,
|
|
|
|
requestedType,
|
|
|
|
options: {
|
|
|
|
forceEmailType: true
|
|
|
|
},
|
|
|
|
tokenData: {}
|
|
|
|
});
|
|
|
|
}
|
2021-07-14 15:32:09 +03:00
|
|
|
});
|
|
|
|
|
|
|
|
const geolocationService = new GeolocationSerice();
|
|
|
|
|
|
|
|
const magicLinkService = new MagicLink({
|
|
|
|
transporter,
|
|
|
|
tokenProvider,
|
|
|
|
getSigninURL,
|
|
|
|
getText,
|
|
|
|
getHTML,
|
|
|
|
getSubject
|
|
|
|
});
|
|
|
|
|
|
|
|
const memberController = new MemberController({
|
|
|
|
memberRepository,
|
|
|
|
StripePrice,
|
2021-09-22 14:32:02 +03:00
|
|
|
tokenService,
|
|
|
|
sendEmailWithMagicLink,
|
|
|
|
allowSelfSignup
|
2021-07-14 15:32:09 +03:00
|
|
|
});
|
|
|
|
|
2021-10-21 14:35:29 +03:00
|
|
|
const paymentsService = new PaymentsService({
|
|
|
|
Offer,
|
|
|
|
offersAPI,
|
|
|
|
stripeAPIService
|
|
|
|
});
|
|
|
|
|
2021-07-14 15:32:09 +03:00
|
|
|
const routerController = new RouterController({
|
2021-10-13 12:11:12 +03:00
|
|
|
offersAPI,
|
2021-10-21 14:35:29 +03:00
|
|
|
paymentsService,
|
2021-10-06 16:01:04 +03:00
|
|
|
productRepository,
|
2021-07-14 15:32:09 +03:00
|
|
|
memberRepository,
|
|
|
|
StripePrice,
|
|
|
|
allowSelfSignup,
|
|
|
|
magicLinkService,
|
|
|
|
stripeAPIService,
|
|
|
|
tokenService,
|
|
|
|
sendEmailWithMagicLink,
|
2021-09-28 14:36:30 +03:00
|
|
|
labsService,
|
2021-07-14 15:32:09 +03:00
|
|
|
config: {
|
|
|
|
checkoutSuccessUrl: stripeConfig.checkoutSuccessUrl,
|
|
|
|
checkoutCancelUrl: stripeConfig.checkoutCancelUrl,
|
|
|
|
billingSuccessUrl: stripeConfig.billingSuccessUrl,
|
|
|
|
billingCancelUrl: stripeConfig.billingCancelUrl
|
2021-12-02 17:46:58 +03:00
|
|
|
}
|
2021-07-14 15:32:09 +03:00
|
|
|
});
|
|
|
|
|
2021-07-19 15:02:45 +03:00
|
|
|
const wellKnownController = new WellKnownController({
|
2021-12-02 17:46:58 +03:00
|
|
|
tokenService
|
2021-07-19 15:02:45 +03:00
|
|
|
});
|
|
|
|
|
2021-09-07 17:34:08 +03:00
|
|
|
async function disconnectStripe() {
|
2021-09-07 18:18:23 +03:00
|
|
|
if (stripeConfig && stripeConfig.webhook && stripeConfig.webhook.id) {
|
|
|
|
await stripeWebhookService.removeWebhook(stripeConfig.webhook.id);
|
|
|
|
}
|
|
|
|
|
2021-09-07 17:34:08 +03:00
|
|
|
await Product.forge().query().update({
|
|
|
|
monthly_price_id: null,
|
|
|
|
yearly_price_id: null
|
|
|
|
});
|
|
|
|
await StripePrice.forge().query().del();
|
|
|
|
await StripeProduct.forge().query().del();
|
|
|
|
await StripeCustomer.forge().query().del();
|
2021-10-20 15:40:34 +03:00
|
|
|
await Offer.forge().query().update({
|
|
|
|
stripe_coupon_id: null
|
|
|
|
});
|
2021-09-07 17:34:08 +03:00
|
|
|
}
|
|
|
|
|
2021-10-04 14:34:17 +03:00
|
|
|
const ready = stripeAPIService.configured ? Promise.all([
|
2021-07-14 15:32:09 +03:00
|
|
|
stripeMigrations.populateProductsAndPrices().then(() => {
|
|
|
|
return stripeMigrations.populateStripePricesFromStripePlansSetting(stripeConfig.plans);
|
|
|
|
}).then(() => {
|
|
|
|
return stripeMigrations.populateMembersMonthlyPriceIdSettings();
|
|
|
|
}).then(() => {
|
|
|
|
return stripeMigrations.populateMembersYearlyPriceIdSettings();
|
|
|
|
}).then(() => {
|
|
|
|
return stripeMigrations.populateDefaultProductMonthlyPriceId();
|
|
|
|
}).then(() => {
|
|
|
|
return stripeMigrations.populateDefaultProductYearlyPriceId();
|
|
|
|
}).then(() => {
|
|
|
|
return stripeMigrations.revertPortalPlansSetting();
|
2021-07-14 14:28:04 +03:00
|
|
|
}).then(() => {
|
|
|
|
return stripeMigrations.removeInvalidSubscriptions();
|
2021-07-14 15:32:09 +03:00
|
|
|
}),
|
|
|
|
stripeWebhookService.configure({
|
|
|
|
webhookSecret: process.env.WEBHOOK_SECRET,
|
|
|
|
webhookHandlerUrl: stripeConfig.webhookHandlerUrl,
|
|
|
|
webhook: stripeConfig.webhook || {}
|
|
|
|
})
|
|
|
|
]) : Promise.resolve();
|
|
|
|
|
|
|
|
async function hasActiveStripeSubscriptions() {
|
|
|
|
const firstActiveSubscription = await StripeCustomerSubscription.findOne({
|
|
|
|
status: 'active'
|
|
|
|
});
|
|
|
|
|
|
|
|
if (firstActiveSubscription) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
const firstTrialingSubscription = await StripeCustomerSubscription.findOne({
|
|
|
|
status: 'trialing'
|
|
|
|
});
|
|
|
|
|
|
|
|
if (firstTrialingSubscription) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
const firstUnpaidSubscription = await StripeCustomerSubscription.findOne({
|
|
|
|
status: 'unpaid'
|
|
|
|
});
|
|
|
|
|
|
|
|
if (firstUnpaidSubscription) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
const firstPastDueSubscription = await StripeCustomerSubscription.findOne({
|
|
|
|
status: 'past_due'
|
|
|
|
});
|
|
|
|
|
|
|
|
if (firstPastDueSubscription) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
const users = memberRepository;
|
|
|
|
|
|
|
|
async function sendEmailWithMagicLink({email, requestedType, tokenData, options = {forceEmailType: false}, requestSrc = ''}) {
|
|
|
|
let type = requestedType;
|
|
|
|
if (!options.forceEmailType) {
|
|
|
|
const member = await users.get({email});
|
|
|
|
if (member) {
|
|
|
|
type = 'signin';
|
|
|
|
} else if (type !== 'subscribe') {
|
|
|
|
type = 'signup';
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return magicLinkService.sendMagicLink({email, type, requestSrc, tokenData: Object.assign({email}, tokenData)});
|
|
|
|
}
|
|
|
|
|
|
|
|
function getMagicLink(email) {
|
|
|
|
return magicLinkService.getMagicLink({tokenData: {email}, type: 'signin'});
|
|
|
|
}
|
|
|
|
|
|
|
|
async function getMemberDataFromMagicLinkToken(token) {
|
|
|
|
const {email, labels = [], name = '', oldEmail} = await magicLinkService.getDataFromToken(token);
|
|
|
|
if (!email) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
const member = oldEmail ? await getMemberIdentityData(oldEmail) : await getMemberIdentityData(email);
|
|
|
|
|
|
|
|
if (member) {
|
|
|
|
await MemberLoginEvent.add({member_id: member.id});
|
|
|
|
if (oldEmail) {
|
|
|
|
// user exists but wants to change their email address
|
|
|
|
if (oldEmail) {
|
|
|
|
member.email = email;
|
|
|
|
}
|
|
|
|
await users.update(member, {id: member.id});
|
|
|
|
return getMemberIdentityData(email);
|
|
|
|
}
|
|
|
|
return member;
|
|
|
|
}
|
|
|
|
|
|
|
|
const newMember = await users.create({name, email, labels});
|
|
|
|
await MemberLoginEvent.add({member_id: newMember.id});
|
|
|
|
return getMemberIdentityData(email);
|
|
|
|
}
|
|
|
|
|
|
|
|
async function getMemberIdentityData(email) {
|
2021-08-26 17:07:06 +03:00
|
|
|
return memberBREADService.read({email});
|
2021-07-14 15:32:09 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
async function getMemberIdentityToken(email) {
|
|
|
|
const member = await getMemberIdentityData(email);
|
|
|
|
if (!member) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
return tokenService.encodeIdentityToken({sub: member.email});
|
|
|
|
}
|
|
|
|
|
|
|
|
async function setMemberGeolocationFromIp(email, ip) {
|
|
|
|
if (!email || !ip) {
|
2021-12-02 17:46:58 +03:00
|
|
|
throw new errors.IncorrectUsageError({
|
2021-07-14 15:32:09 +03:00
|
|
|
message: 'setMemberGeolocationFromIp() expects email and ip arguments to be present'
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
// toJSON() is needed here otherwise users.update() will pick methods off
|
|
|
|
// the model object rather than data and fail to edit correctly
|
|
|
|
const member = (await users.get({email})).toJSON();
|
|
|
|
|
|
|
|
if (!member) {
|
2021-12-02 17:46:58 +03:00
|
|
|
throw new errors.NotFoundError({
|
2021-07-14 15:32:09 +03:00
|
|
|
message: `Member with email address ${email} does not exist`
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
// max request time is 500ms so shouldn't slow requests down too much
|
|
|
|
let geolocation = JSON.stringify(await geolocationService.getGeolocationFromIP(ip));
|
|
|
|
if (geolocation) {
|
|
|
|
member.geolocation = geolocation;
|
|
|
|
await users.update(member, {id: member.id});
|
|
|
|
}
|
|
|
|
|
|
|
|
return getMemberIdentityData(email);
|
|
|
|
}
|
|
|
|
|
|
|
|
const middleware = {
|
|
|
|
sendMagicLink: Router().use(
|
|
|
|
body.json(),
|
|
|
|
(req, res) => routerController.sendMagicLink(req, res)
|
|
|
|
),
|
|
|
|
createCheckoutSession: Router().use(
|
|
|
|
body.json(),
|
|
|
|
(req, res) => routerController.createCheckoutSession(req, res)
|
|
|
|
),
|
|
|
|
createCheckoutSetupSession: Router().use(
|
|
|
|
body.json(),
|
|
|
|
(req, res) => routerController.createCheckoutSetupSession(req, res)
|
|
|
|
),
|
2021-09-22 13:37:37 +03:00
|
|
|
createEvents: Router().use(
|
|
|
|
body.json(),
|
2021-09-22 14:21:03 +03:00
|
|
|
(req, res) => MembersAnalyticsIngress.createEvents(req, res)
|
2021-09-22 13:37:37 +03:00
|
|
|
),
|
2021-09-22 14:32:02 +03:00
|
|
|
updateEmailAddress: Router().use(
|
|
|
|
body.json(),
|
|
|
|
(req, res) => memberController.updateEmailAddress(req, res)
|
|
|
|
),
|
2021-07-14 15:32:09 +03:00
|
|
|
updateSubscription: Router({mergeParams: true}).use(
|
|
|
|
body.json(),
|
|
|
|
(req, res) => memberController.updateSubscription(req, res)
|
|
|
|
),
|
2021-07-19 15:02:45 +03:00
|
|
|
handleStripeWebhook: Router(),
|
|
|
|
wellKnown: Router()
|
|
|
|
.get('/jwks.json',
|
|
|
|
(req, res) => wellKnownController.getPublicKeys(req, res)
|
|
|
|
)
|
2021-07-14 15:32:09 +03:00
|
|
|
};
|
|
|
|
|
|
|
|
middleware.handleStripeWebhook.use(body.raw({type: 'application/json'}), async function (req, res) {
|
2021-09-08 13:27:09 +03:00
|
|
|
if (!stripeAPIService.configured) {
|
2021-12-02 17:46:58 +03:00
|
|
|
logging.error(`Stripe not configured, not handling webhook`);
|
2021-07-14 15:32:09 +03:00
|
|
|
res.writeHead(400);
|
|
|
|
return res.end();
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!req.body || !req.headers['stripe-signature']) {
|
|
|
|
res.writeHead(400);
|
|
|
|
return res.end();
|
|
|
|
}
|
|
|
|
let event;
|
|
|
|
try {
|
|
|
|
event = stripeWebhookService.parseWebhook(req.body, req.headers['stripe-signature']);
|
|
|
|
} catch (err) {
|
2021-12-02 17:46:58 +03:00
|
|
|
logging.error(err);
|
2021-07-14 15:32:09 +03:00
|
|
|
res.writeHead(401);
|
|
|
|
return res.end();
|
|
|
|
}
|
2021-12-02 17:46:58 +03:00
|
|
|
logging.info(`Handling webhook ${event.type}`);
|
2021-07-14 15:32:09 +03:00
|
|
|
try {
|
|
|
|
await stripeWebhookService.handleWebhook(event);
|
|
|
|
res.writeHead(200);
|
|
|
|
res.end();
|
|
|
|
} catch (err) {
|
2021-12-02 17:46:58 +03:00
|
|
|
logging.error(`Error handling webhook ${event.type}`, err);
|
2021-07-14 15:32:09 +03:00
|
|
|
res.writeHead(err.statusCode || 500);
|
|
|
|
res.end();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
const getPublicConfig = function () {
|
|
|
|
return Promise.resolve({
|
|
|
|
publicKey,
|
|
|
|
issuer
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
const bus = new (require('events').EventEmitter)();
|
|
|
|
|
|
|
|
ready.then(() => {
|
|
|
|
bus.emit('ready');
|
|
|
|
}).catch((err) => {
|
|
|
|
bus.emit('error', err);
|
|
|
|
});
|
|
|
|
|
|
|
|
return {
|
|
|
|
middleware,
|
|
|
|
getMemberDataFromMagicLinkToken,
|
|
|
|
getMemberIdentityToken,
|
|
|
|
getMemberIdentityData,
|
|
|
|
setMemberGeolocationFromIp,
|
2021-09-07 17:34:08 +03:00
|
|
|
disconnectStripe,
|
2021-07-14 15:32:09 +03:00
|
|
|
getPublicConfig,
|
|
|
|
bus,
|
|
|
|
sendEmailWithMagicLink,
|
|
|
|
getMagicLink,
|
|
|
|
hasActiveStripeSubscriptions,
|
|
|
|
members: users,
|
2021-08-25 14:30:49 +03:00
|
|
|
memberBREADService,
|
2021-07-14 15:32:09 +03:00
|
|
|
events: eventRepository,
|
|
|
|
productRepository
|
|
|
|
};
|
|
|
|
};
|