1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>ReactJS</title> <style> table { border-collapse: collapse; } th, td { padding: 0 0.5rem; border: 1px solid black; } </style> </head> <body> <div id="root"></div> <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.1.0/redux.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/7.2.4/react-redux.js"></script> <script src="https://cdn.jsdelivr.net/npm/@reduxjs/[email protected]/dist/redux-toolkit.umd.min.js"></script> <!-- =========== slices/auth_slice.js =========== --> <script> const authSlice = RTK.createSlice({ name: 'authSlice', initialState: { info: {}, token: { accessToken: null, expirationTime: null }, loading: false }, reducers: { action_loginRequest(state, action) { state.loading = true; }, action_loginSuccess(state, action) { state.token = action.payload; state.loading = false; }, action_logout(state, action) { state.token = {}; state.info = {}; }, action_getInfoRequest(state, action) { state.loading = true; }, action_setInfoUser(state, action) { state.info = { name: action.payload.name, phone: action.payload.phone, } state.loading = false; } } }) const auth_reducer = authSlice.reducer; const { action_loginRequest, action_loginSuccess, action_logout, action_getInfoRequest, action_setInfoUser } = authSlice.actions; </script> <!-- =========== src/api/authAPI =========== --> <script type="text/babel"> //Đăng nhập chỉ để lấy token const api_login = ({ username, password }) => async (dispatch) => { try { dispatch(action_loginRequest()); let url = "https://learn-api.jmaster.io:8443/api/login"; let config = { method: 'POST', headers: new Headers({ 'Content-Type': "application/x-www-form-urlencoded", 'Cookie': "", }), body: new URLSearchParams({ 'username': username, 'password': password, }), redirect: 'follow' }; let response = await fetch(url, config); let responseJSON = await response.json(); dispatch(action_loginSuccess(responseJSON)); } catch (err) { console.log(err); } } //Dùng token để get thông tin user const api_getUser = (token) => async (dispatch) => { try { dispatch(action_getInfoRequest()); let url = 'https://learn-api.jmaster.io:8443/api/member/me'; let config = { method: 'GET', headers: new Headers({ 'Authorization': "Bearer " + token, 'Content-Type': "application/x-www-form-urlencoded", 'Cookie': "", }), redirect: 'follow' }; let response = await fetch(url, config); let responseJSON = await response.json(); dispatch(action_setInfoUser(responseJSON)); } catch (err) { console.log(err); } } </script> <!-- =========== src/store.js =========== --> <script type="text/babel"> const store = RTK.configureStore({ reducer: { auth: auth_reducer, } }) </script> <!-- =========== components/App.js =========== --> <script type="text/babel"> function Login(props) { const auth = ReactRedux.useSelector(state => state.auth); const dispatch = ReactRedux.useDispatch(); const [username, setUsername] = React.useState('0123456789'); const [password, setPassword] = React.useState('123456'); return ( <div> <input value={username} onChange={e => { setUsername(e.target.value) }} /> <br /> <input type="password" value={password} onChange={e => { setPassword(e.target.value) }} /> <br /> <button onClick={e => { dispatch(api_login({ username, password })) }}>Login</button> {auth.loading && <img src="http://www.vitinhdaivu.com/assets/imgs/ajax-loader.gif" width="18px" />} </div> ); } function Profile(props) { const auth = ReactRedux.useSelector(state => state.auth); const dispatch = ReactRedux.useDispatch(); React.useEffect(() => { dispatch(api_getUser(auth.token.accessToken)); }, []) return ( <div> <p>Name: {auth.loading ? <img src="http://www.vitinhdaivu.com/assets/imgs/ajax-loader.gif" width="18px" /> : auth.info.name}</p> <p>Phone: {auth.loading ? <img src="http://www.vitinhdaivu.com/assets/imgs/ajax-loader.gif" width="18px" /> : auth.info.phone}</p> <button onClick={() => { dispatch(action_logout()) }}>Logout</button> </div> ) } function App(props) { const auth = ReactRedux.useSelector(state => state.auth); return ( // Nếu có token thì dùng token lấy thông tin, nếu không thì phải đăng nhập <div> <p>Token: {JSON.stringify(auth.token, null, '\t')}</p> {auth.token.accessToken ? <Profile /> : <Login />} </div> ); } </script> <!-- =========== src/index.js =========== --> <script type="text/babel"> const Provider = ReactRedux.Provider; ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') ); </script> </body> </html> |
Demo-Authenticator: Login, Logout bằng Token
Author: admin - Posted: 30/06/21 - Update: 30/06/21