Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implementing oauth.js in Angular App #20

Open
fr4n3r opened this issue Nov 10, 2015 · 5 comments
Open

Implementing oauth.js in Angular App #20

fr4n3r opened this issue Nov 10, 2015 · 5 comments
Assignees
Labels

Comments

@fr4n3r
Copy link

fr4n3r commented Nov 10, 2015

We are trying to figure out how to use Oauth.js with Angular.
First question comes where to initialize the library via the init() method. We have guessed a good place would be on angular module configuration through a service.
The second question arises when we want to configure the Oauth object with the loginFn. We have no clue on how to create the modal from the service.
Could you please provide a full sample working with angular? I guess we are not making the right decisions and a simple full working sample would be most helpful.
Thanks in advance.

@dcerecedo
Copy link

+1

@bgaillard
Copy link
Member

Hi @fr4n3r, our library is new and not heavily used but is currently work in production is several applications.

Currently we have only one customer who use our library with Angular JS, here is how we call the init() method (i'm not an Angular JS expert and use Backbone / Marionette more often).

define(['angular', 'oauth'], function (ng, OAuth) {

    var appModule = ng.module('app', []);

    appModule.config(
        [
            '$provide',
            function($provide) {

                console.log('Initializing OAuth.JS...');

                OAuth.init(
                    'angular',
                    {
                        /**
                         * The Angular JS '$provide' service in use in the application, this service will be used by OAuth.JS to 
                         * automatically decorate the Angular JS '$http' service.
                         * 
                         * @var {$provide}
                         */
                        $provide : $provide,

                        /**
                         * The value of OAuth 2.0 'client_id' URL parameter to user.
                         * 
                         * @var {String}
                         */
                        clientId : 'web-app',

                        /**
                         * Callback function automatically called by the 'OAuth.login(...)' method when the OAuth.JS 
                         * client detects that no OAuth 2.0 Access Token is stored in the client storage.
                         * 
                         * @param {Function} cb A function object to be called when the login is successful.
                         */
                        loginFn : function(loginContext) {

                            window.location.reload();

                        },

                        /**
                         * Callback function called by OAuth.JS when an HTTP request is sent on a secured resource and the 
                         * server returned an error. 
                         * 
                         * @param {XMLHttpRequest} xhr The {@link XMLHttpRequest} object used to execute the failed request. 
                         */
                        parseErrorFn : function(xhr) {

                            var action = 'reniew', 
                                jsonError = null;

                            try {
                                jsonError = JSON.parse(xhr.responseText);

                                if(jsonError.error === 'expired_token') {

                                    action = 'refresh';

                                }

                            } catch(syntaxError) {
                                // Nothing to do action stays equal to 'reniew'
                            }

                            return action;

                        },

                        /**
                         * The URL to the OAuth 2.0 Token Endpoint.
                         * 
                         * @var {String}
                         */
                        tokenEndpoint : document.body.getAttribute('data-base-url') + 'rest/tokens'

                    }
                );

                console.log('OAuth.JS initialized.');

            }
        ]
    );

    return appModule;
});

For the modal dialog your are free to create it the way you want, for example in one or our app evrything is wrapped inside a Backbone / Marionette view.

loginFn : function(loginContext) {

                // Show the connection / login modal view
                Backbone.Radio.channel('app-view').command(
                    'show-center-view', 
                    new ConnectionView(
                        {
                            loginContext : loginContext
                        }
                    )
                );

            }

Then in your modal dialog when your user taps the login button...

loginContext.sendCredentials(
    {
        'grant_type' : 'password',
        username : this.ui.pseudo.val(),
        password : this.ui.password.val()
    },
    $.proxy(this._onAfterCrendentialsSent, this)
);

...

onAfterCrendentialsSent : function(authStatus, done) {

    /// The provided credentials have been validated by the server
    if(authStatus.isConnected()) {

        // Here in most cases we fetch a user from our database and persist it inside a local storage to show it in our global layout 
        // Then you can redirect your user to any connected view
        ...

    }
    // An authentication error occured
    else {

var errorCode = authStatus.getAccessTokenResponse().getJsonResponse().error;

                // The provided credentials are bad, this how this code is described in the OAuth 2.0 specifications : 
                // "The provided authorization grants (e.g, authorization code, resource owner credentials) or refresh token 
                //  is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or 
                //  was issued to another client"
                if(errorCode === 'invalid_grant') {

                    // Re-enables the form
                    this._enableForm();

                    // Shows an alert message
                    this._showConnectError('Nom d\'utilisateur et / ou mot de passe invalide(s) !');

                } 

                // One required parameter is missing (username or password or client_id), this is how this code is described
                // in the OAuth 2.0 specifications :
                // "The request is missing a required parameter, includes an invalid parameter value, includes a parameter 
                //  more than once, or is otherwise malformed.
                else if(errorCode === 'invalid_request') {

                    // Re-enables the form
                    this._enableForm();

                    // Shows an alert message
                    this._showConnectError('Nom d\'utilisateur et / ou mot de passe manquant(s) !');

                }

    }

Is this enough to help you implement it inside your app ?

Anyway i'll let this issue open while no great documentation is writtent to describe this.

@bgaillard bgaillard self-assigned this Nov 10, 2015
@bgaillard
Copy link
Member

@fr4n3r Any news on this ? Did you integrate oauth.js with success un your Angular app ?

@fr4n3r
Copy link
Author

fr4n3r commented Jan 8, 2016

Hi, we did it without oauth.js

@bgaillard
Copy link
Member

Ok, thanks for your response, i'll let this issue opened until we improve our Angular integration and associated documentation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants