Toma Tomov
Toma Tomov

Reputation: 1654

How to disable canActivate guard

After hours of searchig of where is CanActivate interface is implemented in the web app didn't find nothing. So I want to ask you is there a way to generally disable it? Cant access my url and didn't find any other redirect. It sends me to the login page every time. I am not familiar with angular so please excuse me. If you need some code example just tell me. I am not sure what I have to provide.

EDIT The routing file ( I guess ):

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { HttpClientModule } from '@angular/common/http';
import { RouterModule } from '@angular/router';
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { DataService } from './data.service';
import { PublicuserService } from './Services/publicuser.service';
import { WardmemberService } from './Services/wardmember.service';
/*import {FileUploadModule} from 'primeng/primeng';*/
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
//import { NgBootstrapFormValidationModule } from 'ng-bootstrap-form-validation';
import { AppComponent } from './app.component';
import { MyLoginComponent } from './my-login/my-login.component';
import { HeaderComponent } from './header/header.component';
import { FooterComponent } from './footer/footer.component';
import { TimelineComponent } from './timeline/timeline.component';
import { LandingPageComponent } from './landing-page/landing-page.component';
import { UserInfoComponent } from './user-info/user-info.component';
import { SubTimelineComponent } from './sub-timeline/sub-timeline.component';
import { EventComponent } from './event/event.component';
import { FriendComponent } from './friend/friend.component';
import { MemberLoginComponent } from './member-login/member-login.component';
import { JobDisplayComponent } from './job-display/job-display.component';
import { AddAdsComponent } from './add-ads/add-ads.component';
import { SearchResultComponent } from './search-result/search-result.component';
/*Social login module*/
import { SocialLoginModule, AuthServiceConfig } from "angular4-social-login";
import { FacebookLoginProvider } from "angular4-social-login";
import { NormalHeaderComponent } from './normal-header/normal-header.component';
import { Ng2FileTypeModule } from 'ng2-file-type';
import { Ng2FileSizeModule } from 'ng2-file-size';
import { PublicUserHeaderComponent } from './public-user-header/public-user-header.component';
import { PublicUserTimelineComponent } from './public-user-timeline/public-user-timeline.component';
import { PublicUserSubTimelineComponent } from './public-user-sub-timeline/public-user-sub-timeline.component';
import { AccceptPublicUserDetailsModalComponent } from './acccept-public-user-details-modal/acccept-public-user-details-modal.component';
import { PublicUserFollowingComponent } from './public-user-following/public-user-following.component';
import { WardMemberPublicProfileComponent } from './ward-member-public-profile/ward-member-public-profile.component';
import { WardMemberPublicProfileTimelineComponent } from './ward-member-public-profile-timeline/ward-member-public-profile-timeline.component';
import { WardMemberPublicProfileAboutComponent } from './ward-member-public-profile-about/ward-member-public-profile-about.component';
import { WardMemberPublicProfileFAQComponent } from './ward-member-public-profile-faq/ward-member-public-profile-faq.component';
import { WardMemberPublicProfileEventComponent } from './ward-member-public-profile-event/ward-member-public-profile-event.component';
import { WardMemberPublicProfileJobComponent } from './ward-member-public-profile-job/ward-member-public-profile-job.component';
import { SharePostComponent } from './share-post/share-post.component';
import { MomentModule } from 'angular2-moment';
import { PostfromFollowingmemberComponent } from './postfrom-followingmember/postfrom-followingmember.component';
import { ShareButtonsModule } from 'ngx-sharebuttons';
import { ShareModule } from 'ng2share/share.module';
import { SelectModule } from 'angular2-select';
import { MyMunicipalityComponent } from './my-municipality/my-municipality.component';
import { PostDetailComponent } from './post-detail/post-detail.component';
import { NgAutoCompleteModule } from "ng-auto-complete";
import { GroupComponent } from './group/group.component';
import { AddGroupMembersComponent } from './add-group-members/add-group-members.component';
import { PostDetailInfoComponent } from './post-detail-info/post-detail-info.component';
import { GroupListComponent } from './group-list/group-list.component';
import { GroupListMemberComponent } from './group-list-member/group-list-member.component';
import { UserGroupComponent } from './user-group/user-group.component';
import { GroupMembersComponent } from './group-members/group-members.component';
import { GroupMemberAboutComponent } from './group-member-about/group-member-about.component';
import { UniversalPageComponent } from './universal-page/universal-page.component';
import { Ng2CompleterModule } from "ng2-completer";
import { SliderModule } from 'ngx-slider';
import { MostAddClickReportComponent } from './most-add-click-report/most-add-click-report.component';
import { DataTableModule } from "angular2-datatable";
import { ReportComponent } from './report/report.component';
import { WardmemberPostCategoryReportComponent } from './wardmember-post-category-report/wardmember-post-category-report.component';
import { WardmemberFellowMemberGroupComponent } from './wardmember-fellow-member-group/wardmember-fellow-member-group.component';
import { WardmemberCounzlorListComponent } from './wardmember-counzlor-list/wardmember-counzlor-list.component';
import { PublicuserPostCategoryReportComponent } from './publicuser-post-category-report/publicuser-post-category-report.component';
import { PublicuserFellowMemberGroupComponent } from './publicuser-fellow-member-group/publicuser-fellow-member-group.component';
import { PublicuserCounzlorListComponent } from './publicuser-counzlor-list/publicuser-counzlor-list.component';
import { PublicuserReportComponent } from './publicuser-report/publicuser-report.component';
import { TooltipModule } from "ngx-tooltip";
import * as FusionCharts from 'fusioncharts';
import * as Charts from 'fusioncharts/fusioncharts.charts';
import * as FintTheme from 'fusioncharts/themes/fusioncharts.theme.fint';
import { FusionChartsModule } from 'angular4-fusioncharts';
import { Nl2BrPipeModule } from 'nl2br-pipe';
import { LinkyModule } from 'angular-linky';
import { AngularDateTimePickerModule } from 'angular2-datetimepicker';

import { DatePipe } from '@angular/common';
import { FollowersPostComponent } from './followers-post/followers-post.component';
import { PostDetailDisplayComponent } from './post-detail-display/post-detail-display.component';
import { FollowersPostGroupComponent } from './followers-post-group/followers-post-group.component';
FusionChartsModule.fcRoot(FusionCharts, Charts, FintTheme);
import { ImageCompressService, ResizeOptions, ImageUtilityService } from 'ng2-image-compress';
import { AngularMultiSelectModule } from 'angular2-multiselect-dropdown/angular2-multiselect-dropdown';
import { LoginServiceService } from './Services/login-service.service';
import { DataProviderService } from './Services/data-provider.service';
import { NgProgressModule } from 'ngx-progressbar';
import { DxDataGridModule, DxPieChartModule } from 'devextreme-angular';
import { LikeCategorywiseReportComponent } from './like-categorywise-report/like-categorywise-report.component';
import { InfiniteScrollModule } from 'ngx-infinite-scroll';

/*Social facebook login */
let config = new AuthServiceConfig([
  {
    id: FacebookLoginProvider.PROVIDER_ID,
    provider: new FacebookLoginProvider('487205825449125'),
  }
]);
export function provideConfig() {
  return config;
}

@NgModule({
  declarations: [
    AppComponent,
    MyLoginComponent,
    HeaderComponent,
    FooterComponent,
    TimelineComponent,
    LandingPageComponent,
    UserInfoComponent,
    SubTimelineComponent,
    EventComponent,
    FriendComponent,
    MemberLoginComponent,
    JobDisplayComponent,
    AddAdsComponent,
    SearchResultComponent,
    NormalHeaderComponent,
    PublicUserHeaderComponent,
    PublicUserTimelineComponent,
    PublicUserSubTimelineComponent,
    AccceptPublicUserDetailsModalComponent,
    PublicUserFollowingComponent,
    WardMemberPublicProfileTimelineComponent,
    WardMemberPublicProfileComponent,
    WardMemberPublicProfileAboutComponent,
    WardMemberPublicProfileFAQComponent,
    WardMemberPublicProfileEventComponent,
    WardMemberPublicProfileJobComponent,
    SharePostComponent,
    PostfromFollowingmemberComponent,
    MyMunicipalityComponent,
    PostDetailComponent,
    GroupComponent,
    AddGroupMembersComponent,
    PostDetailInfoComponent,
    GroupListComponent,
    GroupListMemberComponent,
    UserGroupComponent,
    GroupMembersComponent,
    GroupMemberAboutComponent,
    UniversalPageComponent,
    MostAddClickReportComponent,
    ReportComponent,
    WardmemberPostCategoryReportComponent,
    WardmemberFellowMemberGroupComponent,
    WardmemberCounzlorListComponent,
    PublicuserPostCategoryReportComponent,
    PublicuserFellowMemberGroupComponent,
    PublicuserCounzlorListComponent,
    PublicuserReportComponent,
    FollowersPostComponent,
    PostDetailDisplayComponent,
    FollowersPostGroupComponent,
    LikeCategorywiseReportComponent,
  ],
  imports: [
    SocialLoginModule,
    BrowserModule,
    HttpModule,
    HttpClientModule,
    FormsModule,
    ReactiveFormsModule,
    Ng2FileTypeModule,
    Ng2FileSizeModule,
    MomentModule,
    ShareModule,
    Nl2BrPipeModule,
    LinkyModule,
    NgAutoCompleteModule,
    SliderModule,
    DataTableModule,
    TooltipModule,
    Ng2CompleterModule,
    ShareButtonsModule.forRoot(),
    SelectModule,
    AngularDateTimePickerModule,
    FusionChartsModule,
    AngularMultiSelectModule,
    NgProgressModule,
    DxDataGridModule,
    DxPieChartModule,
    InfiniteScrollModule,
    //  NgBootstrapFormValidationModule.forRoot(),
    RouterModule.forRoot([
      {
        path: '',
        component: UniversalPageComponent
      },
      {
        path: 'login',
        component: MemberLoginComponent
      },
      {
        path: 'report',
        component: ReportComponent,
        children: [
          {
            path: '',
            component: WardmemberPostCategoryReportComponent
          },
          {
            path: 'wardmember-fellow-member-group',
            component: WardmemberFellowMemberGroupComponent
          },
          {
            path: 'wardmember-counzlor-list',
            component: WardmemberCounzlorListComponent
          },
          {
            path: 'most-add-click-report',
            component: MostAddClickReportComponent
          },
          {
            path: 'like-categorywise-report',
            component: LikeCategorywiseReportComponent
          },
        ]
      },
      {
        path: 'publicuser-report',
        component: PublicuserReportComponent,
        children: [
          {
            path: '',
            component: PublicuserPostCategoryReportComponent
          },
          {
            path: 'publicuser-fellow-member-group',
            component: PublicuserFellowMemberGroupComponent
          },
          {
            path: 'publicuser-counzlor-list',
            component: PublicuserCounzlorListComponent
          }
        ]
      },
      {
        path: 'user-profile',
        component: TimelineComponent,
        children: [
          {
            path: '',
            component: SubTimelineComponent
          },
          {
            path: 'followers-post',
            component: FollowersPostComponent
          },
          {
            path: 'user-info',
            component: UserInfoComponent
          },
          {
            path: 'event',
            component: EventComponent
          },
          {
            path: 'followers',
            component: FriendComponent
          },
          {
            path: 'job-display',
            component: JobDisplayComponent
          },
          {
            path: 'add-ads',
            component: AddAdsComponent
          }
        ]
      },
      // {
      //   path:'share-post',
      //   component:SharePostComponent
      // },
      {
        path: 'landing-page',
        component: LandingPageComponent
      },
      {
        path: 'my-municipality/:org_name',
        component: MyMunicipalityComponent
      },
      {
        path: 'postfrom-followingmember',
        component: PostfromFollowingmemberComponent
      },
      {
        path: 'post/:ward-name/:post_id',
        component: PostDetailComponent
      },
      {
        path: 'post-detail/:post_id',
        component: PostDetailDisplayComponent
      },
      {
        path: 'login-redirect',
        component: MyLoginComponent
      },
      {
        path: 'public-user-profile',
        component: PublicUserTimelineComponent,
        children: [
          {
            path: '',
            component: PublicUserSubTimelineComponent
          },
          {
            path: 'following',
            component: PublicUserFollowingComponent
          }
        ]
      },
      {
        path: 'search-result/:ward_name',
        component: SearchResultComponent
      },
      {
        path: 'public-user-details',
        component: AccceptPublicUserDetailsModalComponent
      },
      {
        path: 'group/:ward-name/:group-name',
        component: GroupComponent,
      },
      {
        path: 'followersPostGroup/:ward-name/:group-name',
        component: FollowersPostGroupComponent,
      },
      {
        path: 'group-members/:ward-name/:group-name',
        component: GroupMembersComponent,
      },
      {
        path: 'add-members/:group-id',
        component: AddGroupMembersComponent
      },
      {
        path: 'post-detail-info/:post_id',
        component: PostDetailInfoComponent
      },
      {
        path: 'group-list',
        component: GroupListComponent
      },
      {
        path: 'user-group/:ward-name/:group-name',
        component: UserGroupComponent
      },
      {
        path: 'group-member-about/:ward-name/:group-name',
        component: GroupMemberAboutComponent
      },
      {
        path: 'universal-page',
        component: UniversalPageComponent
      },
      {
        path: ':membercode',
        component: WardMemberPublicProfileComponent,
        children: [
          {
            path: '',
            component: WardMemberPublicProfileTimelineComponent
          },
          {
            path: 'public-about',
            component: WardMemberPublicProfileAboutComponent
          },
          {
              path: 'public-services',
              component: WardMemberPublicProfileFAQComponent
          },
          {
            path: 'public-event',
            component: WardMemberPublicProfileEventComponent
          },
          {
            path: 'public-job',
            component: WardMemberPublicProfileJobComponent
          }
        ]
      },
    ])
  ],
  providers: [
    {
      provide: AuthServiceConfig,
      useFactory: provideConfig,

    },
    DataService,
    WardmemberService,
    PublicuserService,
    DatePipe,
    ImageCompressService,
    ResizeOptions,
    LoginServiceService,
    DataProviderService,
  ],
  bootstrap: [AppComponent]
})

export class AppModule { }

Upvotes: 1

Views: 9178

Answers (4)

Dankwansere
Dankwansere

Reputation: 61

You can use the aop-routing library for this. It provides the capability to temporary remove a canactivate guard on a route for a navigation, then reverts the change back when the navigation is complete

https://js.plainenglish.io/dynamically-add-and-remove-canactivate-route-guards-in-angular-e7820ab4e061

Upvotes: 0

Arindam Dawn
Arindam Dawn

Reputation: 1969

A guard is nothing but a service (basically a class) where you can implement the CanActivate interface which returns simply true or false.

Here is the actual definition from angular.io

Interface that a class can implement to be a guard deciding if a route can be activated. If all guards return true, navigation will continue. If any guard returns false, navigation will be cancelled. If any guard returns a UrlTree, current navigation will be cancelled and a new navigation will be kicked off to the UrlTree returned from the guard.

Here is a sample Authentication Guard that I have written:

@Injectable({
      providedIn: 'root'
    })
    export class AuthGuard implements CanActivate {
      authenticated: boolean = false;

      constructor(private authService: AuthService, private router: Router) {}

      canActivate(
        next: ActivatedRouteSnapshot,
        state: RouterStateSnapshot
      ): Observable<boolean> | Promise<boolean> | boolean {
        console.log('auth guard called', 'you are trying to visit', state.url);
        this.authService.isAuthenticated.subscribe((authenticated: boolean) => {
// this is where your logic should be written
          this.authenticated = authenticated;
          console.log('auth guard is authenticated', this.authenticated);
        });
        if (this.authenticated) {
          return true;
        } else {
          // TODO save the redirect url to redirect user back to the desired url 
after authentication
          console.log('going to login page');
          this.router.navigate(['/auth/login']);
          return false;
        }
      }
    }

As you can see the CanActivate returns true if the isAuthenticated value is true and false otherwise.

If it is a big app and you are not able to find the guard service, go to your routing module file, see the guard that has been linked to that particular module.

For example in your router module file you will find something like this in your Routes array:

 {
    path: 'dashboard',
    loadChildren: () => import('./feature/dashboard/dashboard.module').then(m => m.DashboardModule),
    canActivate: [AuthGuard]
  },

Here the Auth Guard controls the view of the dashboard module. Likewise in your app, there will be a similar Guard service. You need to search for that service and check the logic in the CanActivate method.

Hope it helps!

Upvotes: 1

Reactgular
Reactgular

Reputation: 54741

After hours of searchig of where is CanActivate interface is implemented in the web app didn't find nothing.

There isn't one....

You're using a third-party library that handles logins. It is forcing the user to sign in.

https://github.com/abacritt/angularx-social-login

Upvotes: 1

Shohel
Shohel

Reputation: 3934

Try to return false

canActivate(): boolean {
   return false;
}

The following link is the implementation of canActivate https://medium.com/@ryanchenkie_40935/angular-authentication-using-route-guards-bf7a4ca13ae3

Upvotes: 1

Related Questions