AlexKhymenko / ngx-permissions

Permission and roles based access control for your angular(angular 2,4,5,6,7,9+) applications(AOT, lazy modules compatible
MIT License
939 stars 127 forks source link

HELP : When refresh page its redirect on dashboard #11

Closed ShaileshInfyom closed 7 years ago

ShaileshInfyom commented 7 years ago

i have check permission on route. its working file. thanks for your time. my issue is i load permission list when application startup.
for ex
my current page http://localhost:4200/#/app/users. now i refresh page redirect on dashboard instead of stay on current page. but i don't know how to resolve this issue. i also try to-load-permissions-before-application-start-up . please help me. Thanks in advance

 component: UsersComponent,
        children: [
            {
                path: '',
                component: UsersListComponent,
                pathMatch: 'full',
                canActivate: [NgxPermissionsGuard],
                data: {
                    permissions: {
                        only: 'read_user',
                        redirectTo: ConfigConstant.DEFAULT_ROUTE
                    },
                    title: 'Users · Life AI'
                }
            },

Angular version:4.0.2 ngx-permissions version: ^1.0.0

AlexKhymenko commented 7 years ago

Hi. It means that there are no permissions when application starts pls look in code maybe there is simple mistake in before application starts on try use another approach described here https://github.com/AlexKhymenko/ngx-permissions/wiki/common-use-cases-router sorry writing from phone on vacation :-)

ShaileshInfyom commented 7 years ago

Thanks for your quick response. but actually problem due to interceptor. and i resolved it

we125182 commented 6 years ago

@ShaileshInfyom @AlexKhymenko i have the same issue, could you tell me how to solve this? thank you!

AlexKhymenko commented 6 years ago

The problem that you need to load permissions before application starts you can use canActivate guard to load permissions https://github.com/AlexKhymenko/ngx-permissions/wiki/common-use-cases-router

we125182 commented 6 years ago

@AlexKhymenko thank you for your response. when i follow what you suggested, the problem is still occur. i find NgxPermissionsGuard is start before get permissions

 canActivate() {
       return authLogin().then((obj) => {
           //  NgxPermissionsGuard is start         
           return this.authPermissions.getPermissions('url');
       }).then((permissions) => {
           this.permissions.service.loadPermissions(permissions)
       )
   }
AlexKhymenko commented 6 years ago

can you post how you use it. In routings :-)

we125182 commented 6 years ago

@AlexKhymenko like this

// routings
const ROUTES: Routes = [
  {
    path: '',
    canActivate: [GuardService],
    component: ParentComponent,
    children: [
      {
        path: 'project',
        canActivate: [NgxPermissionsGuard],
        data: {
          permissions: {
            only: 'app/project/project',
            redirectTo: {
              navigationCommands: ['/extra/403'],
              navigationExtras: {
                skipLocationChange: true
              }
            }
          }
        },
        component: ProjectComponent
      },
      ...
]

// guardservice
public canActivate(route, state) {
    if (this.oauth.hasValidAccessToken()) {
      return this.hasGetUserInfo(state);
    } else {
      localStorage.setItem('activeRoute', state.url);
      this.oauth.initImplicitFlow();
    }
  }

public hasGetUserInfo(state) {
    if (this.appConfig.hasGetAuthInfo) {
      return this._isActivate(state);
    } else {
      // return this._waitUtilGetInfo(state);
      return this._getUserInfo();
    }
  }

private _getUserInfo() {
    return this.http.get(environment.env.API_URL + SERVER.authorize ).toPromise()
      .then((data) => {
        const res = (data as any);
        if (res.code === 200) {
          this.appConfig.hasGetAuthInfo = true;
          this.saveAuthInfo(res.data);
          return this._getPermissions();
        } else {
          console.log(res.message);
          return false;
        }
      }).catch((err) => {
        console.log(err);
        return false;
      });
  }

 private _getPermissions(): Promise<boolean> {
    return this.http.get(environment.env.API_URL + SERVER.authorize)
      .toPromise()
      .then((data: any) => {
        if (data.code === 200) {
          this.permissions = this.formatToStringArray(data.data.authorities);
          // this.getPermissions.emit(this.permissions);
          this.ngxP.loadPermissions(this.permissions);
          localStorage.setItem('permissions', JSON.stringify(this.permissions));
          return true;
        }
        return false;
      }).catch((err) => {
        console.error(err);
        return false;
      });
  }

private _isActivate(state): boolean {
    const activeRoute = localStorage.getItem('activeRoute');
    if (activeRoute) {
      localStorage.removeItem('activeRoute'); //
      this.router.navigateByUrl(activeRoute);
      return false;
    }
    return true;
  }
AlexKhymenko commented 6 years ago

Sorry, Have temperature.

I dont see loading permissions in this code.when you use isActivate. When you refresh page all services refreshes. So you need again load permissions or any other data.

 private _isActivate(state): boolean {
    const activeRoute = localStorage.getItem('activeRoute');
    if (activeRoute) {
      localStorage.removeItem('activeRoute'); //
      this.router.navigateByUrl(activeRoute);
      return false;
    }
    return true;
  }
we125182 commented 6 years ago

oh, because i set a judgement to decide which flow i will use. Look at this

public hasGetUserInfo(state) {
    if (this.appConfig.hasGetAuthInfo) {
      return this._isActivate(state);
    } else {
      // return this._waitUtilGetInfo(state);
      return this._getUserInfo();
    }
  }

when refresh page the variable this.appConfig.hasGetAuthInfo is false. so the function _isActivate wouldn't run. After getting the user info and permissions, it will change to true. and In this moment, function _isActive will run.

we125182 commented 6 years ago

@AlexKhymenko thank you for you response. and now i found what the problem is. it's a bug on angular CanActivate guards on child routes run before parent CanActivate guards finish. it fixed in version 4.3.2