@descope/react-sdk 0.0.52-alpha.8 → 0.0.52-alpha.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -24,20 +24,20 @@ const AppRoot = () => {
24
24
  }
25
25
  ```
26
26
  #### Use Descope to render specific flow
27
- You can use default flows or provide flow id directly to the Descope component
27
+ You can use **default flows** or **provide flow id** directly to the Descope component
28
28
 
29
- ##### Default flows
29
+ ##### 1. Default flows
30
30
 
31
31
  ```js
32
+ import { SignInFlow } from '@descope/react-sdk'
32
33
  // you can choose flow to run from the following
33
- // import { SignIn } from '@descope/react-sdk'
34
- // import { SignUp } from '@descope/react-sdk'
35
- import { SignUpOrIn } from '@descope/react-sdk'
34
+ // import { SignUpFlow } from '@descope/react-sdk'
35
+ // import { SignUpOrInFlow } from '@descope/react-sdk'
36
36
 
37
37
  const App = () => {
38
38
  return (
39
39
  {...}
40
- <SignUpOrIn
40
+ <SignInFlow
41
41
  onSuccess={(e) => console.log('Logged in!')}
42
42
  onError={(e) => console.log('Could not logged in!')}
43
43
  />
@@ -45,7 +45,7 @@ const App = () => {
45
45
  }
46
46
  ```
47
47
 
48
- ##### Provide flow id
48
+ ##### 2. Provide flow id
49
49
 
50
50
  ```js
51
51
  import { Descope } from '@descope/react-sdk'
@@ -62,6 +62,78 @@ const App = () => {
62
62
  }
63
63
  ```
64
64
 
65
+ #### Use the `useAuth` hook in your components in order to access authentication state and utilities
66
+ This can be helpful to implement application-specific logic. Examples:
67
+ - Render different components if current session is authenticated
68
+ - Render user's content
69
+ - Logout button
70
+ ```js
71
+ import { useAuth } from '@descope/react-sdk'
72
+
73
+ const App = () => {
74
+ // NOTE - `useAuth` should be used inside `AuthProvider` context,
75
+ // and will throw an exception if this requirement is not met
76
+ const { authenticated, user, logout } = useAuth()
77
+ return (
78
+ {...}
79
+ {
80
+ // render different components if current session is authenticated
81
+ authenticated && <MyPrivateComponent />
82
+ }
83
+ {
84
+ // render user's content
85
+ authenticated && <div>Hello ${user.name}</div>
86
+ }
87
+ {
88
+ // logout button
89
+ authenticated && <button onClick={logout}>Logout</div>
90
+ }
91
+ )
92
+ }
93
+ ```
94
+
95
+ #### Session token server validation (pass session token to server API)
96
+ When developing a full-stack application, it is common to have private server API which requires a valid session token:
97
+
98
+ ![session-token-validation-diagram](https://docs.descope.com/static/SessionValidation-cf7b2d5d26594f96421d894273a713d8.png)
99
+
100
+
101
+ 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.
102
+
103
+ The mechanism to pass session token depends on the Descope project's "Token response method" configuration.
104
+ ##### 1. Manage in cookies
105
+ - 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.
106
+
107
+ When this option is configured, the browser will automatically add the session token cookie to the server in every request.
108
+
109
+ ##### 2. Manage in response body
110
+ - 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.
111
+
112
+ An example for using session token,
113
+
114
+ ```js
115
+ import { useAuth } from '@descope/react-sdk'
116
+ import { useCallback } from 'react'
117
+
118
+ const App = () => {
119
+ const { sessionToken } = useAuth()
120
+
121
+ const onClick = useCallback(() => {
122
+ fetch('https://localhost:3002/api/some-path' {
123
+ method: 'GET',
124
+ headers: { Authorization: `Bearer ${sessionToken}` }
125
+ })
126
+ },[sessionToken])
127
+ return (
128
+ {...}
129
+ {
130
+ // button that triggers an API that may use session token
131
+ <button onClick={onClick}>Click Me</div>
132
+ }
133
+ )
134
+ }
135
+ ```
136
+
65
137
  ## Contributing to this project
66
138
  In order to use this repo locally
67
139
  - Clone this repository
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  /// <reference types="react" />
2
2
  import React, { FC, DOMAttributes } from 'react';
3
3
  import DescopeWc from '@descope/web-component';
4
+ import createSdk from '@descope/web-js-sdk';
4
5
 
5
6
  interface IAuthProviderProps {
6
7
  projectId: string;
@@ -16,6 +17,7 @@ declare global {
16
17
  }
17
18
  }
18
19
  }
20
+ declare type Sdk = ReturnType<typeof createSdk>;
19
21
  declare type CustomEvents<K extends string> = {
20
22
  [key in K]: (event: CustomEvent) => void;
21
23
  };
@@ -47,6 +49,13 @@ interface User {
47
49
  verifiedPhone?: boolean;
48
50
  tenants?: string[];
49
51
  }
52
+ interface IAuth {
53
+ authenticated: boolean;
54
+ user?: User;
55
+ sessionToken?: string;
56
+ logout: Sdk['logout'];
57
+ me: Sdk['me'];
58
+ }
50
59
  interface DescopeProps {
51
60
  flowId: string;
52
61
  onSuccess?: DescopeCustomElement['onsuccess'];
@@ -60,12 +69,6 @@ declare const SignUpOrInFlow: (props: DefaultFlowProps) => JSX.Element;
60
69
 
61
70
  declare const Descope: React.ForwardRefExoticComponent<DescopeProps & React.RefAttributes<HTMLElement>>;
62
71
 
63
- declare const useAuth: () => {
64
- projectId: string;
65
- baseUrl: string;
66
- authenticated: boolean;
67
- user: User;
68
- sessionToken: string;
69
- };
72
+ declare const useAuth: () => IAuth;
70
73
 
71
74
  export { AuthProvider, Descope, SignInFlow, SignUpFlow, SignUpOrInFlow, useAuth };
package/dist/index.js CHANGED
@@ -1 +1 @@
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};
1
+ 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};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@descope/react-sdk",
3
- "version": "0.0.52-alpha.8",
3
+ "version": "0.0.52-alpha.9",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "description": "Descope React SDK",