2021-07-14 15:32:09 +03:00
|
|
|
const {Router} = require('express');
|
|
|
|
const body = require('body-parser');
|
|
|
|
const MagicLink = require('@tryghost/magic-link');
|
2021-07-15 19:54:24 +03:00
|
|
|
const common = require('./common');
|
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-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-07-14 15:32:09 +03:00
|
|
|
StripeProduct,
|
|
|
|
StripePrice,
|
|
|
|
Product,
|
|
|
|
Settings
|
|
|
|
},
|
2021-10-04 14:34:17 +03:00
|
|
|
stripeAPIService,
|
2021-10-06 16:01:04 +03:00
|
|
|
offerRepository,
|
2021-09-14 14:18:34 +03:00
|
|
|
logger,
|
|
|
|
labsService
|
2021-07-14 15:32:09 +03:00
|
|
|
}) {
|
|
|
|
if (logger) {
|
|
|
|
common.logging.setLogger(logger);
|
|
|
|
}
|
|
|
|
|
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,
|
|
|
|
Settings,
|
|
|
|
logger
|
|
|
|
});
|
|
|
|
|
|
|
|
const productRepository = new ProductRepository({
|
|
|
|
Product,
|
|
|
|
StripeProduct,
|
|
|
|
StripePrice,
|
|
|
|
stripeAPIService
|
|
|
|
});
|
|
|
|
|
|
|
|
const memberRepository = new MemberRepository({
|
|
|
|
stripeAPIService,
|
|
|
|
logger,
|
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-07-14 15:32:09 +03:00
|
|
|
StripeCustomer,
|
|
|
|
StripeCustomerSubscription
|
|
|
|
});
|
|
|
|
|
|
|
|
const eventRepository = new EventRepository({
|
|
|
|
logger,
|
|
|
|
MemberSubscribeEvent,
|
|
|
|
MemberPaidSubscriptionEvent,
|
|
|
|
MemberPaymentEvent,
|
|
|
|
MemberStatusEvent,
|
|
|
|
MemberLoginEvent
|
|
|
|
});
|
|
|
|
|
2021-08-25 14:30:49 +03:00
|
|
|
const memberBREADService = new MemberBREADService({
|
2021-09-14 14:18:34 +03:00
|
|
|
memberRepository,
|
|
|
|
emailService: {
|
|
|
|
sendEmailWithMagicLink
|
|
|
|
},
|
|
|
|
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,
|
|
|
|
sendEmailWithMagicLink
|
|
|
|
});
|
|
|
|
|
|
|
|
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
|
|
|
});
|
|
|
|
|
|
|
|
const routerController = new RouterController({
|
2021-10-06 16:01:04 +03:00
|
|
|
offerRepository,
|
|
|
|
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
|
|
|
|
},
|
|
|
|
logging: common.logging
|
|
|
|
});
|
|
|
|
|
2021-07-19 15:02:45 +03:00
|
|
|
const wellKnownController = new WellKnownController({
|
|
|
|
tokenService,
|
|
|
|
logging: common.logging
|
|
|
|
});
|
|
|
|
|
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-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) {
|
|
|
|
throw new common.errors.IncorrectUsageError({
|
|
|
|
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) {
|
|
|
|
throw new common.errors.NotFoundError({
|
|
|
|
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-07-14 15:32:09 +03:00
|
|
|
common.logging.error(`Stripe not configured, not handling webhook`);
|
|
|
|
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) {
|
|
|
|
common.logging.error(err);
|
|
|
|
res.writeHead(401);
|
|
|
|
return res.end();
|
|
|
|
}
|
|
|
|
common.logging.info(`Handling webhook ${event.type}`);
|
|
|
|
try {
|
|
|
|
await stripeWebhookService.handleWebhook(event);
|
|
|
|
res.writeHead(200);
|
|
|
|
res.end();
|
|
|
|
} catch (err) {
|
|
|
|
common.logging.error(`Error handling webhook ${event.type}`, err);
|
|
|
|
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
|
|
|
|
};
|
|
|
|
};
|