All files / src/methods/login index.js

52.63% Statements 30/57
48.65% Branches 18/37
37.5% Functions 3/8
52.63% Lines 30/57
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 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278                  1x                                                                                                                                                                                                                                                   5x 5x             5x       5x 5x 5x 5x 5x 5x 5x       5x     2x 2x   2x 2x   2x 2x   1x                                   1x                   1x             1x                                     1x         5x 5x                 5x                           5x 5x     5x                 5x                                
import Api from '../../api';
import recognize from '../../automaticRecognition';
import config from '../../config';
import { cleanErrorEvo, manageError } from '../../errorManager';
import { isValid } from '../../validation';
import utility from '../../utility';
import global from '../../global';
import Method from '../Method';
 
const formModel = {
    container: 'smartlogin-container',
    username: 'username',
    password: 'passw',
    switchEye: 'login_pass_switch_type',
    loginButton: 'frmbutton',
    fbConnect: 'fb_connect',
    operatorChoice: 'operator'
};
 
/**
 * @memberOf Useris
 * @function login
 *
 * @description Validate and recognize the login object
 * to be sent to the newton adapter for the login.
 *
 * It must be used with the **smartlogin** template.
 *
 * It also manage the facebook login button.
 * Please note that you have to append the facebook access token
 * once you have logged in with facebook before passing useris response to newton.
 * This why we have decided to leave Useris unaware of Facebook.
 *
 * To allow the facebook integration
 * remember that you have to create and configurate a facebook app for your web applications.
 *
 * @param {Object} options Options object
 * @param {Object} [options.element=false] The div element where the html's tmpl will be injected
 * @param {Object} [options.regexObject={}]
 * **Optional** Contains all the regular expressions for input validation
 * (msisdn, pin, email, password and generic regex are allowed)
 * @param {String} [options.acccess_token=''] **Optionals** if true,
 * the tmpl calls will be called with the params access_token filled
 * @param {Boolean} [options.doNotLoad=false] **Optionals** if true,
 * this params will tell useris to not load the template (It doesn't make the apicall)
 * @param {Object} callbackObject Manage the success and error callback
 * @param {function} [callbackObject.onSuccess='no-default']
 * Success callback (code managed by the app)
 * @param {function} [callbackObject.onError='no-default'] Error callback (code managed by the app)
 * @param {function} [callbackObject.onFacebookSuccess='no-default']
 * Facebook success callback (code managed by the app).
 * You have to ovveride the access_token params before passing it to newton
 * @param {function} [callbackObject.onFacebookError='no-default']
 * Facebook error callback (code managed by the app)
 * @param {function} [callbackObject.onTemplateLoaded='no-default']
 * Callback executed when the template has been loaded.
 
 *
 * @example
 *  Useris.login({
 *      element: document.getElementById('elementId'),
 *      regexObject: {
 *          msidn: '',
 *          pin: '',
 *          email: '',
 *          password: '',
 *          generic: '',
 *          genericPassword: ''
 *      }
 *  }, {
 *      onSuccess: function(userCredentials){
 *          console.log(userCredentials);
 *          callsToNewtonAdapter.login(userCredentials);
 *      },
 *      onError: function(error){
 *          console.log('Error:', error);
 *          manageError(error);
 *      },
 *      onFacebookSuccess: function(userCredentials){
 *          console.log(userCredentials);
 *          FB.login(function(fbResponse){
 *              if(fbResponse.status === 'connected'){
 *                  // override the access_token params
 *                  userCredentials.access_token = FB.getAccessToken();
 *                  callsToNewtonAdapter.login(userCredentials);
 *              }
 *          }
 *      },
 *      onFacebookError: function(error){
 *          console.log('Error:', error);
 *          manageError(error);
 *      },
 *      onTemplateLoaded: function(tmplInfo){
 *          console.log('Template loaded', tmplInfo);
 *      }
 *  });
 *
 * @returns {object}
 * **Msisdn case:**
 * <pre>
 *     {
 *         msisdn: string,
 *         pin: string,
 *         type: 'msisdn',
 *         logged: boolean
 *     }
 * </pre>
 *
 * **Email case:**
 * <pre>
 *     {
 *         email: string,
 *         password: string,
 *         type: 'email',
 *         logged: boolean
 *     }
 * </pre>
 *
 * **Generic case:**
 * <pre>
 *     {
 *         username: string,
 *         password: string,
 *         type: 'generic',
 *         logged: boolean
 *     }
 * </pre>
 */
 
export default class Login extends Method {
    init = (options) => {
        this.queryParams = utility.getQueryParams();
        this.smartsectionObj = {
            subsection: 'smartlogin',
            loadForm: options.element || false,
            sentpin: this.queryParams.sentpin || 0,
            access_token: options.access_token || '',
            doNotLoad: options.doNotLoad || false
        };
        this.initUserView();
    };
 
    attachEvents = () => {
        const usernameInput = this.UserViewInstance.getElement(formModel.username);
        const passwordInput = this.UserViewInstance.getElement(formModel.password);
        const switchEye = this.UserViewInstance.getElement(formModel.switchEye);
        const operatorChoiceArray = config.get('operatorList') ? this.UserViewInstance.getElementsByName(formModel.operatorChoice) : false;
        const loginButton = this.UserViewInstance.getElement(formModel.loginButton);
        let facebookButton = false;
        Iif (config.get('identityFbEnabled')) {
            facebookButton = this.UserViewInstance.getElement(formModel.fbConnect);
        }
 
        this.UserViewInstance.attachEvent(loginButton, {
            eventName: 'click',
            event: (e) => {
                e.preventDefault();
                cleanErrorEvo();
 
                let username = usernameInput.value;
                const password = passwordInput.value;
 
                try {
                    switch (recognize(username, password, this.regexObject)) {
                    case 'MSISDN':
                        Iif (config.get('enableAliasCheck')) {
                            if (username.indexOf('+') >= 0) {
                                username = username.replace('+', '');
                            }
 
                            Api.getAlias({
                                msisdn: username
                            }).then((response) => {
                                this.callback('onSuccess', {
                                    alias: response.alias,
                                    pin: password,
                                    type: 'alias',
                                    logged: true
                                });
                            }).catch((error) => {
                                global.logger.log('Error: Can\'t get Alias from this username');
                                manageError(error, formModel.container);
                            });
                        } else Iif (operatorChoiceArray) {
                            this.callback('onSuccess', {
                                msisdn: username,
                                pin: password,
                                type: 'msisdn',
                                operator: this.UserViewInstance
                                    .getCheckedRadioValue(operatorChoiceArray),
                                logged: true
                            });
                        } else {
                            this.callback('onSuccess', {
                                msisdn: username,
                                pin: password,
                                type: 'msisdn',
                                logged: true
                            });
                        }
                        break;
                    case 'EMAIL':
                        this.callback('onSuccess', {
                            password,
                            email: username,
                            type: 'email',
                            logged: true
                        });
                        break;
                    default:
                        this.callback('onSuccess', {
                            username,
                            password,
                            type: 'generic',
                            logged: true
                        });
                        break;
                    }
                } catch (error) {
                    manageError(error, formModel.container);
                }
            }
        });
 
        Eif (switchEye) {
            this.UserViewInstance.attachEvent(switchEye, {
                eventName: 'click',
                event: (e) => {
                    e.preventDefault();
                    this.UserViewInstance.switchInputType(formModel.password, switchEye.id);
                }
            });
        }
 
        Iif (facebookButton) {
            this.UserViewInstance.attachEvent(facebookButton, {
                eventName: 'click',
                event: (e) => {
                    e.preventDefault();
                    this.callback('onFacebookSuccess', {
                        type: 'oauth',
                        provider: 'facebook',
                        logged: true
                    });
                }
            });
        }
 
        Eif (!config.get('enableAliasCheck')) {
            Iif (this.queryParams.msisdn) {
                this.UserViewInstance
                    .setValue(formModel.username, decodeURIComponent(this.queryParams.msisdn));
            } else Iif (this.queryParams.email) {
                this.UserViewInstance
                    .setValue(formModel.username, decodeURIComponent(this.queryParams.email));
            }
        }
 
        /* add on keyup event listener to disable password input for login
            where is required just the msisdn and not the pin */
 
        Iif (config.get('disablePinInput')) {
            this.UserViewInstance.attachEvent(usernameInput, {
                eventName: 'keyup',
                event: () => {
                    const isDisabled = passwordInput.disabled;
                    const value = this.UserViewInstance.getValue(formModel.username);
                    if (isValid(value, this.regexObject.msisdn)) {
                        this.UserViewInstance.disable(formModel.password);
                        this.UserViewInstance.setValue(formModel.password, '');
                    } else if (isDisabled) {
                        passwordInput.disabled = false;
                    }
                }
            });
        }
    }
}