Search code examples
node.jsexpressauthenticationpassport.jspassport-google-oauth

Login persist MEAN stack and passport google strategy


I understand how to setup the Google strategy and have done it normally using session cookies but my question revolves around persisting a login state client side.

How can I show that the user is logged in/out on the client side using session cookies? Should I have an isLoggedIn variable that is set depending on the result of every request? Should I simply check if a cookie exists and set the variable or should I have an API that tells me if req.user isn't empty?


Solution

  • The first thing I do when the page is initialized is to request the currently logged in user through an API request. This request may or may not contain a valid session token with which I can find the currently logged in user in the backend. Depending on your backend implementation this can be as easy as just checking if req.user is existing on the request. In my application I need the user information anyways, so they are transfered in this request as well if and only if the request was made by a valid session.

    This way I currently use only one request to check if the user is logged in. This state can be saved in an application wide service so that you can use this information if you need it. To only check the cookies on the frontend is probably not enough. Even if you have a session cookie set in the browser, it does not mean that it is still valid for backend requests. This information can only be verified by the backend and therefore you should always check it with some kind of a request.

    Check user on angular initialization

    What I do to init the user on angular application initialization is to use APP_INITIALIZER as a dependency. It triggers a specific function of a given service during initialization process. This way the information about the login status is already there when the application has finished loading.

    export function startupServiceFactory(startupService: UserService): Function {
        return () => startupService.initUser();
    }
    @NgModule({
        imports: [...],
        providers: [..., { provide: APP_INITIALIZER, useFactory: startupServiceFactory, deps: [UserService], multi: true }, ...],
        declarations: [...],
        bootstrap: [AppComponent]
    })