@codens/codens-auth
v0.1.9
Published
---
Downloads
1
Readme
codens-auth
Installation
npm install --save codens-auth
Documentation
Getting Started
1. Create configuration file
Create a configuration object to be able to do API calls and redirect to the correct auth endpoints.
export const authConfig = {
host: {
protocol: 'http',
name: 'localhost:5000',
},
endpoints: {
loggedIn: '/', // route when logged in
login: '/login', // login route
signup: '/signup', // signup route
recover: '/recover', // recover route
api: {
login: '/auth', // api login route
register: '/register', // api register route
recover: '/recover', // api recover route
},
},
};
2. Import and combine reducer
const { auth, form } = codensAuthReducer;
export default combineReducers({
auth,
form,
});
form
is the redux-form reducer. Don't implement if you already use redux-form.
3. Modify routes
Add requireAuth
to protect the route. noAuth
makes route inaccessible when user is logged in.
<Route>
<Route path="/protected" component={Protected} requireAuth />
<Route path="/open" component={Open} noAuth />
</Route>
createRoutes
adds onEnter depending on the routes. store
and config
are required.
import { createRoutes } from 'codens-auth';
const routes = createRoutes(routeElements, store, config);
When using SSR, modify this in the render function as well.
Note: createRoutes
has to be called before the Provider
component.
4. Add token to initialstate
When SSR is enabled, you have to add the token to the initialstate to redirect if necessary.
Note: Add cookieParser
to read cookies.
const token = (req.cookies && req.cookies.token) || null;
const store = configureStore(memoryHistory, { auth: { token, isFetching: false } });
5. Extract language messages
Add pattern node_modules/codens-auth/src/**/*.js
to extractMessages.js
.
Components
1. Login - Signup
import {
Login,
Signup,
} from 'codens-auth';
<Route path="/login" component={Login} noAuth />
<Route path="/signup" component={Signup} noAuth />
Login
: Login form component.Signup
: Signup form component.
2. SignoutButton
import { SignoutButton } from 'codens-auth';
<SignoutButton />
API Server
1. Create configuration file
const authConfig = {
token: {
expires: 10080,
secret: 'eyJ0aXRsZSI6ImZ1Y2sgeW91IHBheSBtZSIsImxlYWQiOiJ0',
},
};
2. createSecureAPI
import { createSecureAPI } from 'codens-auth/lib/server';
const secureAPI = createSecureAPI(authConfig, mongo);
Note: mongo
is an instance of mongoDB.
3. Routes
Make sure that the auth routes are accessible.
router.use(secureAPI.routes.unless([
'/auth',
'/register',
]));
Auth routes:
router.post('/auth', secureAPI.auth);
router.post('/register', secureAPI.register);