Skip to content

Instantly share code, notes, and snippets.

@jscyo

jscyo/sample.ts Secret

Last active January 16, 2023 07:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jscyo/8a26e4324b6943e1b240fa5259554437 to your computer and use it in GitHub Desktop.
Save jscyo/8a26e4324b6943e1b240fa5259554437 to your computer and use it in GitHub Desktop.
Map External UserId on successfull signup
import SuperTokens from "supertokens-node";
import ThirdPartyEmailPassword from "supertokens-node/recipe/thirdpartyemailpassword";
ThirdPartyEmailPassword.init({
override: {
functions: (oI) => {
return {
...oI,
emailPasswordSignUp: async function (input){
let response = await oI.emailPasswordSignUp(input);
if(response.status === "OK"){
// on successful signup
// retrieve/generate your postgres userId
let postgresUserId = "YOUR_POSTGRES_USER_ID"
await SuperTokens.createUserIdMapping({superTokensUserId: response.user.id, externalUserId: postgresUserId});
// update the response to use the postgresUserId
response.user.id = postgresUserId
}
return response;
}
}
}
}
})
@mitulkheni
Copy link

export class SupertokensService {
  private redisClient = redis.createClient({
    legacyMode: true,
    url: `redis://${process.env.REDIS_HOST}:${process.env.REDIS_PORT}`,
  });
  phoneNumberRegularExpresion = phoneNumberRegularExpresion;

  constructor(
    @Inject(ConfigInjectionToken) private config: AuthModuleConfig,
    @Inject(forwardRef(() => UsersService)) private userService: UsersService,
  ) {
    (async () => {
      await this.redisClient.connect();
    })();

    supertokens.init({
      appInfo: this.config.appInfo,
      supertokens: {
        connectionURI: this.config.connectionURI,
        apiKey: this.config.apiKey,
      },

      recipeList: [
        ThirdPartyEmailPassword.init({
          providers: [
            ThirdPartyEmailPassword.Google({
              clientSecret: 'TODO: GOOGLE_CLIENT_SECRET',
              clientId
            }),
          ],
          signUpFeature: {
            formFields: [
              {
                id: 'firstName',
              },
              {
                id: 'lastName',
              },
              {
                id: 'phoneNumber',
              },
            ],
          },
          override: {
            apis: (originalImplementation: any) => {
              return {
                ...originalImplementation,

                emailPasswordSignUpPOST: async function (input: any) {
                  if (
                    originalImplementation.emailPasswordSignUpPOST === undefined
                  ) {
                    throw Error('Should never come here');
                  }
                  const formFields: any = input.formFields;
                  const inputObject: any = {};
                  for (let index = 0; index < formFields.length; index++) {
                    const element = formFields[index];
                    inputObject[element.id] = element.value;
                  }
                  const { email, firstName, lastName, phoneNumber } =
                    inputObject;

                  // First we call the original implementation of signUpPOST.
                  const response: any =
                    await originalImplementation.emailPasswordSignUpPOST(input);

                  response['user'] = {
                    ...response['user'],
                    email,
                    firstName,
                    lastName,
                    phoneNumber,
                  };
                  return response;
                },

                emailPasswordEmailExistsGET: async function (input) {
                  console.log('in the emailPasswordEmailExistsGET');
                  input.options.res.setStatusCode(200);
                  input.options.res.sendJSONResponse({
                    message: 'my custom response',
                  });
                  return {
                    status: 'OK',
                    exists: false,
                  };
                },
              };
            },
          },
        }),
        Session.init({
          cookieSecure: true,
          cookieSameSite: 'none',
          override: {
            functions: (originalImplementation) => {
              return {
                ...originalImplementation,
                createNewSession: async function (input) {
                  return originalImplementation.createNewSession({
                    ...input,
                    accessTokenPayload: {
                      ...input.accessTokenPayload,
                      isPasswordless: input.userContext.isPasswordless === true,
                    },
                  });
                },
              };
            },
          },
        }),
      ],
    });
  }
}``` I have this implementation in my nest app. Please update the code accordingly to send custom response in signup and sign-in method.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment