Angular 6: Guard on all routes is not working











up vote
0
down vote

favorite












I'm trying to make the frontend secured by only letting certain Id's getting access. I want that If someone try to enter any route except for /login/:id, he'll get page-not-found if he didn't logged already, but it's not working.
These are my routing table and guard:



EDIT:
I edited the routing table and added to 'login/:id' redirectTo, and now there aren't any errors, but the id is undefined so it's go to page-not-found component even though I entered login/1.
when I tried to debug the code, I noticed that the route isn't of login/1 but '' even if I wrote in the url login/1.



app-routing.module.ts






// Routing array - set routes to each html page
const appRoutes: Routes = [
{ path: 'login/:id', redirectTo:'/courses', canActivate: [AuthGuard] },
{ path: '', canActivate: [AuthGuard], canActivateChild: [AuthGuard], children: [
{ path: '', redirectTo: '/courses', pathMatch: 'full' },
{ path: 'courses', component: CourseListComponent, pathMatch: 'full'},
{ path: 'courses/:courseId', component: CourseDetailComponent, pathMatch: 'full' },
{ path: 'courses/:courseId/unit/:unitId', component: CoursePlayComponent,
children: [
{ path: '', component: CourseListComponent },
{ path: 'lesson/:lessonId', component: CourseLessonComponent, data:{ type: 'lesson'} },
{ path: 'quiz/:quizId', component: CourseQuizComponent, data: {type: 'quiz'} }
]}
]},
{ path: '**', component: PageNotFoundComponent, pathMatch: 'full' }];





auth.guard.ts






     // what we'll use in production and testing
canActivate(route: ActivatedRouteSnapshot, state:
RouterStateSnapshot): boolean |
Observable<boolean> | Promise<boolean> {
// save the id from route snapshot
const id = route.params.id;

// if you try to logged with id
if (id) {
this.authUserService.login(id);

// if there was error with HttpClient - return false
if (this.authUserService.errorMessage) {
this.router.navigate(["**"]);
return false;
}

// there wasn't any errors - redirectTo courses
else {
this.router.navigate(["/courses"]);
return true;
}
}

// if you already logged and just navigate between pages
else if (this.authUserService.isLoggedIn )
return true;

else {
this.router.navigate(["**"]);
return false;
}
}

canActivateChild(route: ActivatedRouteSnapshot,state:
RouterStateSnapshot): boolean |
Observable<boolean> | Promise<boolean> {
return this.canActivate(route, state);
}





auth-user.service.ts






export class AuthUserService {

private user: IUser;
public errorMessage: string;
public isLoggedIn: boolean = false;

constructor(private userService: UserService) { }

// store the session and call http get
login(id: number) {
this.userService.getUser(id).subscribe(
user => {
this.user = user;
localStorage.setItem('user', JSON.stringify(this.user));
this.isLoggedIn = true;
},
error => this.errorMessage = <any>error
);
}

// clear session
logout() {
localStorage.removeItem('user');
this.isLoggedIn = false;
}
}












share|improve this question




























    up vote
    0
    down vote

    favorite












    I'm trying to make the frontend secured by only letting certain Id's getting access. I want that If someone try to enter any route except for /login/:id, he'll get page-not-found if he didn't logged already, but it's not working.
    These are my routing table and guard:



    EDIT:
    I edited the routing table and added to 'login/:id' redirectTo, and now there aren't any errors, but the id is undefined so it's go to page-not-found component even though I entered login/1.
    when I tried to debug the code, I noticed that the route isn't of login/1 but '' even if I wrote in the url login/1.



    app-routing.module.ts






    // Routing array - set routes to each html page
    const appRoutes: Routes = [
    { path: 'login/:id', redirectTo:'/courses', canActivate: [AuthGuard] },
    { path: '', canActivate: [AuthGuard], canActivateChild: [AuthGuard], children: [
    { path: '', redirectTo: '/courses', pathMatch: 'full' },
    { path: 'courses', component: CourseListComponent, pathMatch: 'full'},
    { path: 'courses/:courseId', component: CourseDetailComponent, pathMatch: 'full' },
    { path: 'courses/:courseId/unit/:unitId', component: CoursePlayComponent,
    children: [
    { path: '', component: CourseListComponent },
    { path: 'lesson/:lessonId', component: CourseLessonComponent, data:{ type: 'lesson'} },
    { path: 'quiz/:quizId', component: CourseQuizComponent, data: {type: 'quiz'} }
    ]}
    ]},
    { path: '**', component: PageNotFoundComponent, pathMatch: 'full' }];





    auth.guard.ts






         // what we'll use in production and testing
    canActivate(route: ActivatedRouteSnapshot, state:
    RouterStateSnapshot): boolean |
    Observable<boolean> | Promise<boolean> {
    // save the id from route snapshot
    const id = route.params.id;

    // if you try to logged with id
    if (id) {
    this.authUserService.login(id);

    // if there was error with HttpClient - return false
    if (this.authUserService.errorMessage) {
    this.router.navigate(["**"]);
    return false;
    }

    // there wasn't any errors - redirectTo courses
    else {
    this.router.navigate(["/courses"]);
    return true;
    }
    }

    // if you already logged and just navigate between pages
    else if (this.authUserService.isLoggedIn )
    return true;

    else {
    this.router.navigate(["**"]);
    return false;
    }
    }

    canActivateChild(route: ActivatedRouteSnapshot,state:
    RouterStateSnapshot): boolean |
    Observable<boolean> | Promise<boolean> {
    return this.canActivate(route, state);
    }





    auth-user.service.ts






    export class AuthUserService {

    private user: IUser;
    public errorMessage: string;
    public isLoggedIn: boolean = false;

    constructor(private userService: UserService) { }

    // store the session and call http get
    login(id: number) {
    this.userService.getUser(id).subscribe(
    user => {
    this.user = user;
    localStorage.setItem('user', JSON.stringify(this.user));
    this.isLoggedIn = true;
    },
    error => this.errorMessage = <any>error
    );
    }

    // clear session
    logout() {
    localStorage.removeItem('user');
    this.isLoggedIn = false;
    }
    }












    share|improve this question


























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I'm trying to make the frontend secured by only letting certain Id's getting access. I want that If someone try to enter any route except for /login/:id, he'll get page-not-found if he didn't logged already, but it's not working.
      These are my routing table and guard:



      EDIT:
      I edited the routing table and added to 'login/:id' redirectTo, and now there aren't any errors, but the id is undefined so it's go to page-not-found component even though I entered login/1.
      when I tried to debug the code, I noticed that the route isn't of login/1 but '' even if I wrote in the url login/1.



      app-routing.module.ts






      // Routing array - set routes to each html page
      const appRoutes: Routes = [
      { path: 'login/:id', redirectTo:'/courses', canActivate: [AuthGuard] },
      { path: '', canActivate: [AuthGuard], canActivateChild: [AuthGuard], children: [
      { path: '', redirectTo: '/courses', pathMatch: 'full' },
      { path: 'courses', component: CourseListComponent, pathMatch: 'full'},
      { path: 'courses/:courseId', component: CourseDetailComponent, pathMatch: 'full' },
      { path: 'courses/:courseId/unit/:unitId', component: CoursePlayComponent,
      children: [
      { path: '', component: CourseListComponent },
      { path: 'lesson/:lessonId', component: CourseLessonComponent, data:{ type: 'lesson'} },
      { path: 'quiz/:quizId', component: CourseQuizComponent, data: {type: 'quiz'} }
      ]}
      ]},
      { path: '**', component: PageNotFoundComponent, pathMatch: 'full' }];





      auth.guard.ts






           // what we'll use in production and testing
      canActivate(route: ActivatedRouteSnapshot, state:
      RouterStateSnapshot): boolean |
      Observable<boolean> | Promise<boolean> {
      // save the id from route snapshot
      const id = route.params.id;

      // if you try to logged with id
      if (id) {
      this.authUserService.login(id);

      // if there was error with HttpClient - return false
      if (this.authUserService.errorMessage) {
      this.router.navigate(["**"]);
      return false;
      }

      // there wasn't any errors - redirectTo courses
      else {
      this.router.navigate(["/courses"]);
      return true;
      }
      }

      // if you already logged and just navigate between pages
      else if (this.authUserService.isLoggedIn )
      return true;

      else {
      this.router.navigate(["**"]);
      return false;
      }
      }

      canActivateChild(route: ActivatedRouteSnapshot,state:
      RouterStateSnapshot): boolean |
      Observable<boolean> | Promise<boolean> {
      return this.canActivate(route, state);
      }





      auth-user.service.ts






      export class AuthUserService {

      private user: IUser;
      public errorMessage: string;
      public isLoggedIn: boolean = false;

      constructor(private userService: UserService) { }

      // store the session and call http get
      login(id: number) {
      this.userService.getUser(id).subscribe(
      user => {
      this.user = user;
      localStorage.setItem('user', JSON.stringify(this.user));
      this.isLoggedIn = true;
      },
      error => this.errorMessage = <any>error
      );
      }

      // clear session
      logout() {
      localStorage.removeItem('user');
      this.isLoggedIn = false;
      }
      }












      share|improve this question















      I'm trying to make the frontend secured by only letting certain Id's getting access. I want that If someone try to enter any route except for /login/:id, he'll get page-not-found if he didn't logged already, but it's not working.
      These are my routing table and guard:



      EDIT:
      I edited the routing table and added to 'login/:id' redirectTo, and now there aren't any errors, but the id is undefined so it's go to page-not-found component even though I entered login/1.
      when I tried to debug the code, I noticed that the route isn't of login/1 but '' even if I wrote in the url login/1.



      app-routing.module.ts






      // Routing array - set routes to each html page
      const appRoutes: Routes = [
      { path: 'login/:id', redirectTo:'/courses', canActivate: [AuthGuard] },
      { path: '', canActivate: [AuthGuard], canActivateChild: [AuthGuard], children: [
      { path: '', redirectTo: '/courses', pathMatch: 'full' },
      { path: 'courses', component: CourseListComponent, pathMatch: 'full'},
      { path: 'courses/:courseId', component: CourseDetailComponent, pathMatch: 'full' },
      { path: 'courses/:courseId/unit/:unitId', component: CoursePlayComponent,
      children: [
      { path: '', component: CourseListComponent },
      { path: 'lesson/:lessonId', component: CourseLessonComponent, data:{ type: 'lesson'} },
      { path: 'quiz/:quizId', component: CourseQuizComponent, data: {type: 'quiz'} }
      ]}
      ]},
      { path: '**', component: PageNotFoundComponent, pathMatch: 'full' }];





      auth.guard.ts






           // what we'll use in production and testing
      canActivate(route: ActivatedRouteSnapshot, state:
      RouterStateSnapshot): boolean |
      Observable<boolean> | Promise<boolean> {
      // save the id from route snapshot
      const id = route.params.id;

      // if you try to logged with id
      if (id) {
      this.authUserService.login(id);

      // if there was error with HttpClient - return false
      if (this.authUserService.errorMessage) {
      this.router.navigate(["**"]);
      return false;
      }

      // there wasn't any errors - redirectTo courses
      else {
      this.router.navigate(["/courses"]);
      return true;
      }
      }

      // if you already logged and just navigate between pages
      else if (this.authUserService.isLoggedIn )
      return true;

      else {
      this.router.navigate(["**"]);
      return false;
      }
      }

      canActivateChild(route: ActivatedRouteSnapshot,state:
      RouterStateSnapshot): boolean |
      Observable<boolean> | Promise<boolean> {
      return this.canActivate(route, state);
      }





      auth-user.service.ts






      export class AuthUserService {

      private user: IUser;
      public errorMessage: string;
      public isLoggedIn: boolean = false;

      constructor(private userService: UserService) { }

      // store the session and call http get
      login(id: number) {
      this.userService.getUser(id).subscribe(
      user => {
      this.user = user;
      localStorage.setItem('user', JSON.stringify(this.user));
      this.isLoggedIn = true;
      },
      error => this.errorMessage = <any>error
      );
      }

      // clear session
      logout() {
      localStorage.removeItem('user');
      this.isLoggedIn = false;
      }
      }








      // Routing array - set routes to each html page
      const appRoutes: Routes = [
      { path: 'login/:id', redirectTo:'/courses', canActivate: [AuthGuard] },
      { path: '', canActivate: [AuthGuard], canActivateChild: [AuthGuard], children: [
      { path: '', redirectTo: '/courses', pathMatch: 'full' },
      { path: 'courses', component: CourseListComponent, pathMatch: 'full'},
      { path: 'courses/:courseId', component: CourseDetailComponent, pathMatch: 'full' },
      { path: 'courses/:courseId/unit/:unitId', component: CoursePlayComponent,
      children: [
      { path: '', component: CourseListComponent },
      { path: 'lesson/:lessonId', component: CourseLessonComponent, data:{ type: 'lesson'} },
      { path: 'quiz/:quizId', component: CourseQuizComponent, data: {type: 'quiz'} }
      ]}
      ]},
      { path: '**', component: PageNotFoundComponent, pathMatch: 'full' }];





      // Routing array - set routes to each html page
      const appRoutes: Routes = [
      { path: 'login/:id', redirectTo:'/courses', canActivate: [AuthGuard] },
      { path: '', canActivate: [AuthGuard], canActivateChild: [AuthGuard], children: [
      { path: '', redirectTo: '/courses', pathMatch: 'full' },
      { path: 'courses', component: CourseListComponent, pathMatch: 'full'},
      { path: 'courses/:courseId', component: CourseDetailComponent, pathMatch: 'full' },
      { path: 'courses/:courseId/unit/:unitId', component: CoursePlayComponent,
      children: [
      { path: '', component: CourseListComponent },
      { path: 'lesson/:lessonId', component: CourseLessonComponent, data:{ type: 'lesson'} },
      { path: 'quiz/:quizId', component: CourseQuizComponent, data: {type: 'quiz'} }
      ]}
      ]},
      { path: '**', component: PageNotFoundComponent, pathMatch: 'full' }];





           // what we'll use in production and testing
      canActivate(route: ActivatedRouteSnapshot, state:
      RouterStateSnapshot): boolean |
      Observable<boolean> | Promise<boolean> {
      // save the id from route snapshot
      const id = route.params.id;

      // if you try to logged with id
      if (id) {
      this.authUserService.login(id);

      // if there was error with HttpClient - return false
      if (this.authUserService.errorMessage) {
      this.router.navigate(["**"]);
      return false;
      }

      // there wasn't any errors - redirectTo courses
      else {
      this.router.navigate(["/courses"]);
      return true;
      }
      }

      // if you already logged and just navigate between pages
      else if (this.authUserService.isLoggedIn )
      return true;

      else {
      this.router.navigate(["**"]);
      return false;
      }
      }

      canActivateChild(route: ActivatedRouteSnapshot,state:
      RouterStateSnapshot): boolean |
      Observable<boolean> | Promise<boolean> {
      return this.canActivate(route, state);
      }





           // what we'll use in production and testing
      canActivate(route: ActivatedRouteSnapshot, state:
      RouterStateSnapshot): boolean |
      Observable<boolean> | Promise<boolean> {
      // save the id from route snapshot
      const id = route.params.id;

      // if you try to logged with id
      if (id) {
      this.authUserService.login(id);

      // if there was error with HttpClient - return false
      if (this.authUserService.errorMessage) {
      this.router.navigate(["**"]);
      return false;
      }

      // there wasn't any errors - redirectTo courses
      else {
      this.router.navigate(["/courses"]);
      return true;
      }
      }

      // if you already logged and just navigate between pages
      else if (this.authUserService.isLoggedIn )
      return true;

      else {
      this.router.navigate(["**"]);
      return false;
      }
      }

      canActivateChild(route: ActivatedRouteSnapshot,state:
      RouterStateSnapshot): boolean |
      Observable<boolean> | Promise<boolean> {
      return this.canActivate(route, state);
      }





      export class AuthUserService {

      private user: IUser;
      public errorMessage: string;
      public isLoggedIn: boolean = false;

      constructor(private userService: UserService) { }

      // store the session and call http get
      login(id: number) {
      this.userService.getUser(id).subscribe(
      user => {
      this.user = user;
      localStorage.setItem('user', JSON.stringify(this.user));
      this.isLoggedIn = true;
      },
      error => this.errorMessage = <any>error
      );
      }

      // clear session
      logout() {
      localStorage.removeItem('user');
      this.isLoggedIn = false;
      }
      }





      export class AuthUserService {

      private user: IUser;
      public errorMessage: string;
      public isLoggedIn: boolean = false;

      constructor(private userService: UserService) { }

      // store the session and call http get
      login(id: number) {
      this.userService.getUser(id).subscribe(
      user => {
      this.user = user;
      localStorage.setItem('user', JSON.stringify(this.user));
      this.isLoggedIn = true;
      },
      error => this.errorMessage = <any>error
      );
      }

      // clear session
      logout() {
      localStorage.removeItem('user');
      this.isLoggedIn = false;
      }
      }






      angular typescript authentication parameters routing






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 15 hours ago

























      asked 22 hours ago









      Ofir Sasson

      6710




      6710
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote













          change this line:



          const id = route.params.id;


          to



          const id = +route.params.id; // to convert from string to number (it's string from route params)


          and one more thing, I'm not sure you should navigate to a page not found like you did ['**']



          instead do this: ['/page_not_found']



          now I know that 'page_not_found' does not exist in your route but that's the point,
          because of it, the user will be redirected to a page not found as you wanted






          share|improve this answer





















            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














             

            draft saved


            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53138922%2fangular-6-guard-on-all-routes-is-not-working%23new-answer', 'question_page');
            }
            );

            Post as a guest
































            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            0
            down vote













            change this line:



            const id = route.params.id;


            to



            const id = +route.params.id; // to convert from string to number (it's string from route params)


            and one more thing, I'm not sure you should navigate to a page not found like you did ['**']



            instead do this: ['/page_not_found']



            now I know that 'page_not_found' does not exist in your route but that's the point,
            because of it, the user will be redirected to a page not found as you wanted






            share|improve this answer

























              up vote
              0
              down vote













              change this line:



              const id = route.params.id;


              to



              const id = +route.params.id; // to convert from string to number (it's string from route params)


              and one more thing, I'm not sure you should navigate to a page not found like you did ['**']



              instead do this: ['/page_not_found']



              now I know that 'page_not_found' does not exist in your route but that's the point,
              because of it, the user will be redirected to a page not found as you wanted






              share|improve this answer























                up vote
                0
                down vote










                up vote
                0
                down vote









                change this line:



                const id = route.params.id;


                to



                const id = +route.params.id; // to convert from string to number (it's string from route params)


                and one more thing, I'm not sure you should navigate to a page not found like you did ['**']



                instead do this: ['/page_not_found']



                now I know that 'page_not_found' does not exist in your route but that's the point,
                because of it, the user will be redirected to a page not found as you wanted






                share|improve this answer












                change this line:



                const id = route.params.id;


                to



                const id = +route.params.id; // to convert from string to number (it's string from route params)


                and one more thing, I'm not sure you should navigate to a page not found like you did ['**']



                instead do this: ['/page_not_found']



                now I know that 'page_not_found' does not exist in your route but that's the point,
                because of it, the user will be redirected to a page not found as you wanted







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 14 hours ago









                Y_Moshe

                1035




                1035






























                     

                    draft saved


                    draft discarded



















































                     


                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53138922%2fangular-6-guard-on-all-routes-is-not-working%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest




















































































                    這個網誌中的熱門文章

                    Xamarin.form Move up view when keyboard appear

                    Post-Redirect-Get with Spring WebFlux and Thymeleaf

                    Anylogic : not able to use stopDelay()