简体   繁体   中英

Login page before main (Aurelia)

I want when user coming check if he login before - if not -> redirect to login page -> if his email & password are okay -> redirect back to welcome page.

What problem I have -> service work properly with login class but welcome class totally ignore any changes in service.

Code

users.js

export class Users {
users = [
    { name: 'Lucian', email: 'lucian1992@zalando.de', password: 'lucian' },
    { name: 'Corki', email: 'corki2010@supplier.de', password: 'corki' },
    { name: 'Vayne', email: 'vaynii@zalando.de', password: 'vayne' }];

securedUser = {};
error = {};
usedOnce = 0;

check(checkUser) {
    this.usedOnce = 1;
    this.securedUser = this.users.filter((user) => user.email === checkUser.email
                                                && user.password ===   checkUser.password)[0];
    if (typeof this.securedUser === 'undefined'){
        this.error = { message: "No such kind of user or wrong password" };
    }
 }

}

login.js

import {inject} from 'aurelia-framework';
import {Users} from 'users-list';
import {Router} from 'aurelia-router';

@inject(Users, Router)
export class Login {
    constructor(userData, router) {
        this.router = router;
        this.users = userData.users;
        this.check = userData.check;
        this.securedUser = userData.securedUser;  // Changed after check function
        this.userError = userData.error;
    }
    checkUser = {};
    login() {
        this.check(this.checkUser);
        if (typeof this.userError === 'undefined') {
            alert(this.error.message);
        } else {
            this.router.navigate("")
        }
    }
}

welcome.js

import {inject} from 'aurelia-framework';
import {Users} from 'users-list';
import {Redirect} from 'aurelia-router';

@inject(Users)
export class Overview {
  constructor(userData) {
    this.usedOnce  = userData.usedOnce;
    this.securedUser = userData.securedUser;  // This object changed in login.js, but totally ignores in this class
  }
  heading = 'Welcome to the Article Manager Prototype!';

  canActivate() {
    if (this.securedUser) {
      return new Redirect('/login')
    }
  }
}

So, tech issue that securedUser changed in login.js, but totally ignored in welcome.js. Is this because of canActivate method? Because I also use activate() - the same problem.

Will appreciate any help with understanding the issue.

There is a solution for your problem in the official documentation:

import {Redirect} from 'aurelia-router';

export class App {
  configureRouter(config) {
    config.title = 'Aurelia';
    config.addPipelineStep('authorize', AuthorizeStep);
    config.map([
      { route: ['welcome'],    name: 'welcome',       moduleId: 'welcome',      nav: true, title:'Welcome' },
      { route: 'flickr',       name: 'flickr',        moduleId: 'flickr',       nav: true, auth: true },
      { route: 'child-router', name: 'childRouter',   moduleId: 'child-router', nav: true, title:'Child Router' },
      { route: '', redirect: 'welcome' }
    ]);
  }
}

class AuthorizeStep {
  run(navigationInstruction, next) {
    if (navigationInstruction.getAllInstructions().some(i => i.config.auth)) {
      var isLoggedIn = /* insert magic here */false;
      if (!isLoggedIn) {
        return next.cancel(new Redirect('login'));
      }
    }

    return next();
  }
}

Notice the addition of config.addPipelineStep('authorize', AuthorizeStep); compared to the regular router config logic.

Source: http://aurelia.io/docs.html#/aurelia/framework/1.0.0-beta.1.2.2/doc/article/cheat-sheet/7 (you need to scroll down a bit to section "Customizing the Navigation Pipeline")

I tried an own example with this and maybe i found your Problem.

You are checking if your securedUser is null. If it is NOT null you will reditect to login

canActivate() {
    if (this.securedUser) { // change to !this.securedUser
        return new Redirect('/login')
    }
}

And you are setting your securedUser initial to an empty object:

securedUser = {};

Because of that your first redirect was working even your if condition was wrong. Don´t set a initial value, set undefined or change your if condition and check on sercuredUser properties.

Your solution might work, but if you have 50 routes that must be authorised you would have to use canActivate hook 50 times! That is not an elegant solution for an authorising workflow.

This is a more elegant solution:

Instead of having a "route" to login, create an isolated root component and then update your main.js file:

//for example, imagine that your root component is located at src/app/app.js
//and your login component at src/login/login.js
//app.isLoggedIn() checks if the credentials/tokens are OK
aurelia.start().then(a => {
  let rootComponent = '' app.isLoggedIn() ? 'app/app' : 'login/login';
  a.setRoot(rootComponent, document.body);
});

Now, in your login/login.js root component you have to configure the router:

configureRouter(config, router) {
  config.title = 'YourTitle';
  config.map([
    { route: '', name: 'user-password', moduleId: './user-password', title: 'Sign In' }, //route for "username/password" screen
    { route: 'forgot-password', name: 'forgot-pwd', moduleId: './forgot-pwd', title: 'Forgot Password?' } //example of "forgot password" screen
  ]);
  config.mapUnknownRoutes(instruction => {
    //if an unknown route has been found,
    //a route from the app component, 'users/add' for example
    //redirect to sign-in component
    return './user-password';
  });

  this.router = router;
}

Create appropriated methods to authenticate the user and then redirect it to the app/app component:

//import and inject { Aurelia } from 'aurelia-framework';
this.aurelia.setRoot('app/app');

Now, if an unauthorised user access 'users/add', it will be redirected to the login page. If the login succeeds, the 'users/add' page will be shown.

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM