aio-login 8.0.1 → 8.0.2

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.
Files changed (3) hide show
  1. package/index.d.ts +0 -1
  2. package/index.js +358 -1
  3. package/package.json +1 -1
package/index.d.ts CHANGED
@@ -28,7 +28,6 @@ type I_AILogin = {
28
28
  }) => ReactNode;
29
29
  translate?: (key: I_login_key) => string | undefined;
30
30
  fa?: boolean;
31
- rememberTime: number;
32
31
  id: string;
33
32
  splash?: {
34
33
  html: ReactNode;
package/index.js CHANGED
@@ -1 +1,358 @@
1
- import{useEffect as e,useRef as r,useState as t}from"react";import s from"aio-input";import{AddToAttrs as o,Storage as i}from"aio-utils";import{Loading as n,Alert as a}from"aio-popup";import u from"axios";import"./index.css";import{Fragment as l}from"react/jsx-runtime";import{jsxs as d}from"react/jsx-runtime";import{jsx as p}from"react/jsx-runtime";import{createElement as c}from"react";export function AIOLogin_updateCatchedUser(e,r){let t=new i("ai-login"+e),s=t.load("data");if(!s)return r;let o={...s,user:r};return t.save("data",o)}let AILogin=f=>{let{translate:m=()=>{},otpLength:g=4}=f,{validation:h=()=>{}}=f,[y,k]=t(),[b]=t(new i("ai-login"+f.id)),[w,x]=t(L),[$]=t(new n),[T,v]=t(!1),R=r(w);R.current=w,console.log(R.current);let[q,N]=t(A());function _(){return f.mode?f.mode:f.userpass?"userpass":f.otp?"otpnumber":"userpass"}function A(e){let r={inputs:()=>null,key:e||_(),title:null,submitText:"",shouldReturnsUserAndToken:!1};if("userpass"===r.key)r.inputs=()=>d(l,{children:[E({mode:r.key,field:"username",type:"text"}),E({mode:r.key,field:"password",type:"text"})]}),r.shouldReturnsUserAndToken=!0;else if("register"===r.key){if(f.register){let t=(f.register.inputs||(()=>[]))(R.current)||[];r.inputs=()=>d(l,{children:[E({mode:r.key,field:"username",type:"text"}),E({mode:r.key,field:"password",type:"password"}),E({mode:r.key,field:"repassword",type:"password"}),t.map(e=>E({mode:r.key,field:e.field,type:e.type,inputProps:e}))]})}}else"otpnumber"===r.key?r.inputs=()=>E({mode:r.key,field:"otpnumber",type:"text"}):"otpcode"===r.key&&(r.inputs=()=>E({mode:r.key,field:"otpcode",type:"text"}),r.shouldReturnsUserAndToken=!0);return r.submitText=U(r.key+"Button"),r.title=p("div",{className:"ai-login-title",children:U(r.key+"Title")}),r}function E(e){let r=e.inputProps||{},t=R.current;"register"===e.mode&&(t=t.register);let{maxLength:o=({otpnumber:11,otpcode:g})[e.mode],filter:i="otpnumber"===e.mode||"otpcode"===e.mode?["number"]:void 0,preview:n="password"===e.field,rtl:a=!!f.fa,label:u=f.label(e.field)}=r,l={...r,"aria-label":`aio-login-${e.field}`},d=r=>{let t=R.current;"register"===e.mode?x({...t,register:{...t.register,[e.field]:r}}):x({...t,[e.field]:r})};return c(s,{...r,maxLength:o,filter:i,preview:n,rtl:a,label:u,onChange:d,inputAttrs:l,key:`${e.mode}-${e.field}`,value:t[e.field],type:e.type})}function L(){var e;let r={username:"",password:"",otpnumber:"",otpcode:"",register:{username:"",password:"",repassword:""}};if(!f.register)return r;if(null!==(e=f.register)&&void 0!==e&&e.defaultValue){let t={};for(let s in f.register.defaultValue)t[s]=f.register.defaultValue[s];r.register=t}return r}let[P,j]=t(!0),[B,C]=t(!!f.splash);function U(e){let r={registerButton:{en:"Register",fa:"ثبت نام"},userpassButton:{en:"Login",fa:"ورود"},otpnumberButton:{en:"Send Number",fa:"ارسال شماره همراه"},otpcodeButton:{en:"Login",fa:"ورود"},registerTitle:{en:"Register",fa:"ثبت نام"},userpassTitle:{en:"Login",fa:"ورود"},otpcodeTitle:{en:"OTP Code",fa:"کد یکبار مصرف"},otpnumberTitle:{en:"Phone Number",fa:"شماره همراه"},switchuserpass:{en:"login by user name",fa:"ورود با نام کاربری"},switchregister:{en:"Go To Register",fa:"ثبت نام"},switchotp:{en:"login by otp",fa:"ورود با رمز یکبار مصرف"},repasswordMatch:{en:"Password is not match with Re password",fa:"رمز عبور با تکرار آن مطابقت ندارد"},usernameRequired:{en:"User Name is required",fa:"نام کاربری ضروری است"},passwordRequired:{en:"password is required",fa:"رمز عبور ضروری است"},repasswordRequired:{en:"Re Password is required",fa:"تکرار رمز عبور ضروری است"},otpnumberRequired:{en:"Phone Number is required",fa:"شماره همراه ضروری است"},otpcodeLength:{en:`otp code should be ${g} digit`,fa:`کد یکبار مصرف باید ${g} رقم باشد`},registerError:{en:"Registeration failed",fa:"ثبت نام با خطا روبرو شد"},userpassError:{en:"login by username failed",fa:"ورود با نام کاربری با خطا روبرو شد"},otpcodeError:{en:"login by otp failed",fa:"ورود با کد یکبار مصرف با خطا روبرو شد"},otpnumberError:{en:"send otp number for receive otp code failed",fa:"ارسال شماره همراه برای دریافت کد یکبار مصرف با خطا روبرو شد"}};return f.fa?r[e].fa:m(e)||r[e].en}async function I(e,r){if(!f.userpass)return;let{onSuccess:t}=await f.userpass.api(R.current,"userpass");$.show("login0");let s=await t(e);if($.hide("login0"),"object"==typeof s&&s.user&&"string"==typeof s.token){s.message&&W({type:"success",text:s.message});let{user:o,token:i}=s;b.save("data",{user:o,token:i}),k({user:o,token:i})}else{let n=`onSuccess of props.${r}.${"userpass"===r?"api":"codeApi"} should returns {user:any,token:string}`;W({type:"error",text:U(`${r}Error`),subtext:n})}}async function V(e,r){if(!f.userpass)return;let{onSuccess:t}=await f.userpass.api(R.current,"userpass");$.show("login0");let s=await t(e);$.hide("login0"),s.message&&W({type:"success",text:s.message}),"otpnumber"===r?N(A("otpcode")):setTimeout(()=>window.location.reload(),1e3)}async function M(e){"userpass"===q.key||"otpcode"===q.key?I(e,q.key):V(e,q.key)}async function O(){$.show("login0");let{url:e,method:r,body:t,onCatch:s}=await f[q.key].api(R.current,q.key);$.hide("login0"),u[r](e,t).then(M).catch(e=>{s?W({type:"error",text:"Error",subtext:s(e)}):e.message&&W({type:"error",text:"Error",subtext:e.message})})}function S(e){x(L()),N(A(e))}function z(e){return{className:"ai-login-mode",onClick:()=>S(e)}}function F(){return d("div",{className:"ai-login-modes",children:[f.userpass&&"userpass"!==q.key&&p("button",{...z("userpass"),children:U("switchuserpass")}),f.register&&"register"!==q.key&&p("button",{...z("register"),children:U("switchregister")}),f.otp&&"otpnumber"!==q.key&&p("button",{...z("otpnumber"),children:U("switchotp")})]})}function G(){let e=R.current;if("otpcode"===q.key&&(e.otpcode||"").length!==g)return U("otpcodeLength");if("otpnumber"===q.key&&!e.otpnumber)return U("otpnumberRequired");if("userpass"===q.key&&!e.username)return U("usernameRequired");if("register"===q.key){if(!e.register.username)return U("usernameRequired");if(!e.register.password)return U("passwordRequired");if(!e.register.repassword)return U("repasswordRequired");if(e.register.password!==e.register.repassword)return U("repasswordMatch")}return h(e,q.key)}function D(){let e=G();return d(l,{children:[p("div",{className:"ai-login-errors",children:!!e&&p("div",{className:"ai-login-error",children:e})}),p("button",{className:"ai-login-submit",disabled:!!e||!!T,onClick(){v(!0),setTimeout(()=>v(!1),3e3),O()},children:q.submitText})]})}function H(){let{title:e,inputs:r}=q;return d("div",{className:"ai-login-form",children:[e,r(),D(),F()]})}let J=e=>{let r=f[e],t=null;return r&&(t=r(q.key)),p("div",{className:`ai-login-${e}`,children:t})};function K(){b.remove("data"),window.location.reload()}async function Q(){if(f.splash&&setTimeout(()=>{C(!1)},f.splash.time),f.mock){k({user:f.mock.user,token:f.mock.token});return}let e=b.load("data",{},f.rememberTime),{user:r,token:t}=e;$.show("login0");let{url:s,method:o,onSuccess:i,onCatch:n}=await f.checkToken(t||"");$.hide("login0"),r&&t&&u[o](s,{headers:{authorization:`Bearer ${t}`}}).then(e=>{let s;try{s=i(e)}catch(o){W({type:"error",text:"checkToken failed",subtext:o.message});return}!0===s?k({user:r,token:t}):!1===s?K():W({type:"error",text:"checkToken failed",subtext:"checkToken props should return string as error or true as token is valid and false as token is invalid"})}).catch(e=>{let r,t="";try{r=n(e)}catch(s){t=s.message}"string"==typeof r?t=r:!1===r?K():t="AILogin checkToken onCatch props should returns string as error or false as invalid token",t?W({type:"error",text:"checkToken failed",subtext:t}):e.message&&W({type:"error",text:"Error",subtext:e.message})}),j(!1)}function W(e){a(e)}function X(){if(P||B)return f.splash?f.splash.html:null;if(!y){let e=o(f.attrs,{className:"ai-login",style:{direction:f.fa?"rtl":void 0}});return d("div",{...e,children:[J("before")," ",H()," ",J("after")]})}return f.renderApp({token:y.token,user:y.user,logout:K})}return e(()=>{Q()},[]),p(l,{children:X()})};export default AILogin;
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { useEffect, useRef, useState } from "react";
11
+ import AIOInput from "aio-input";
12
+ import { AddToAttrs, Storage } from "aio-utils";
13
+ import { Loading, Alert } from "aio-popup";
14
+ import axios from "axios";
15
+ import './index.css';
16
+ export function AIOLogin_updateCatchedUser(loginId, newUser) {
17
+ const storage = new Storage('ai-login' + loginId);
18
+ const storedData = storage.load('data');
19
+ if (!storedData) {
20
+ return newUser;
21
+ }
22
+ const newStoredData = Object.assign(Object.assign({}, storedData), { user: newUser });
23
+ return storage.save('data', newStoredData);
24
+ }
25
+ const AILogin = (props) => {
26
+ const { translate = () => { }, otpLength = 4 } = props;
27
+ const { validation = () => { return undefined; } } = props;
28
+ const [data, setData] = useState();
29
+ const [storage] = useState(new Storage('ai-login' + props.id));
30
+ const [model, setModel] = useState(getModel);
31
+ const [loading] = useState(new Loading());
32
+ const [submitDisabled, setSubmitDisabled] = useState(false);
33
+ const modelRef = useRef(model);
34
+ modelRef.current = model;
35
+ console.log(modelRef.current);
36
+ const [mode, setMode] = useState(getMode());
37
+ function getModeKey() {
38
+ if (props.mode) {
39
+ return props.mode;
40
+ }
41
+ if (props.userpass) {
42
+ return 'userpass';
43
+ }
44
+ if (props.otp) {
45
+ return 'otpnumber';
46
+ }
47
+ return 'userpass';
48
+ }
49
+ function getMode(mode) {
50
+ let res = { inputs: () => null, key: mode || getModeKey(), title: null, submitText: '', shouldReturnsUserAndToken: false };
51
+ if (res.key === 'userpass') {
52
+ res.inputs = () => {
53
+ return (<>
54
+ {getInput({ mode: res.key, field: 'username', type: 'text' })}
55
+ {getInput({ mode: res.key, field: 'password', type: 'text' })}
56
+ </>);
57
+ };
58
+ res.shouldReturnsUserAndToken = true;
59
+ }
60
+ else if (res.key === 'register') {
61
+ if (props.register) {
62
+ const inputs = (props.register.inputs || (() => []))(modelRef.current) || [];
63
+ res.inputs = () => {
64
+ return (<>
65
+ {getInput({ mode: res.key, field: 'username', type: 'text' })}
66
+ {getInput({ mode: res.key, field: 'password', type: 'password' })}
67
+ {getInput({ mode: res.key, field: 'repassword', type: 'password' })}
68
+ {inputs.map((input) => getInput({ mode: res.key, field: input.field, type: input.type, inputProps: input }))}
69
+ </>);
70
+ };
71
+ }
72
+ }
73
+ else if (res.key === 'otpnumber') {
74
+ res.inputs = () => getInput({ mode: res.key, field: 'otpnumber', type: 'text' });
75
+ }
76
+ else if (res.key === 'otpcode') {
77
+ res.inputs = () => getInput({ mode: res.key, field: 'otpcode', type: 'text' });
78
+ res.shouldReturnsUserAndToken = true;
79
+ }
80
+ res.submitText = trans(res.key + 'Button');
81
+ res.title = <div className="ai-login-title">{trans(res.key + 'Title')}</div>;
82
+ return res;
83
+ }
84
+ function getInput(p) {
85
+ const inputProps = p.inputProps || {};
86
+ let model = modelRef.current;
87
+ if (p.mode === 'register') {
88
+ model = model.register;
89
+ }
90
+ const { maxLength = { otpnumber: 11, otpcode: otpLength }[p.mode], filter = p.mode === 'otpnumber' || p.mode === 'otpcode' ? ['number'] : undefined, preview = p.field === 'password', rtl = !!props.fa, label = props.label(p.field) } = inputProps;
91
+ const inputAttrs = Object.assign(Object.assign({}, inputProps), { 'aria-label': `aio-login-${p.field}` });
92
+ const onChange = (v) => {
93
+ let model = modelRef.current;
94
+ if (p.mode === 'register') {
95
+ setModel(Object.assign(Object.assign({}, model), { register: Object.assign(Object.assign({}, model.register), { [p.field]: v }) }));
96
+ }
97
+ else {
98
+ setModel(Object.assign(Object.assign({}, model), { [p.field]: v }));
99
+ }
100
+ };
101
+ return (<AIOInput {...Object.assign(Object.assign({}, inputProps), { maxLength, filter, preview, rtl, label, onChange, inputAttrs })} key={`${p.mode}-${p.field}`} value={model[p.field]} type={p.type}/>);
102
+ }
103
+ function getModel() {
104
+ var _a;
105
+ let model = { username: '', password: '', otpnumber: '', otpcode: '', register: { username: '', password: '', repassword: '' } };
106
+ if (!props.register) {
107
+ return model;
108
+ }
109
+ if ((_a = props.register) === null || _a === void 0 ? void 0 : _a.defaultValue) {
110
+ let register = {};
111
+ for (let prop in props.register.defaultValue) {
112
+ register[prop] = props.register.defaultValue[prop];
113
+ }
114
+ model.register = register;
115
+ }
116
+ return model;
117
+ }
118
+ const [waitingCheckToken, setWeightingCheckToken] = useState(true);
119
+ const [splashing, setSplashing] = useState(!!props.splash);
120
+ function trans(key) {
121
+ const dic = {
122
+ registerButton: { en: 'Register', fa: 'ثبت نام' },
123
+ userpassButton: { en: 'Login', fa: 'ورود' },
124
+ otpnumberButton: { en: 'Send Number', fa: 'ارسال شماره همراه' },
125
+ otpcodeButton: { en: 'Login', fa: 'ورود' },
126
+ registerTitle: { en: 'Register', fa: 'ثبت نام' },
127
+ userpassTitle: { en: 'Login', fa: 'ورود' },
128
+ otpcodeTitle: { en: 'OTP Code', fa: 'کد یکبار مصرف' },
129
+ otpnumberTitle: { en: 'Phone Number', fa: 'شماره همراه' },
130
+ switchuserpass: { en: 'login by user name', fa: 'ورود با نام کاربری' },
131
+ switchregister: { en: 'Go To Register', fa: 'ثبت نام' },
132
+ switchotp: { en: 'login by otp', fa: 'ورود با رمز یکبار مصرف' },
133
+ repasswordMatch: { en: 'Password is not match with Re password', fa: 'رمز عبور با تکرار آن مطابقت ندارد' },
134
+ usernameRequired: { en: 'User Name is required', fa: 'نام کاربری ضروری است' },
135
+ passwordRequired: { en: 'password is required', fa: 'رمز عبور ضروری است' },
136
+ repasswordRequired: { en: 'Re Password is required', fa: 'تکرار رمز عبور ضروری است' },
137
+ otpnumberRequired: { en: 'Phone Number is required', fa: 'شماره همراه ضروری است' },
138
+ otpcodeLength: { en: `otp code should be ${otpLength} digit`, fa: `کد یکبار مصرف باید ${otpLength} رقم باشد` },
139
+ registerError: { en: 'Registeration failed', fa: 'ثبت نام با خطا روبرو شد' },
140
+ userpassError: { en: 'login by username failed', fa: 'ورود با نام کاربری با خطا روبرو شد' },
141
+ otpcodeError: { en: 'login by otp failed', fa: 'ورود با کد یکبار مصرف با خطا روبرو شد' },
142
+ otpnumberError: { en: 'send otp number for receive otp code failed', fa: 'ارسال شماره همراه برای دریافت کد یکبار مصرف با خطا روبرو شد' },
143
+ };
144
+ return props.fa ? dic[key].fa : translate(key) || dic[key].en;
145
+ }
146
+ function success_1(response, mode) {
147
+ return __awaiter(this, void 0, void 0, function* () {
148
+ if (!props.userpass) {
149
+ return;
150
+ }
151
+ const { onSuccess } = yield props.userpass.api(modelRef.current, 'userpass');
152
+ loading.show('login0');
153
+ const res = yield onSuccess(response);
154
+ loading.hide('login0');
155
+ if (typeof res !== 'object' || !res.user || typeof res.token !== 'string') {
156
+ const message = `onSuccess of props.${mode}.${mode === 'userpass' ? 'api' : 'codeApi'} should returns {user:any,token:string}`;
157
+ setAlert({ type: 'error', text: trans(`${mode}Error`), subtext: message });
158
+ }
159
+ else {
160
+ if (res.message) {
161
+ setAlert({ type: 'success', text: res.message });
162
+ }
163
+ const { user, token } = res;
164
+ storage.save('data', { user, token });
165
+ setData({ user, token });
166
+ }
167
+ });
168
+ }
169
+ function success_2(response, mode) {
170
+ return __awaiter(this, void 0, void 0, function* () {
171
+ if (!props.userpass) {
172
+ return;
173
+ }
174
+ const { onSuccess } = yield props.userpass.api(modelRef.current, 'userpass');
175
+ loading.show('login0');
176
+ const res = yield onSuccess(response);
177
+ loading.hide('login0');
178
+ if (res.message) {
179
+ setAlert({ type: 'success', text: res.message });
180
+ }
181
+ if (mode === 'otpnumber') {
182
+ setMode(getMode('otpcode'));
183
+ }
184
+ else {
185
+ setTimeout(() => window.location.reload(), 1000);
186
+ }
187
+ });
188
+ }
189
+ function success(response) {
190
+ return __awaiter(this, void 0, void 0, function* () {
191
+ if (mode.key === 'userpass' || mode.key === 'otpcode') {
192
+ success_1(response, mode.key);
193
+ }
194
+ else {
195
+ success_2(response, mode.key);
196
+ }
197
+ });
198
+ }
199
+ function submit() {
200
+ return __awaiter(this, void 0, void 0, function* () {
201
+ loading.show('login0');
202
+ const { url, method, body, onCatch } = yield props[mode.key].api(modelRef.current, mode.key);
203
+ loading.hide('login0');
204
+ axios[method](url, body).then(success).catch(response => {
205
+ if (onCatch) {
206
+ setAlert({ type: 'error', text: 'Error', subtext: onCatch(response) });
207
+ }
208
+ else if (response.message) {
209
+ setAlert({ type: 'error', text: 'Error', subtext: response.message });
210
+ }
211
+ });
212
+ });
213
+ }
214
+ function changeMode(mode) { setModel(getModel()); setMode(getMode(mode)); }
215
+ function mode_props(key) { return { className: 'ai-login-mode', onClick: () => changeMode(key) }; }
216
+ function mode_layout() {
217
+ return (<div className="ai-login-modes">
218
+ {props.userpass && mode.key !== 'userpass' && <button {...mode_props('userpass')}>{trans('switchuserpass')}</button>}
219
+ {props.register && mode.key !== 'register' && <button {...mode_props('register')}>{trans('switchregister')}</button>}
220
+ {props.otp && mode.key !== 'otpnumber' && <button {...mode_props('otpnumber')}>{trans('switchotp')}</button>}
221
+ </div>);
222
+ }
223
+ function validate() {
224
+ const model = modelRef.current;
225
+ if (mode.key === 'otpcode') {
226
+ if ((model.otpcode || '').length !== otpLength) {
227
+ return trans('otpcodeLength');
228
+ }
229
+ }
230
+ if (mode.key === 'otpnumber') {
231
+ if (!model.otpnumber) {
232
+ return trans('otpnumberRequired');
233
+ }
234
+ }
235
+ if (mode.key === 'userpass') {
236
+ if (!model.username) {
237
+ return trans('usernameRequired');
238
+ }
239
+ }
240
+ if (mode.key === 'register') {
241
+ if (!model.register.username) {
242
+ return trans('usernameRequired');
243
+ }
244
+ if (!model.register.password) {
245
+ return trans('passwordRequired');
246
+ }
247
+ if (!model.register.repassword) {
248
+ return trans('repasswordRequired');
249
+ }
250
+ if (model.register.password !== model.register.repassword) {
251
+ return trans('repasswordMatch');
252
+ }
253
+ }
254
+ return validation(model, mode.key);
255
+ }
256
+ function submit_layout() {
257
+ const message = validate();
258
+ return (<>
259
+ <div className="ai-login-errors">
260
+ {!!message && <div className="ai-login-error">{message}</div>}
261
+ </div>
262
+ <button className='ai-login-submit' disabled={!!message || !!submitDisabled} onClick={() => {
263
+ setSubmitDisabled(true);
264
+ setTimeout(() => setSubmitDisabled(false), 3000);
265
+ submit();
266
+ }}>{mode.submitText}</button>
267
+ </>);
268
+ }
269
+ function form_layout() {
270
+ const { title, inputs } = mode;
271
+ return (<div className="ai-login-form">{title}{inputs()}{submit_layout()}{mode_layout()}</div>);
272
+ }
273
+ const bf_layout = (type) => {
274
+ const fn = props[type];
275
+ let content = null;
276
+ if (fn) {
277
+ content = fn(mode.key);
278
+ }
279
+ return (<div className={`ai-login-${type}`}>{content}</div>);
280
+ };
281
+ function logout() { storage.remove('data'); window.location.reload(); }
282
+ function CheckToken() {
283
+ return __awaiter(this, void 0, void 0, function* () {
284
+ if (props.splash) {
285
+ setTimeout(() => { setSplashing(false); }, props.splash.time);
286
+ }
287
+ if (props.mock) {
288
+ setData({ user: props.mock.user, token: props.mock.token });
289
+ return;
290
+ }
291
+ const storedData = storage.load('data', {}), { user, token } = storedData;
292
+ loading.show('login0');
293
+ const { url, method, onSuccess, onCatch } = yield props.checkToken(token || '');
294
+ loading.hide('login0');
295
+ if (user && token) {
296
+ axios[method](url, { headers: { authorization: `Bearer ${token}` } })
297
+ .then(response => {
298
+ let res;
299
+ try {
300
+ res = onSuccess(response);
301
+ }
302
+ catch (err) {
303
+ setAlert({ type: 'error', text: 'checkToken failed', subtext: err.message });
304
+ return;
305
+ }
306
+ if (res === true) {
307
+ setData({ user, token });
308
+ }
309
+ else if (res === false) {
310
+ logout();
311
+ }
312
+ else {
313
+ setAlert({ type: 'error', text: 'checkToken failed', subtext: 'checkToken props should return string as error or true as token is valid and false as token is invalid' });
314
+ }
315
+ })
316
+ .catch(response => {
317
+ let res, message = '';
318
+ try {
319
+ res = onCatch(response);
320
+ }
321
+ catch (err) {
322
+ message = err.message;
323
+ }
324
+ if (typeof res === 'string') {
325
+ message = res;
326
+ }
327
+ else if (res === false) {
328
+ logout();
329
+ }
330
+ else {
331
+ message = 'AILogin checkToken onCatch props should returns string as error or false as invalid token';
332
+ }
333
+ if (message) {
334
+ setAlert({ type: 'error', text: 'checkToken failed', subtext: message });
335
+ }
336
+ else if (response.message) {
337
+ setAlert({ type: 'error', text: 'Error', subtext: response.message });
338
+ }
339
+ });
340
+ }
341
+ setWeightingCheckToken(false);
342
+ });
343
+ }
344
+ useEffect(() => { CheckToken(); }, []);
345
+ function setAlert(p) { Alert(p); }
346
+ function getContent() {
347
+ if (waitingCheckToken || splashing) {
348
+ return props.splash ? props.splash.html : null;
349
+ }
350
+ if (!data) {
351
+ const attrs = AddToAttrs(props.attrs, { className: 'ai-login', style: { direction: !!props.fa ? 'rtl' : undefined } });
352
+ return (<div {...attrs}>{bf_layout('before')} {form_layout()} {bf_layout('after')}</div>);
353
+ }
354
+ return props.renderApp({ token: data.token, user: data.user, logout });
355
+ }
356
+ return (<>{getContent()}</>);
357
+ };
358
+ export default AILogin;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aio-login",
3
- "version": "8.0.1",
3
+ "version": "8.0.2",
4
4
  "description": "handle all types of popup and modals in react",
5
5
  "main": "index.js",
6
6
  "scripts": {