@descope/react-sdk
Advanced tools
Comparing version 0.0.52-alpha.8 to 0.0.52-alpha.9
/// <reference types="react" /> | ||
import React, { FC, DOMAttributes } from 'react'; | ||
import DescopeWc from '@descope/web-component'; | ||
import createSdk from '@descope/web-js-sdk'; | ||
@@ -19,2 +20,3 @@ interface IAuthProviderProps { | ||
} | ||
declare type Sdk = ReturnType<typeof createSdk>; | ||
declare type CustomEvents<K extends string> = { | ||
@@ -51,2 +53,9 @@ [key in K]: (event: CustomEvent) => void; | ||
} | ||
interface IAuth { | ||
authenticated: boolean; | ||
user?: User; | ||
sessionToken?: string; | ||
logout: Sdk['logout']; | ||
me: Sdk['me']; | ||
} | ||
interface DescopeProps { | ||
@@ -65,10 +74,4 @@ flowId: string; | ||
declare const useAuth: () => { | ||
projectId: string; | ||
baseUrl: string; | ||
authenticated: boolean; | ||
user: User; | ||
sessionToken: string; | ||
}; | ||
declare const useAuth: () => IAuth; | ||
export { AuthProvider, Descope, SignInFlow, SignUpFlow, SignUpOrInFlow, useAuth }; |
@@ -1,1 +0,1 @@ | ||
import e,{useState as t,useMemo as r,useRef as s,useImperativeHandle as o,useCallback as n,useEffect as c}from"react";import"@descope/web-component";const i=e.createContext(void 0),d=({projectId:s,baseUrl:o,children:n})=>{const[c,d]=t(!1),[u,a]=t({}),[l,p]=t(""),f=r((()=>({projectId:s,baseUrl:o,user:u,authenticated:c,sessionToken:l,setUser:a,setAuthenticated:d,setSessionToken:p})),[c,u,s,o]);return e.createElement(i.Provider,{value:f},n)};d.defaultProps={baseUrl:"",children:void 0};const u=e.forwardRef((({flowId:t,onSuccess:r,onError:d},u)=>{const a=s();o(u,(()=>a.current));const{projectId:l,baseUrl:p,setAuthenticated:f,setUser:v,setSessionToken:E}=e.useContext(i),h=n((e=>{v(e.detail?.user),f(!0),E(e.detail?.sessionJwt),r&&r(e)}),[v,f,r]);return c((()=>{const e=a.current;return e?.addEventListener("success",h),d&&e?.addEventListener("error",d),()=>{d&&e?.removeEventListener("error",d),e?.removeEventListener("success",h)}}),[a,d,h]),e.createElement("descope-wc",{"project-id":l,"flow-id":t,"base-url":p,ref:a})}));u.defaultProps={onError:void 0,onSuccess:void 0};const a=t=>e.createElement(u,{...t,flowId:"sign-in"}),l=t=>e.createElement(u,{...t,flowId:"sign-up"}),p=t=>e.createElement(u,{...t,flowId:"sign-up-or-in"}),f=()=>{const t=e.useContext(i);if(!t)throw Error("You can only use useAuth in the context of <AuthProvider />");const{projectId:s,baseUrl:o,authenticated:n,user:c,sessionToken:d}=t;return r((()=>({projectId:s,baseUrl:o,authenticated:n,user:c,sessionToken:d})),[s,o,n,c,d])};export{d as AuthProvider,u as Descope,a as SignInFlow,l as SignUpFlow,p as SignUpOrInFlow,f as useAuth}; | ||
import e from"@descope/web-js-sdk";import t,{useState as o,useMemo as r,useRef as s,useImperativeHandle as n,useCallback as c,useEffect as i}from"react";import"@descope/web-component";const u=t.createContext(void 0),d=({projectId:s,baseUrl:n,children:c})=>{const[i,d]=o(!1),[a,l]=o({}),[p,f]=o(""),m=r((()=>s?e({projectId:s,baseUrl:n}):null),[s,n]),h=r((()=>({sdk:m,projectId:s,baseUrl:n,user:a,authenticated:i,sessionToken:p,setUser:l,setAuthenticated:d,setSessionToken:f})),[i,a,s,n]);return t.createElement(u.Provider,{value:h},c)};d.defaultProps={baseUrl:"",children:void 0};const a=t.forwardRef((({flowId:e,onSuccess:o,onError:r},d)=>{const a=s();n(d,(()=>a.current));const{projectId:l,baseUrl:p,setAuthenticated:f,setUser:m,setSessionToken:h}=t.useContext(u),v=c((e=>{m(e.detail?.user),f(!0),h(e.detail?.sessionJwt),o&&o(e)}),[m,f,o]);return i((()=>{const e=a.current;return e?.addEventListener("success",v),r&&e?.addEventListener("error",r),()=>{r&&e?.removeEventListener("error",r),e?.removeEventListener("success",v)}}),[a,r,v]),t.createElement("descope-wc",{"project-id":l,"flow-id":e,"base-url":p,ref:a})}));a.defaultProps={onError:void 0,onSuccess:void 0};const l=e=>t.createElement(a,{...e,flowId:"sign-in"}),p=e=>t.createElement(a,{...e,flowId:"sign-up"}),f=e=>t.createElement(a,{...e,flowId:"sign-up-or-in"}),m=()=>{const e=t.useContext(u);if(!e)throw Error("You can only use 'useAuth' in the context of <AuthProvider />");const{authenticated:o,user:s,sessionToken:n,sdk:i}=e,d=c(((...e)=>{if(!i)throw Error("You can only use 'logout' after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component");return i.logout(...e)}),[i]),a=c(((...e)=>{if(!i)throw Error("You can only use 'me' after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component");return i.me(...e)}),[i]);return r((()=>({authenticated:o,user:s,sessionToken:n,logout:d,me:a})),[o,s,n,i])};export{d as AuthProvider,a as Descope,l as SignInFlow,p as SignUpFlow,f as SignUpOrInFlow,m as useAuth}; |
{ | ||
"name": "@descope/react-sdk", | ||
"version": "0.0.52-alpha.8", | ||
"version": "0.0.52-alpha.9", | ||
"main": "dist/index.js", | ||
@@ -5,0 +5,0 @@ "types": "dist/index.d.ts", |
@@ -27,11 +27,11 @@ # @descope/react-sdk | ||
#### Use Descope to render specific flow | ||
You can use default flows or provide flow id directly to the Descope component | ||
You can use **default flows** or **provide flow id** directly to the Descope component | ||
##### Default flows | ||
##### 1. Default flows | ||
```js | ||
import { SignInFlow } from '@descope/react-sdk' | ||
// you can choose flow to run from the following | ||
// import { SignIn } from '@descope/react-sdk' | ||
// import { SignUp } from '@descope/react-sdk' | ||
import { SignUpOrIn } from '@descope/react-sdk' | ||
// import { SignUpFlow } from '@descope/react-sdk' | ||
// import { SignUpOrInFlow } from '@descope/react-sdk' | ||
@@ -41,3 +41,3 @@ const App = () => { | ||
{...} | ||
<SignUpOrIn | ||
<SignInFlow | ||
onSuccess={(e) => console.log('Logged in!')} | ||
@@ -50,3 +50,3 @@ onError={(e) => console.log('Could not logged in!')} | ||
##### Provide flow id | ||
##### 2. Provide flow id | ||
@@ -68,2 +68,74 @@ ```js | ||
#### Use the `useAuth` hook in your components in order to access authentication state and utilities | ||
This can be helpful to implement application-specific logic. Examples: | ||
- Render different components if current session is authenticated | ||
- Render user's content | ||
- Logout button | ||
```js | ||
import { useAuth } from '@descope/react-sdk' | ||
const App = () => { | ||
// NOTE - `useAuth` should be used inside `AuthProvider` context, | ||
// and will throw an exception if this requirement is not met | ||
const { authenticated, user, logout } = useAuth() | ||
return ( | ||
{...} | ||
{ | ||
// render different components if current session is authenticated | ||
authenticated && <MyPrivateComponent /> | ||
} | ||
{ | ||
// render user's content | ||
authenticated && <div>Hello ${user.name}</div> | ||
} | ||
{ | ||
// logout button | ||
authenticated && <button onClick={logout}>Logout</div> | ||
} | ||
) | ||
} | ||
``` | ||
#### Session token server validation (pass session token to server API) | ||
When developing a full-stack application, it is common to have private server API which requires a valid session token: | ||
 | ||
Note: Descope also provides server-side SDKs in various languages (NodeJS, Go, Python, etc). Descope's server SDKs have out-of-the-box session validation API that supports the options described bellow. To read more about session validation, Read [this section](https://docs.descope.com/guides/gettingstarted/#session-validation) in Descope documentation. | ||
The mechanism to pass session token depends on the Descope project's "Token response method" configuration. | ||
##### 1. Manage in cookies | ||
- Descope sets session token as cookie, which automatically sent each server api request. This option is more secure and is the recommended method for managing tokens, but for this option to work well with the browser - you must also configure a CNAME record for the custom domain listed, which will give a unified log in experience and securely restrict access to the session tokens that are stored in the cookies. | ||
When this option is configured, the browser will automatically add the session token cookie to the server in every request. | ||
##### 2. Manage in response body | ||
- Descope API returns session token in body. In this option, The React application should pass session cookie (`const { sessionToken } = useAuth()`) as Authorization header. This option never requires a custom domain, and is recommended for testing or while working in a sandbox environment. | ||
An example for using session token, | ||
```js | ||
import { useAuth } from '@descope/react-sdk' | ||
import { useCallback } from 'react' | ||
const App = () => { | ||
const { sessionToken } = useAuth() | ||
const onClick = useCallback(() => { | ||
fetch('https://localhost:3002/api/some-path' { | ||
method: 'GET', | ||
headers: { Authorization: `Bearer ${sessionToken}` } | ||
}) | ||
},[sessionToken]) | ||
return ( | ||
{...} | ||
{ | ||
// button that triggers an API that may use session token | ||
<button onClick={onClick}>Click Me</div> | ||
} | ||
) | ||
} | ||
``` | ||
## Contributing to this project | ||
@@ -70,0 +142,0 @@ In order to use this repo locally |
11912
76
147