0.0.8 • Published 6 years ago
dunv-auth v0.0.8
dunv-auth
A helper library for logging in and out of a react-application. It is using a pretty standard jwt token-scheme. The token is saved to local storage. I built this package to be able to interface easily with uauth (https://github.com/dunv/uauth)
Setup
required
- the authReducer needs to be added to the store i.e. (
auth: authReducer) - setStore (access to redux-store) when initializing the app
- dispatch the action
loginBySavedtokenafter setting the store
optional
- setAuthComponent when a custom component for the login-screen is desired
- if using the default authComponent for logging in: include
import 'dunv-auth/lib/component.auth.less';
Usage
loginandlogoutactions can be dispatched on a redux-store anywhere in the app- the full
jwtand anything an auth-endpoint returns will be saved to the redux-store (propertyauth) - a HOC for requiring authorization with any other component can be used (
withAuth) - creating requests with
Authorizationheader (using Bearer jwt-token) already set (by means of Axios base requests)
Example
store.js
import { createStore, applyMiddleware, compose, combineReducers } from 'redux';
import ReduxThunk from 'redux-thunk';
import { authReducer } from 'dunv-auth';
const store = createStore(
combineReducers({
auth: authReducer,
}),
compose(applyMiddleware(ReduxThunk))
);
export default store;index.js
import { loginBySavedToken, setStore as setStoreInDunvAuth } from 'dunv-auth';
import 'dunv-auth/lib/component.auth.less';
(async () => {
// Init
setStoreInDunvAuth(store);
// If there is a saved token: log in with it
await store.dispatch(loginBySavedToken());
// Render
ReactDOM.render(routes, root);
})();requests.js
import { apiRequest, apiRequestWithoutAuth } from 'dunv-auth';
// an authenticated request to the backend with a apiUrl specified in redux-state (store.getState().config.apiUrl)
await apiRequest().post(urlPart, data);
// an authenticated request to the backend with a apiUrl specified in redux-state (store.getState().config.apiUrl) and timeout
apiRequest(timeout).post(urlPart, data);
// an authenticated request to the backend with a custom apiUrl
apiRequest(timeout, customBaseUrl).get(urlPart);
// an unauthenticated request to the backend
apiRequestWithoutAuth(timeout, customBaseUrl).get(urlPart)Development
- clone into
dunvAuthfolder - run
npm linkindunvAuthfolder - depend on this package in another project
- run
npm link dunv-authin that project - run
npm link <pathToNodeModulesReactOfProject>indunvAuthfolder (otherwise we will get the "two react versions" error https://reactjs.org/warnings/invalid-hook-call-warning.html#duplicate-react) - Hint: I could not get connect to work in this library, so I worked around it, using the store directly.
- publish
npm publish - build
npm run build - watch
npm run watch