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;
}
}
angular typescript authentication parameters routing
add a comment |
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;
}
}
angular typescript authentication parameters routing
add a comment |
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;
}
}
angular typescript authentication parameters routing
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
angular typescript authentication parameters routing
edited 15 hours ago
asked 22 hours ago
Ofir Sasson
6710
6710
add a comment |
add a comment |
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
add a comment |
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
add a comment |
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
add a comment |
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
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
answered 14 hours ago
Y_Moshe
1035
1035
add a comment |
add a comment |
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password