Skip to content

Commit

Permalink
Merge branch 'master' of github.com:supertokens/blog into blog/expres…
Browse files Browse the repository at this point in the history
…s-session-vs-supertokens
  • Loading branch information
Chakravarthy7102 committed Oct 5, 2023
2 parents b952839 + ac22b9e commit 2a772bb
Show file tree
Hide file tree
Showing 39 changed files with 888 additions and 22 deletions.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
284 changes: 284 additions & 0 deletions content/all-you-need-to-know-about-user-session-security/index.md

Large diffs are not rendered by default.

Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
Expand Up @@ -191,8 +191,7 @@ At the time of writing this article, the SuperTokens feature set is completely f

- #### Managed Service:
- Free for the first **5000 MAUs** .
- **$29/month** for every **5000 MAUs** beyond the free limit of up to **50000 MAUs**.
- Custom pricing beyond **50000 MAUs**
- 2 cents / MAU post the first **5000 MAUs**.

### So is SuperTokens the way to go?
SuperToken's feature set and pricing make it a great choice for startups and mid-level businesses, but it may not be the best fit for large organisations that require enterprise features.
Expand Down
223 changes: 223 additions & 0 deletions content/how-to-create-an-invite-only-auth-flow/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@
---
title: How to create an invite-only auth flow in 2023
date: "2023-09-28"
description: "Invite only flows can drive exclusivity and enhance user engagement. In this blog we will go over how you can customize SuperTokens authentication to create an invite only flow"
cover: "how-to-create-an-invite-only-auth-flow.png"
category: "programming"
author: "Joel Coutinho"
---


## Introduction
Whether aiming to boost referrals, drive exclusivity, or simply enhance user engagement, a well-crafted invite flow can make all the difference. In this blog post, we will delve into the steps of how you can secure your React app with Email-password authentication with SuperTokens, customized to have an invite-only flow.


## Setup
Our demo app will use a React frontend with a NodeJS backend, but the instructions should translate to other frameworks and languages. You can find the list of [SuperTokens-supported frameworks and languages here](https://supertokens.com/docs/community/sdks).

We can start a new project configured with SuperTokens using their CLI with the following command:

`npx create-supertokens-app@latest`

You should see the following output:

![SuperTokens CLI](./supertokens-cli.png)


Follow the prompts on-screen and set up an app with a React frontend, and NodeJs backend configured with email-password based authentication.

We can now start customizing the authentication flows to enable invite-only authentication

## Step 1: Disable Sign Ups
If you were to run the example application now, you would be greeted with the authentication page. This page allows you to sign users up. We will need to disable the sign-up UI on the frontend and disable the sign up API on the backend.

![SuperTokens Sign Up screen](./sign-in-screen.png)

### Disable the sign up UI in SuperTokens Frontend config

We can customize the frontend UI and use CSS to hide the sign up button.

```tsx
import SuperTokens from "supertokens-auth-react";
import EmailPassword from "supertokens-auth-react/recipe/emailpassword";

SuperTokens.init({
appInfo: {
apiDomain: "...",
appName: "...",
websiteDomain: "..."
},
recipeList: [
EmailPassword.init({
signInAndUpFeature: {
signInForm: {
style: `
[data-supertokens~=headerSubtitle] {
display: none;
}
`,
}
},
}),
]
});
```

This should hide the button which allows you to switch to the sign up screen.

![SuperTokens Sign Up screen with sign up disabled](./sign-in-screen-sign-up-disabled.png)

### Disable the sign up API in SuperTokens Backend config

We override the SuperTokens backend config to disable the public facing sign up API:

```ts
import SuperTokens from "supertokens-node";
import EmailPassword from "supertokens-node/recipe/emailpassword";

SuperTokens.init({
appInfo: {
apiDomain: "...",
appName: "...",
websiteDomain: "..."
},
supertokens: {
connectionURI: "...",
},
recipeList: [
EmailPassword.init({
override: {
apis: (originalImplementation) => {
return {
...originalImplementation,
signUpPOST: undefined,
}
}
}
})
]
});
```

## Step 2: Creating the invite-only flow

### Create a protected API that will create users and send invite links
To create users and send them invite links we will need to create an API on the backend which will:

- Call the `signUp` function from the SuperTokens backend SDK using the user's email and a fake password. This fake password should be unguessable and should be shared across all invited users.
- Generate a password reset link and send that as an invite link to the user's email.
- Once the user clicks the link, they will be shown a page asking them to input their password after which, they can login.
- Finally, we add an access control check to make sure that only users with the `admin` role can add additional users.

```ts

import express from "express";
import { verifySession } from "supertokens-node/recipe/session/framework/express";
import { SessionRequest } from "supertokens-node/framework/express";
import UserRoles from "supertokens-node/recipe/userroles";
import EmailPassword from "supertokens-node/recipe/emailpassword";

const FAKE_PASSWORD = "asokdA87fnf30efjoiOI**cwjkn";

let app = express();

app.post("/create-user", verifySession({
overrideGlobalClaimValidators: async function (globalClaimValidators) {
return [...globalClaimValidators,
UserRoles.UserRoleClaim.validators.includes("admin")]
}
}), async (req: SessionRequest, res) => {
let email = req.body.email;

let signUpResult = await EmailPassword.signUp("public", email, FAKE_PASSWORD);
if (signUpResult.status === "EMAIL_ALREADY_EXISTS_ERROR") {
res.status(400).send("User already exists");
return;
}

// we successfully created the user. Now we should send them their invite link
await EmailPassword.sendResetPasswordEmail("public", signUpResult.user.id);

res.send("Success");
});
```

>Note:
> - The code above uses the default password reset path for the invite link (`/auth/reset-password`). You can create custom UI hosted on another path and use the password reset functions provided by the SuperTOkens frontend SDK to call the password reset token consumption API from the frontend.
> - Additionally, the `sendResetPasswordEmail` function uses the default password reset email(or the one customized using the emailDelivery config). If you would like to create the reset password link and send it yourself, you can use the `createResetPasswordLink` function to generate the password reset string.
### Ensure that invited users have reset their passwords

To ensure that users who have reset their passwords, we need to make the following changes:

- Prevent users from signing in with the `FAKE_PASSWORD`.
- Prevent users from resetting their password by setting their new password as the `FAKE_PASSWORD`.
- Prevent users from updating their password and setting it to the `FAKE_PASSWORD`.



```ts
import SuperTokens from "supertokens-node";
import EmailPassword from "supertokens-node/recipe/emailpassword";

const FAKE_PASSWORD = "asokdA87fnf30efjoiOI**cwjkn"

SuperTokens.init({
appInfo: {
apiDomain: "...",
appName: "...",
websiteDomain: "..."
},
supertokens: {
connectionURI: "...",
},
recipeList: [
EmailPassword.init({
override: {
apis: (originalImplementation) => {
// ... override from previous code snippets...
return originalImplementation
},
functions: (originalImplementation) => {
return {
...originalImplementation,
updateEmailOrPassword: async function (input) {
// This can be called on the backend
// in your own APIs
if (input.password === FAKE_PASSWORD) {
throw new Error("Use a different password")
}

return originalImplementation.updateEmailOrPassword(input);
},
resetPasswordUsingToken: async function (input) {
// This is called during the password reset flow
// when the user enters their new password
if (input.newPassword === FAKE_PASSWORD) {
return {
status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"
}
}
return originalImplementation.resetPasswordUsingToken(input);
},
signIn: async function (input) {
// This is called in the email password sign in API
if (input.password === FAKE_PASSWORD) {
return {
status: "WRONG_CREDENTIALS_ERROR"
}
}
return originalImplementation.signIn(input);
},
}
}
}
})
]
});
```

And that's it! Your app now only allows invited users to log in. Once a user is invited they will be sent an email asking to reset their password post which they are able to sign in.

## Conclusion
Although there are a few customizations that needed to be made, setting up an invite only flow with SuperTokens is pretty straight forward. You can find the related [documentation for the invite flow here](https://supertokens.com/docs/emailpassword/common-customizations/disable-sign-up/emailpassword-changes) if you need the code for other languages/frameworks.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
64 changes: 64 additions & 0 deletions content/how-we-cut-our-aws-costs-part-2/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
---
title: How we used multi-tenancy to cut our AWS costs by 50%
date: "2023-10-01"
description: "Part 2 in a series of howe we were able to cut down our AWS infrastructure costs by more than 50%"
cover: "how-we-cut-our-aws-costs-part-2.png"
category: "programming"
author: "Joel Coutinho"
---

[**Part 1: How does the SuperTokens managed service work and why does it need to change.**](./how-we-cut-our-aws-costs/)

**Part 2: Using multi-tenancy to cut our AWS infra costs by by more than 50%**

In this part we will go over SuperTokens Multi-tenancy feature and how it evolved our deployment cycle to cut our AWS billing by 50%.

Here's what we covered in our [last post](./how-we-cut-our-aws-costs/):
- SuperTokens infrastructure and deployment cycle.
- Improvements made to the SuperTokens deployment cycle to speed up production deployment times by 30%
- How our infra costs were not sustainable and why it needed to change.

## What is multi-tenancy?

As mentioned in Part 1, "We saw multi-tenancy as an opportunity to optimize the utilization of our EC2 instances by consolidating our core instances. This would cut down our costs while also providing the expected performance"... But what does that mean? Lets break it down. Multi-tenancy is a feature, typically used by B2B SaaS companies to allow multiple organizations to sign up to their SaaS app, with the ability for each organization to have their own login methods or SSO configurations. Additionally, user pools can also be segmented. Heres how it helped us.

## How we implemented SuperTokens Multi-tenancy

With multi-tenancy we re-architected the way we host and manage our users. Initially whenever a signed up and created an app with SuperTokens, it would trigger the following flow:

![SuperTokens Old Deployment Process](./supertokens-deployment-process.png)

In this process each development and production SuperTokens core ran in their own separate EC2 instances. With Multi-tenancy we now treat all SuperTokens customers as tenants. This means that we could now host multiple users on a single SuperTokens instance. Our deployment process now looks like this:

![SuperTokens New Deployment Process](./supertokens-deployment-process-new.png.png)

As you can see in the new deployment strategy, when a new user signs up, we now create a new tenant in a SuperTokens instance. These instances run in `T3 large` instances. In our testing, for development mode, up to 100 tenants can be run seamlessly on a single instance and for production mode, up to 50 tenants can be created on single instance.

![SuperTokens infrastructure](./supertokens-infrastructure.png)

## What are the benefits of the new architecture?

### 1. Cost Savings

Well the biggest difference post this change is the cost savings.

Heres a bill for the month of July before the multi-tenancy changes kicked-in:

![SuperTokens AWS bill for July](./supertokens-aws-bill-july.png)

And heres the bill for September, post the changes going live

![SuperTokens AWS bill for September](./supertokens-aws-bill-september.png)

When compared, its **54%** down

![SuperTokens Pricing comparison](./supertokens-pricing-comparison.png)

### 2. Improved start up time

Another improvement was app startup time. In the new architecture, creating a new user is as simple as creating a new tenant. When compared to the old process, the new architecture is about 94% faster and new apps can be crated in seconds.


## Conclusion

Multi-tenancy with SuperTokens is a powerful feature that enables businesses to create unique authentication flows for their customers, segment users into unique user pools and automatically create new new tenants. For SuperTokens, multi-tenancy allowed us to consolidate our user applications to save on resources, but, your use case maybe very different. You can learn more about how multi-tenancy works and the experiences it enables by visiting the [multi-tenancy feature page](https://supertokens.com/features/multi-tenancy)
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
54 changes: 54 additions & 0 deletions content/how-we-cut-our-aws-costs/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
---
title: How we cut our AWS costs by more than 50%
date: "2023-09-19"
description: "Part 1 in a series of how we were able to cut down our AWS infrastructure costs by more than 50%"
cover: "how-we-cut-our-aws-costs.png"
category: "programming"
author: "Joel Coutinho"
---

In this two part series we will go over SuperTokens manged service infrastructure and the changes we made to cut our AWS billing by more than 50%.

**Part 1: How does the SuperTokens managed service work and why does it need to change.**

[**Part 2: Using multi-tenancy to cut our AWS infra costs by by more than 50%**](./how-we-cut-our-aws-costs-part-2/)

## Introduction

The SuperTokens managed service powers numerous web products, mobile applications, and services and is primarily hosted on AWS. Our infrastructure leverages a suite of AWS tools, including AWS RDS for our database, EC2 instances for SuperToken deployments, and System Manager for instance management and automation. Over time, we've refined our deployment cycle to enhance stability, fault tolerance, and cost efficiency but our most recent update has yielded our biggest savings yet, slashing costs by over 50% while achieving [record scalability](https://twitter.com/supertokensio/status/1701600309397852270).


## What was the SuperTokens infrastructure like?

To gain a better understanding of the SuperTokens infrastructure, it's crucial to grasp the deployment cycle.

![SuperTokens Deployment process](./supertokens-deployment-process.png)

SuperTokens allow users to use the SuperTokens SAAS service in two modes: development and production. Here’s the breakdown of each:

**Development Mode:**
The Development mode runs on an *EC2 T3.small* instance. To maximize resource utilization, we deploy up to seven development core instances on the same *T3.small* instance. This configuration results in a remarkably swift setup for new development cores, typically taking a mere 15-20 seconds and is suitable for testing purposes.

**Production mode:**
In contrast, production mode follows a different deployment strategy. Each production mode deployment is hosted on a dedicated *EC2 T2.micro* instance. This means that when a new production SuperTokens core instance needs to be created, a fresh *T2.micro* instance is spun up, and docker is installed on it using System Manager. Consequently, this process requires additional time compared to the development mode, with an average deployment time of around 4-5 minutes.


For example, if 7 users were to sign up for SuperTokens, it would look like the following:

![SuperTokens example Infrastructure](./supertokens-example-infrastructure.png)

### Initial Improvements to the deployment cycle

One of our initial optimizations focused on reducing the startup time for generating production instances. We recognized that creating a custom [AMI](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html)(Amazon Machine Image) pre-installed with Docker alongside the operating system that would cut down on start-up time. This change trimmed approximately 45 seconds from the production deployment procedure, reducing the setup time to approximately 3-4 minutes.

In retrospect, another avenue for improvement that we identified was the usage of [AWS Reserved Instances](https://aws.amazon.com/ec2/pricing/reserved-instances/). While this approach would have entailed an upfront cost, it would have resulted in substantial long-term savings.

So what prompted us to change our deployment process?

## Why we had to change our deployment process
The past year has been quite a ride for SuperTokens. We released a host of new features and saw a big uptick in users. But, as our user numbers climbed, so did our infrastructure costs. With our AWS credits running out soon, we knew we had to do something to cut our expenses.

With the release of our new multi-tenancy feature we saw it as an opportunity to optimize the utilization of our EC2 instances by consolidating our core instances. This would cut down our costs while also providing the expected performance.

In part 2 we will go over the changes we made to achieve this.

Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading

0 comments on commit 2a772bb

Please sign in to comment.