Hamza Khadhri
Hamza Khadhri

Reputation: 217

logged out while refeshing the page

Spent 2 days looking why the session storage becoming null when i reload the page i lost token and the current user, even when i set the uri to /loginthe session logged out, Spent much time on googling, don’t have an idea what to do…

Here is how the UserService:

..
export class UserService {

    private currentUserSubject: BehaviorSubject<JwtResponse>;
    public currentUser: Observable<JwtResponse>;
    public nameTerms = new Subject<string>();
    public name$ = this.nameTerms.asObservable();
    constructor(private http: HttpClient,
    private cookieService: CookieService) 
    {
        const memo = localStorage.getItem('currentUser');
        this.currentUserSubject = new BehaviorSubject<JwtResponse>(JSON.parse(memo));
        this.currentUser = this.currentUserSubject.asObservable();
        cookieService.set('currentUser', memo);
    }

    get currentUserValue() {
        return this.currentUserSubject.value;
    }

    login(loginForm): Observable<JwtResponse> {

        const url = `${apiUrl}/login`;
        return this.http.post<JwtResponse>(url, loginForm).pipe(
            tap(user => {
                if (user && user.token) {

                    this.cookieService.set('currentUser', JSON.stringify(user));

                    if (loginForm.remembered) {
                        localStorage.setItem('currentUser', JSON.stringify(user));
                    }        

                    this.nameTerms.next(user.name);
                    this.currentUserSubject.next(user);
                    return user;
                }
            }),
           ...............
        );
    }

And Here is the auth-guard itself:

export class AuthGuard implements CanActivate {


    constructor(
        private router: Router,
        private userService: UserService
    ) {
    }

    canActivate(
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
        const currentUser = this.userService.currentUserValue;
        if (currentUser) {
            // check if route is restricted by role
            if (route.data.roles && route.data.roles.indexOf(currentUser.role) === -1) {
                console.log(currentUser.role + "fail in " + route.data.roles);
                // role not authorised so redirect to home page
                this.router.navigate(['/']);
                return false;
            }
            // authorised so return true
            return true;
        }

        console.log("Need log in");
        // not logged in so redirect to login page with the return url{queryParams: {returnUrl: state.url}}
        this.router.navigate(['/login'], {queryParams: {returnUrl: state.url}});
        return false;
    }
}

this is my app.componenet

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'shop';
}

Upvotes: 0

Views: 69

Answers (1)

check how sessionStorage and localStorage works, here is an article about it:

https://alligator.io/js/introduction-localstorage-sessionstorage/

We will need to see how your cookieService works, and check in what part of your code you check your session, if is in your app component, or your first component as landing

Upvotes: 1

Related Questions