diff --git a/docs/open-login/api-reference/initialization.mdx b/docs/open-login/api-reference/initialization.mdx index b15d11e..bae32bf 100644 --- a/docs/open-login/api-reference/initialization.mdx +++ b/docs/open-login/api-reference/initialization.mdx @@ -27,7 +27,9 @@ The OpenLogin constructor takes an object with `OpenLoginOptions` as input. - `options` - `OpenLoginOptions`: The options of the constructor - `clientId` - `string` : Your project id which you can get from [developer dashboard](https://developer.tor.us/) + - `network` - `enum`: Environment to run openlogin (testnet, mainnet, development) + - `_iframeUrl`- `string`: Url of openlogin iframe, you can pass custom iframe url here else it will be added based on network value.For testnet iframe url is `https://beta.openlogin.com` and for mainnet it is `https://app.openlogin.com`. If you are passing valid `network` value then network value @@ -35,6 +37,12 @@ The OpenLogin constructor takes an object with `OpenLoginOptions` as input. - `uxMode` - `enum`(optional): `popup` and `redirect` uxmode are supported. By default it is set to `redirect` + - `loginConfig` -`LoginConfig`(optional): LoginConfig allows you to specify custom loginConfig to customize visiblity of login modal + options and to specify your custom verifier for each login option. + + - `whiteLabel`: `WhiteLabelData` (optional): Options for whitelabling default openlogin modal. + You can toggle theme and primary colors of login modal and openlogin verification screens by using WhiteLabelData. + **Returns** - `Object`: The openlogin instance with all its methods and events. @@ -43,16 +51,147 @@ The OpenLogin constructor takes an object with `OpenLoginOptions` as input. ```javascript type OpenLoginOptions = { + /** + * You can get your clientId/projectId by registering your + * dapp on {@link "https://developer.tor.us"| developer dashbaord} + */ clientId: string; + + /** + * network specifies the openlogin iframe url url to be used. + * + * - `'mainnet'`: https://app.openlogin.com will be used which is the production version. + * - `'testnet'`: https://beta.openlogin.com will be used which is the beta version. + * - `'development'`: http://localhost:3000 will be used for development purpose. + */ network: OPENLOGIN_NETWORK_TYPE; - _iframeUrl?: string; + + /** + * Setting no3PC forces openlogin to assume that third party cookies are blocked + * in the browser. + * + * @defaultValue false + * @remarks + * Only pass no3PC to `true` when you are sure that third party cookies are not + * supported. By default openlogin will self check third party cookies and proceed + * accordingly. + */ + no3PC?: boolean; + + /** + * redirectUrl is the dapp's url where user will be redirected after login. + * + * @remarks + * Register this url at {@link "https://developer.tor.us"| developer dashbaord} + * else initialization will give error. + */ redirectUrl?: string; - loginUrl?: string; - webAuthnUrl?: string; - logoutUrl?: string; + + /** + * two uxModes are supported:- + * - `'POPUP'`: In this uxMode, a popup will be shown to user for login. + * - `'REDIRECT'`: In this uxMode, user will be redirected to a new window tab for login. + * + * @defaultValue `'POPUP'` + * @remarks + * + * Use of `'REDIRECT'` mode is recommended in browsers where popups might get blocked. + */ uxMode?: UX_MODE_TYPE; + + /** + * replaceUrlOnRedirect removes the params from the redirected url after login + * + * @defaultValue true + */ replaceUrlOnRedirect?: boolean; + + /** + * originData is used to verify the origin of dapp by iframe. + * + * @internal + * @remarks + * You don't have to pass originData explicitly if you have registered your dapp at + * {@link "https://developer.tor.us"| developer dashbaord}. + * + * originData contains a signature of dapp's origin url which is generated using + * project's secret. + */ originData?: OriginData; + + /** + * loginConfig enables you to pass your own login verifiers configuration for various + * loginProviders. + * + * loginConfig is key value map where each key should be a valid loginProvider and value + * should be custom configuration for that loginProvider + * + * @remarks + * You can deploy your own verifiers from {@link "https://developer.tor.us"| developer dashbaord} + * to use here. + * + */ + loginConfig?: LoginConfig; + + /** + * _iframeUrl is for internal development use only and is used to override the + * `network` parameter. + * @internal + */ + _iframeUrl?: string; + /** + * _startUrl is for internal development use only and is used specify authentication + * start url of iframe. + * @internal + */ + _startUrl?: string; + + /** + * _popupUrl is for internal development use only and is used specify url of popup window + * for popup uxMode. + * @internal + */ + _popupUrl?: string; + + /** + * options for whitelabling default openlogin modal. + */ + whiteLabel?: WhiteLabelData; +}; + +type WhiteLabelData = { + /** + * App name to display in the UI + */ + name?: string; + /** + * App logo to use in light mode + */ + logoLight?: string; + /** + * App logo to use in dark mode + */ + logoDark?: string; + /** + * Default language to use + * + * @defaultValue en + */ + defaultLanguage?: string; + /** + * Whether to enable dark mode + * + * @defaultValue false + */ + dark?: boolean; + + /** + * Used to customize theme of the login modal with following options + * `'primary'` - To customize primary color of modal's content. + */ + theme?: { + [P in string]: string; + }; }; const OPENLOGIN_NETWORK = { @@ -85,6 +224,118 @@ const openlogin = new OpenLogin({ }); ``` +## Using Custom login configuration + + +By default , openlogin will use verifiers deployed by torus and will show all default available login options in login modal. +If you want to customize the login modal or want to use your own login verifiers then you can use custom login configuration +with openlogin. + +For ex: In code snippet below, we are customizing loginConfig to show only google and facebook as login options in default +openlogin modal. Also you can pass your own verifiers in the configuration for any of the login providers. + +```javascript +const openlogin = new OpenLogin({ + // your clientId aka projectId , get it from https://developer.tor.us + // clientId is not required for localhost, you can set it to any string + // for development + clientId: YOUR_PROJECT_ID, + network: "testnet", + // you can pass login config to modify default + // login options in login modal, also you can pass + // your own verifiers. + loginConfig: { + google: { + verifier: "tkey-google-lrc", + name: "google", + typeOfLogin: "google", + showOnModal: true, + showOnDesktop: true, + showOnMobile: true, + }, + facebook: { + verifier: "tkey-facebook-lrc", + name: "facebook", + typeOfLogin: "facebook", + showOnModal: true, + showOnDesktop: false, + showOnMobile: true, + mainOption: true, + description: "facebook social login", + }, + }, +}); +``` + +**Reference** +```javascript + +type LoginConfig = Record< + string, + { + verifier: string; + + /** + * The type of login. Refer to enum `LOGIN_TYPE` + */ + typeOfLogin: TypeOfLogin; + + /** + * Display Name. If not provided, we use the default for openlogin app + */ + name: string; + + /** + * Description for button. If provided, it renders as a full length button. else, icon button + */ + description?: string; + + /** + * Custom client_id. If not provided, we use the default for openlogin app + */ + clientId?: string; + + verifierSubIdentifier?: string; + + /** + * Logo to be shown on mouse hover. If not provided, we use the default for openlogin app + */ + logoHover?: string; + + /** + * Logo to be shown on dark background (dark theme). If not provided, we use the default for openlogin app + */ + logoLight?: string; + + /** + * Logo to be shown on light background (light theme). If not provided, we use the default for openlogin app + */ + logoDark?: string; + + /** + * Show login button on the main list + */ + mainOption?: boolean; + + /** + * Whether to show the login button on modal or not + */ + showOnModal?: boolean; + + /** + * Whether to show the login button on desktop + */ + showOnDesktop?: boolean; + + /** + * Whether to show the login button on mobile + */ + showOnMobile?: boolean; + } +>; + +``` + ## `init` Initialize the OpenLogin object after creation. Init sync up the state of user login session in diff --git a/docs/open-login/api-reference/usage.mdx b/docs/open-login/api-reference/usage.mdx index e08dcf1..447464e 100644 --- a/docs/open-login/api-reference/usage.mdx +++ b/docs/open-login/api-reference/usage.mdx @@ -16,6 +16,7 @@ await openlogin.login(params); - `params` - `LoginParams` \(optional\) : The login options. Used to specify a type of login. + - `loginProvider` - `LOGIN_PROVIDER` : The loginProvider name. Supported loginProviders are can be of any value given in LOGIN_PROVIDER. In future versions you can pass custom loginProvider apart from options given LOGIN_PROVIDER. @@ -190,11 +191,11 @@ const privKey = await openlogin.login(); ```javascript const privKey = await openlogin.login({ - extraLoginOptions: { - login_hint: email, - }, - loginProvider: "email_passwordless", - redirectUrl: `https://example.com/redirect`, + extraLoginOptions: { + login_hint: email, + }, + loginProvider: "email_passwordless", + redirectUrl: `https://example.com/redirect`, }); ``` diff --git a/src/pages/guides/customAuth-aws-cognito.md b/src/pages/guides/customAuth-aws-cognito.md index fda15ec..89b8bca 100644 --- a/src/pages/guides/customAuth-aws-cognito.md +++ b/src/pages/guides/customAuth-aws-cognito.md @@ -1,7 +1,7 @@ --- -title: How to Integrate Torus CustomAuth and AWS Cognito -image: "/contents/TorusXAWSCognito.png" -description: Learn to use Torus CustomAuth with AWS Cognito. +title: How to Integrate Torus CustomAuth and AWS Cognito Hosted UI +image: "/contents/TorusxAWSCognito.png" +description: Learn to use Torus CustomAuth with AWS Cognito Hosted UI. order: 13 --- @@ -11,21 +11,14 @@ import TabItem from "@theme/TabItem"; ## Introduction -This tutorial will guide you on how to integrate CustomAuth with AWS cognito service. +This tutorial will guide you on how to integrate CustomAuth with AWS cognito service hosted ui. -In this example we will be using the aws cognito hosted UI with following login providers:- -- AWS cognito email password login provider -- Google Login Provider - -You can enable other providers from aws cognito console based on your requirements. In this example we are using above -login providers for a reason that we will going to use `email` as `jwt verifier id` field which will be available in both `AWS cognito email password login provider` and `Google Login Provider` jwt tokens , which means that a user who is using same email in above login providers will get same `private key` returned from torus nodes. - -It will make more sense later in this tutorial. +We will be authenticating users with google idp using aws cognito. However you can can enable other providers from aws cognito console based on your requirements. You can find -[the source code of this is example on Github](https://github.com/torusresearch/torus-direct-web-sdk/tree/master/examples/aws-cognito-example). +[the source code of this is example on Github](https://github.com/torusresearch/torus-direct-web-sdk/tree/master/examples/vue-app). -## Configuring Cognito user pool login provider in aws cognito. +## Configuring Cognito user pool in aws cognito. - Go to your aws account and open aws cognito service. @@ -50,13 +43,9 @@ domain in the `Authorized Javascript Origins` list and ` Note: `redirect_uri` should be added in app client settings in aws console. User will be redirected to `redirect_uri` -after login with `id_token`, which we will use to get user's torus key. - -To login a user we are appending above login params to hosted ui login route and redirecting user to it. +In order to login with aws cognito hosted ui, we just have to initialize torus `torus-direct-web-sdk` and call triggerLogin function as given in code snippet below. ```js - import { AWS_COGNITO_LOGIN_PARAMS, AWS_COGNITO_LOGIN_ROUTE } from "./config"; - - ... - ... - - login = async (e: React.FormEvent) => { - e.preventDefault(); - const finalUrl = new URL(AWS_COGNITO_LOGIN_ROUTE); - const finalJwtParams = JSON.parse(JSON.stringify(AWS_COGNITO_LOGIN_PARAMS)); - Object.keys(finalJwtParams).forEach((key) => { - if (finalJwtParams[key]) finalUrl.searchParams.append(key, finalJwtParams[key]); - }); - window.location.href = finalUrl.href; - }; + import TorusSdk, { UX_MODE } from "@toruslabs/torus-direct-web-sdk"; + ... + ... + async mounted() { + const torusdirectsdk = new TorusSdk({ + baseUrl: window.location.origin, + redirectPathName: "auth", + enableLogging: true, + uxMode: UX_MODE.REDIRECT, + network: "testnet", + }); + this.torusdirectsdk = torusdirectsdk; + await torusdirectsdk.init({ skipSw: true }); + } + ... + ... + async login() { + if (!this.torusdirectsdk) return; + return this.torusdirectsdk.triggerLogin({ + typeOfLogin: "jwt", + verifier: "demo-cognito-example", // verifier name , which we just created above from developer dashboard + clientId: "78i338ev9lkgjst3mfeuih9tsh", // aws cognito app client id + jwtParams: { + domain: "https://torus-test.auth.ap-southeast-1.amazoncognito.com/oauth2/", // your aws cognito hosted ui domain + user_info_endpoint: "userInfo" // aws cognito user info api path (optional) + }, + }); + }, ``` ## Handling login result:- -After user is logged in to aws cognito ui, user will be redirected back to our app on `redirect_ui` route. -We will parse redirected url hash params to decode the `id_token` in order to get torus key. +In login code snippet, note that we are using redirect `uxMode` while initializing which means that user will +be redirect to `redirectPathName` which is `auth` page in this example along with privateKey. You can get the result +on auth page with a simple function call which is shown in code snippet below. However you can also use `POPUP` uxmode to get +privateKey as a response to triggerLogin function. -- Import dependencies in redirect page:- -```js - import jwtDecode from "jwt-decode"; - import TorusDirectSdk, { TorusKey } from "@toruslabs/torus-direct-web-sdk"; -``` +- On auth page just calling `getRedirectResult` function will return the login result along with user's private key. -- Parse redirect url hash params:- ```js - componentDidMount = async () => { - try { - const url = new URL(window.location.href); - const cleanUrl = window.location.origin + window.location.pathname; - window.history.replaceState(null, "", cleanUrl); - const hash = url.hash.substr(1); - const { error, hashParameters } = this.handleRedirectParameters(hash); - if (error) { - this.setState({ consoleText: error }); - return; - } - const torusKeyResult = await this.getTorusKeyResult(hashParameters); - console.log(torusKeyResult); - if (torusKeyResult) { - this.setState({ consoleText: typeof torusKeyResult === "object" ? JSON.stringify(torusKeyResult) : torusKeyResult }); - } - } catch (error) { - console.log(error); - this.setState({ consoleText: error.message }); - } - }; - - handleRedirectParameters = (hash: string): { error: string; hashParameters: Record } => { - const hashParameters: Record = hash.split("&").reduce((result: Record, item) => { - const [part0, part1] = item.split("="); - result[part0] = part1; - return result; - }, {}); - let error = ""; - if (Object.keys(hashParameters).length > 0) { - error = hashParameters.error_description || hashParameters.error || error; - } - return { error, hashParameters }; - }; - -} -``` - -- Fetch torus key using parsed login response hash params:- - - Here we are decoding the `id_token` to get `jwt verifier id` field which is `email` in our case, as we configured it while creating verifier. - - > Note:- You cannot use reuse a `id_token` in `getTorusKey` function. It will give `Duplicate token error` - -```js - // this the verifier identifier which you entered to identify your verifier while creating custom verifier - const TORUS_DIRECT_SDK_VERIFIER_NAME = "your-custom-verifier-identifier"; - - getTorusKeyResult = async (loginResponse: Record): Promise => { - const torusdirectsdk = new TorusDirectSdk({ - baseUrl: `${window.location.origin}`, - redirectPathName: "/", - enableLogging: true, - network: "testnet", // details for test net - }); - const idToken = loginResponse.id_token; - const decodedToken = jwtDecode(idToken) as any; - - // note that we are passing decodedToken.email in this function which is important. - // we must pass the value of the field which was defined as jwt verifier id field while creating custom verifier. - return torusdirectsdk?.getTorusKey( - TORUS_DIRECT_SDK_VERIFIER_NAME, - decodedToken.email, - { verifier_id: decodedToken.email }, - loginResponse.id_token - ); - }; -``` - -## Logout:- - -To logout from congito you can simply redirect user to logout page of hosted aws cogito ui:- - -```js - const clientId = process.env.REACT_APP_COGNITO_CLIENT_ID; - - const AWS_COGNITO_LOGOUT_ROUTE = `${AWS_COGNITO_USER_POOL_DOMAIN}/logout`; - - const AWS_COGNITO_LOGOUT_PARAMS = { - client_id: clientId, - logout_uri: "http://localhost:3000", - }; - logout = async (e: React.FormEvent) => { - e.preventDefault(); - - try { - const finalUrl = new URL(AWS_COGNITO_LOGOUT_ROUTE); - const finalJwtParams = JSON.parse(JSON.stringify(AWS_COGNITO_LOGOUT_PARAMS)); - Object.keys(finalJwtParams).forEach((key) => { - if (finalJwtParams[key]) finalUrl.searchParams.append(key, finalJwtParams[key]); - }); - window.location.href = finalUrl.href; - } catch (error) { - console.error(error, "login caught"); - } - }; - + const torusdirectsdk = new TorusSdk({ + baseUrl: location.origin, + redirectPathName: "auth", + enableLogging: true, + uxMode: "redirect", + network: "testnet", + }); + const loginResult = await torusdirectsdk.getRedirectResult(); ``` ## Conclusion -You can use the above private key which is returned as response of `getTorusKey` in your web3 SDK. +You can use the above private key which is returned as response of `getRedirectResult` in your web3 SDK. diff --git a/src/pages/guides/customAuth-native-applelogins.md b/src/pages/guides/customAuth-native-applelogins.md index 5628ecf..33f2725 100644 --- a/src/pages/guides/customAuth-native-applelogins.md +++ b/src/pages/guides/customAuth-native-applelogins.md @@ -1,6 +1,6 @@ --- title: How to Integrate CustomAuth and apple logins -image: "/contents/torus-apple.png" +image: "/contents/Torus-apple.png" description: Learn to use CustomAuth with native apple logins. order: 12 ---