EdG
EdG

Reputation: 2351

Getting started with aor-permissions (admin-on-rest permissions)

I have read almost all the documentation aor-permissions available on internet. I am not starting a new project. I already have a project setup. This is my login method right now:

function getRoutes(store) {

    function hasAuth(nextState, replace, callback){
        const state = store.getState();
        const valid = !!state.tokenReducer.token;

        debug('AUTH: ', valid)

        if (valid){
            console.log("I am inside client routes line 44")
            debug('AUTH: Bailing. Already Valid.')
            return callback()
        }
        replace('/login')
        debug('AUTH: To Login')
        callback();
    }

    return (
        <Route path='/' component={App}>
            <Route path='/login' component={LoginPage}/>
            {/*<Route path='/login' component={LoginPage}/>*/}
            <Route path="/app" onEnter={hasAuth}>

Login component

class LoginPage extends Component {

    static contextTypes = {
        router: PropTypes.object.isRequired
    }

    toApp() {
        console.log("login ajax called")
        //event.preventDefault();
        var that = this;
        let token;
        var settings = {
            "async": true,
            "crossDomain": true,
            "url": "https://www.xxxx.xxxxx.xxxxx.com/auth/login/",
            "method": "POST",
            "credentials": 'include',
            "headers": {
                "content-type": "application/x-www-form-urlencoded",
            },
            "data": {
                "password": document.getElementById("password").value,
                "username": document.getElementById("username").value
            },
            success: (response, textStatus, jQxhr) => {

                this.props.tokenAction(response.auth_token, "apurv");


            }
        }


        $.ajax(settings).done((response) => {

            token = response.auth_token
            window.localStorage.token_auth = token;
            this.context.router.push('/app')
        });

Now I am trying to start using aor-permissions. The first thing it asks to do is something like this

// in authClient.js
import { AUTH_LOGIN, AUTH_LOGOUT, AUTH_CHECK, AUTH_ERROR } from 'admin-on-rest';
import { AUTH_GET_PERMISSIONS } from 'aor-permissions';
import { decode } from 'jsonwebtoken';

export default (type, params) => {
    // to login, fetch token and role from auth server, and store them in local storage
    if (type === AUTH_LOGIN) {
        const { username, password } = params;
        const request = new Request('https://example.com/authenticate', {
            method: 'POST',
            body: JSON.stringify({ username, password }),
            headers: new Headers({ 'Content-Type': 'application/json' }),
        })
        return fetch(request)
            .then(response => {
                if (response.status < 200 || response.status >= 300) {
                    throw new Error(response.statusText);
                }
                return response.json();
            })
            .then(({ token }) => {
                const decoded = decode(token);
                localStorage.setItem('token', token);
                localStorage.setItem('role', decoded.role);
            });
    }
    // ... usual authClient code

    // now simply read permissions from local storage
    if (type === AUTH_GET_PERMISSIONS) {
        return Promise.resolve(localStorage.getItem('role'));
    }
};

I don't have any authClient.js. How can I stitch my current structure with aor and start using it. The first step is not at all clear to me.

Upvotes: 1

Views: 150

Answers (1)

H S
H S

Reputation: 735

Using authclient is completely optional, if you want to write your own logic for a lot of things which are already in built in admin-on-rest such as authentication and login hooks.

But, if you want to use aor-permissions, I think you will have to go through authclient.

Also, you are making a /login route separately, so, I am assuming you don't know that you have a /login route already built in Admin component, if you are using Admin component. You just have to change loginPage prop of Admin component to customize the login view.

By default, an admin-on-rest app doesn’t require authentication. But if the REST API ever returns a 401 (Unauthorized) or a 403 (Forbidden) response, then the user is redirected to the /login route. You have nothing to do - it’s already built in.

The source of above quote is @ Authentication.

And in case you are not using Admin component at all, then, you will have to write your own login and authentication system. For more information visit - making custom app using admin-on-rest.

And if you already have the app written and want to integrate aor-permissions, you may like to go through the documentation of aor-permissions. In api section you may find interesting components like SwitchPermissions, WithPermission, etc., which might help you, where authClient function is passed to these components rather than in Admin component.

Hope it helps.

Upvotes: 1

Related Questions