Skip to content

Commit

Permalink
docs: update examples
Browse files Browse the repository at this point in the history
  • Loading branch information
porcellus committed Sep 15, 2023
1 parent 60dd12d commit cabf84f
Show file tree
Hide file tree
Showing 24 changed files with 137 additions and 62 deletions.
2 changes: 1 addition & 1 deletion examples/with-account-linking/backend/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export function getWebsiteDomain() {
export const SuperTokensConfig: TypeInput = {
supertokens: {
// this is the location of the SuperTokens core.
connectionURI: "http://localhost:3567",
connectionURI: "https://try.supertokens.com",
},
appInfo: {
appName: "SuperTokens Demo App",
Expand Down
6 changes: 5 additions & 1 deletion examples/with-emailpassword-vercel/test/basic.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,11 @@ describe("SuperTokens Example Basic tests", function () {
await waitForSTElement(page, "[data-supertokens~='sendVerifyEmailIcon']");

// Create a new token and use it (we don't have access to the originally sent one)
const tokenInfo = await EmailVerification.createEmailVerificationToken("public", userId, email);
const tokenInfo = await EmailVerification.createEmailVerificationToken(
"public",
SuperTokensNode.convertToRecipeUserId(userId),
email
);
await page.goto(`${websiteDomain}/auth/verify-email?token=${tokenInfo.token}`);
await submitForm(page);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,9 @@ supertokens.init({
};
}
const res = await oI.emailPasswordSignInPOST(input);
await res.session.setClaimValue(RealPasswordClaim, true, input.userContext);
if (res.status === "OK") {
await res.session.setClaimValue(RealPasswordClaim, true, input.userContext);
}
return res;
},
emailPasswordSignUpPOST: async function (input) {
Expand All @@ -101,34 +103,42 @@ supertokens.init({
if (signInResponse.status === "WRONG_CREDENTIALS_ERROR") {
return response;
} else {
await EmailVerification.unverifyEmail(signInResponse.user.id, email);
await EmailVerification.unverifyEmail(signInResponse.recipeUserId, email);
response = {
status: "OK",
user: signInResponse.user,
recipeUserId: signInResponse.recipeUserId,
};
}
}
let user = response.user;

// we have just created a user with the fake password.
// so we mark their session as unusable by the APIs
await Session.createNewSession(
const newSession = await Session.createNewSession(
input.options.req,
input.options.res,
input.tenantId,
user.id,
response.recipeUserId,
{
...RealPasswordClaim.build(user.id, input.tenantId, input.userContext),
...RealPasswordClaim.build(
user.id,
response.recipeUserId,
input.tenantId,
input.userContext
),
},
{}
);
return {
...response,
status: "OK",
user,
session: newSession,
};
} else {
// session exists.. so the user is trying to change their password now
let userId = session.getUserId();
let recipeUserId = session.getRecipeUserId();
let password = input.formFields.filter((f) => f.id === "password")[0].value;

if (password === FAKE_PASSWORD) {
Expand All @@ -137,16 +147,18 @@ supertokens.init({

// now we modify the user's password to the new password + change the session to set RealPasswordClaim to true
await ThirdPartyEmailPassword.updateEmailOrPassword({
userId,
recipeUserId,
password,
});

await session.setClaimValue(RealPasswordClaim, true);

let user = await ThirdPartyEmailPassword.getUserById(userId);
let user = await supertokens.getUser(recipeUserId.getAsString());
return {
status: "OK",
user,
recipeUserId,
session,
};
}
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,11 @@ describe("SuperTokens Example Basic tests", function () {
const userId = await page.evaluate(() => window.__supertokensSessionRecipe.getUserId());

// Create a new token and use it (we don't have access to the originally sent one)
const tokenInfo = await EmailVerification.createEmailVerificationToken("public", userId, email);
const tokenInfo = await EmailVerification.createEmailVerificationToken(
"public",
SuperTokensNode.convertToRecipeUserId(userId),
email
);
await page.goto(`${websiteDomain}/auth/verify-email?token=${tokenInfo.token}`);
await submitForm(page);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ supertokens.init({
framework: "express",
supertokens: {
// TODO: This is a core hosted for demo purposes. You can use this, but make sure to change it to your core instance URI eventually.
connectionURI: "https://try.supertokens.io",
connectionURI: "https://try.supertokens.com",
apiKey: "<REQUIRED FOR MANAGED SERVICE, ELSE YOU CAN REMOVE THIS FIELD>",
},
appInfo: {
Expand Down
4 changes: 2 additions & 2 deletions examples/with-hasura-thirdpartyemailpassword/api-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,12 +89,12 @@ supertokens.init({
return {
...oI,
createNewSession: async function (input) {
let userInfo = await ThirdPartyEmailPassword.getUserById(input.userId);
let userInfo = await supertokens.getUser(input.userId);

input.accessTokenPayload = {
...input.accessTokenPayload,
"https://hasura.io/jwt/claims": {
"x-hasura-user-id": userInfo.email,
"x-hasura-user-id": userInfo.emails[0],
"x-hasura-default-role": "user",
"x-hasura-allowed-roles": ["user"],
},
Expand Down
6 changes: 5 additions & 1 deletion examples/with-i18next/test/basic.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,11 @@ describe("SuperTokens Example Basic tests", function () {
await waitForSTElement(page, "[data-supertokens~='sendVerifyEmailIcon']");

// Create a new token and use it (we don't have access to the originally sent one)
const tokenInfo = await EmailVerification.createEmailVerificationToken("public", userId, email);
const tokenInfo = await EmailVerification.createEmailVerificationToken(
"public",
SuperTokensNode.convertToRecipeUserId(userId),
email
);
await page.goto(`${websiteDomain}/auth/verify-email?token=${tokenInfo.token}`);

await submitForm(page);
Expand Down
6 changes: 5 additions & 1 deletion examples/with-localstorage/test/basic.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,11 @@ describe("SuperTokens Example Basic tests", function () {
await waitForSTElement(page, "[data-supertokens~='sendVerifyEmailIcon']");

// Create a new token and use it (we don't have access to the originally sent one)
const tokenInfo = await EmailVerification.createEmailVerificationToken("public", userId, email);
const tokenInfo = await EmailVerification.createEmailVerificationToken(
"public",
SuperTokensNode.convertToRecipeUserId(userId),
email
);
await page.goto(`${websiteDomain}/auth/verify-email?token=${tokenInfo.token}`);
await submitForm(page);

Expand Down
32 changes: 15 additions & 17 deletions examples/with-multiple-email-sign-in/api-server/epOverride.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,27 @@
import { RecipeInterface } from "supertokens-node/recipe/emailpassword";
import { APIInterface } from "supertokens-node/recipe/emailpassword";
import { getPrimaryEmailFromInputEmail } from "./emailLinkingMap";

export function epOverride(oI: RecipeInterface): RecipeInterface {
export function epOverride(oI: APIInterface): APIInterface {
return {
...oI,
signIn: async function (input) {
let primaryEmail = getPrimaryEmailFromInputEmail(input.email);
if (primaryEmail !== undefined) {
input.email = primaryEmail;
}
return oI.signIn(input);
},
signUp: async function (input) {
let primaryEmail = getPrimaryEmailFromInputEmail(input.email);
signInPOST: async function (input) {
const emailField = input.formFields.find((f) => f.id === "email")!;

let primaryEmail = getPrimaryEmailFromInputEmail(emailField.value);
if (primaryEmail !== undefined) {
input.email = primaryEmail;
emailField.value = primaryEmail;
}
return oI.signUp(input);
return oI.signInPOST!(input);
},
getUserByEmail: async function (input) {
let primaryEmail = getPrimaryEmailFromInputEmail(input.email);
signUpPOST: async function (input) {
const emailField = input.formFields.find((f) => f.id === "email")!;

let primaryEmail = getPrimaryEmailFromInputEmail(emailField.value);
if (primaryEmail !== undefined) {
input.email = primaryEmail;
emailField.value = primaryEmail;
}
return oI.getUserByEmail(input);

return oI.signUpPOST!(input);
},
};
}
4 changes: 2 additions & 2 deletions examples/with-multiple-email-sign-in/api-server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ supertokens.init({
}),
EmailPassword.init({
override: {
functions: (oI) => epOverride(oI),
apis: (oI) => epOverride(oI),
},
}),
Session.init(),
Expand All @@ -79,7 +79,7 @@ app.use(middleware());
app.post("/add-email", verifySession(), async (req: SessionRequest, res) => {
let userId = req.session!.getUserId();
let emailToAdd = req.body.email;
let success = associateNewEmailWithPrimaryEmail(emailToAdd, (await EmailPassword.getUserById(userId))!.email);
let success = associateNewEmailWithPrimaryEmail(emailToAdd, (await supertokens.getUser(userId))!.emails[0]);
res.send({
status: success ? "OK" : "INPUT_EMAIL_ASSOCIATED_WITH_ANOTHER_USER",
});
Expand Down
12 changes: 10 additions & 2 deletions examples/with-multiple-email-sign-in/test/basic.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,11 @@ describe("SuperTokens Example Basic tests", function () {
await waitForSTElement(page, "[data-supertokens~='sendVerifyEmailIcon']");

// Create a new token and use it (we don't have access to the originally sent one)
const tokenInfo = await EmailVerification.createEmailVerificationToken("public", userId, email);
const tokenInfo = await EmailVerification.createEmailVerificationToken(
"public",
SuperTokensNode.convertToRecipeUserId(userId),
email
);
await page.goto(`${websiteDomain}/auth/verify-email?token=${tokenInfo.token}`);
await waitForSTElement(page, "[data-supertokens='button']");
await submitForm(page);
Expand Down Expand Up @@ -121,7 +125,11 @@ describe("SuperTokens Example Basic tests", function () {
await submitForm(page);
// Redirected to email verification screen
await waitForSTElement(page, "[data-supertokens~='sendVerifyEmailIcon']");
const tokenInfo2 = await EmailVerification.createEmailVerificationToken("public", userId, email2);
const tokenInfo2 = await EmailVerification.createEmailVerificationToken(
"public",
SuperTokensNode.convertToRecipeUserId(userId),
email2
);
await page.goto(`${websiteDomain}/auth/verify-email?token=${tokenInfo2.token}`);
await waitForSTElement(page, "[data-supertokens='button']");
await submitForm(page);
Expand Down
Original file line number Diff line number Diff line change
@@ -1 +1,7 @@
{ "imports": { "netlify:edge": "https://edge.netlify.com/v1/index.ts" } }
{
"imports": {
"@netlify/edge-functions": "https://edge.netlify.com/v1/index.ts",
"netlify:edge": "https://edge.netlify.com/v1/index.ts?v=legacy"
},
"scopes": {}
}
1 change: 1 addition & 0 deletions examples/with-netlify/test/basic.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ describe("SuperTokens Example Basic tests", function () {

describe("Email Password test", function () {
it("Successful signup with credentials", async function () {
await new Promise((res) => setTimeout(res, 1000));
await Promise.all([page.goto(websiteDomain), page.waitForNavigation({ waitUntil: "networkidle0" })]);

// redirected to /auth
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ supertokens.init({
getSessionDataFromDatabase: () => null,
getTimeCreated: () => -1,
getUserId: () => "",
getRecipeUserId: () => input.recipeUserId,
revokeSession: () => {},
updateSessionDataInDatabase: () => {},
attachToRequestResponse: () => {},
Expand Down
6 changes: 5 additions & 1 deletion examples/with-one-login-per-subdomain/test/basic.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,11 @@ describe("SuperTokens Example Basic tests", function () {
await waitForSTElement(page, "[data-supertokens~='sendVerifyEmailIcon']");

// Create a new token and use it (we don't have access to the originally sent one)
const tokenInfo = await EmailVerification.createEmailVerificationToken("public", userId, email);
const tokenInfo = await EmailVerification.createEmailVerificationToken(
"public",
SuperTokensNode.convertToRecipeUserId(userId),
email
);
await page.goto(`${websiteDomain}/auth/verify-email?token=${tokenInfo.token}`);
await submitForm(page);

Expand Down
12 changes: 9 additions & 3 deletions examples/with-phone-password/api-server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ supertokens.init({
// session's payload as PhoneVerifiedClaim: true so that
// the user has access to API routes and the frontend UI
await session.setClaimValue(PhoneVerifiedClaim, true, input.userContext);
resp.user = (await supertokens.getUser(session.getUserId()))!;
}

return resp;
Expand Down Expand Up @@ -187,13 +188,18 @@ supertokens.init({

// we also get the phone number of the user and save it in the
// session so that the OTP can be sent to it directly
let userInfo = await EmailPassword.getUserById(input.userId, input.userContext);
let userInfo = await supertokens.getUser(input.userId, input.userContext);
return originalImplementation.createNewSession({
...input,
accessTokenPayload: {
...input.accessTokenPayload,
...PhoneVerifiedClaim.build(input.userId, input.tenantId, input.userContext),
phoneNumber: userInfo?.email,
...PhoneVerifiedClaim.build(
input.userId,
input.recipeUserId,
input.tenantId,
input.userContext
),
phoneNumber: userInfo?.emails[0],
},
});
}
Expand Down
6 changes: 3 additions & 3 deletions examples/with-phone-password/test/basic.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,9 @@ describe("SuperTokens Example Basic tests", function () {
const testOTP = "test123456";

before(async function () {
const user = await EmailPassword.getUserByEmail("public", phoneNumber);
if (user) {
await SuperTokensNode.deleteUser(user.id);
const user = await SuperTokensNode.listUsersByAccountInfo("public", { email: phoneNumber });
if (user.length > 0) {
await SuperTokensNode.deleteUser(user[0].id);
}

browser = await puppeteer.launch({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -185,17 +185,22 @@ supertokens.init({
// we alreay have a phone number associated with this user,
// so we will add it to the access token payload so that
// we can send an OTP to it without asking the end user.
let passwordlessUserInfo = await Passwordless.getUserById({
userId: userMetadata.metadata.passwordlessUserId as string,
userContext: input.userContext,
});
phoneNumber = passwordlessUserInfo?.phoneNumber;
let passwordlessUserInfo = await supertokens.getUser(
userMetadata.metadata.passwordlessUserId as string,
input.userContext
);
phoneNumber = passwordlessUserInfo?.phoneNumbers[0];
}
return originalImplementation.createNewSession({
...input,
accessTokenPayload: {
...input.accessTokenPayload,
...(await SecondFactorClaim.build(input.userId, input.tenantId, input.userContext)),
...(await SecondFactorClaim.build(
input.userId,
input.recipeUserId,
input.tenantId,
input.userContext
)),
phoneNumber,
},
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,11 @@ describe("SuperTokens Example Basic tests", function () {
await waitForSTElement(page, "[data-supertokens~='sendVerifyEmailIcon']");

// Create a new token and use it (we don't have access to the originally sent one)
const tokenInfo = await EmailVerification.createEmailVerificationToken("public", userId, email);
const tokenInfo = await EmailVerification.createEmailVerificationToken(
"public",
SuperTokensNode.convertToRecipeUserId(userId),
email
);
await page.goto(`${websiteDomain}/auth/verify-email?token=${tokenInfo.token}`);
await submitForm(page);

Expand Down
Loading

0 comments on commit cabf84f

Please sign in to comment.