Keeping the user logged in even after closing the app in an Ionic/Angular project: Best practices to retain user sessions

As a newcomer to angular/ionic, I have been given a project where the user needs to remain logged in even after closing the application unless they explicitly log out. Can anyone provide suggestions on how to modify the code below?

login.page.ts

import { AuthenticationService } from '../../services/authentication/authentication.service';
import {
    ToastController,
    AlertController,
    NavController,
    ModalController,
    Platform,
} from '@ionic/angular';
import { FormBuilder, Validators, FormGroup } from '@angular/forms';
import { ApiService } from '../../services/api/api.service';
import { Router } from '@angular/router';
import { crm, environment } from '../../../environments/environment';
import { DataService } from '../../services/data/data.service';
import { ToastService } from '../../services/toast/toast.service';
import { AlertService } from '../../services/alert/alert.service';
import { ForgotPasswordModalPage } from '../forgot-password-modal/forgot-password-modal.page';
import { Device } from '@ionic-native/device/ngx';
import { FcmService } from '../../services/fcm/fcm.service';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { LoadingService } from 'src/app/services/loading/loading.service';
import { ServerService } from 'src/app/services/server/server.service';
import * as moment from 'moment';
import { AppComponent } from '../../app.component';

@Component({
    selector: 'app-login',
    templateUrl: './login.page.html',
    styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {
    loginForm: FormGroup;
    development: boolean;
    counts: number = 0;
    platformName: string;
    settings: any;

    constructor(
        private authService: AuthenticationService,
        public formBuilder: FormBuilder,
        private api: ApiService,
        private router: Router,
        private alert: AlertService,
        private dataService: DataService,
        private toast: ToastService,
        private navCtrl: NavController,
        private modalCtrl: ModalController,
        private device: Device,
        private fcmService: FcmService,
        private splashScreen: SplashScreen,
        private loadingService: LoadingService,
        private server: ServerService,
        private alertCtrl: AlertController,
        private platform: Platform,
        private app: AppComponent,
    ) {
        this.initForm();
    }

    ngOnInit(): void {
        this.setupServerUrl();
    }

    async setSettings() {
        console.log('settings called in appcomp');
        
        // Your unique rewritten code here...

    }

    // Repeat the above process for other methods within the component

}

authentication.service.ts

import { Platform, NavController } from "@ionic/angular";
import { Injectable } from "@angular/core";
import { Storage } from "@ionic/storage";
import { BehaviorSubject } from "rxjs";
import { DataService } from "../data/data.service";
import { ObservablesService } from "../observable/observables.service";
import { SplashScreen } from "@ionic-native/splash-screen/ngx";
import { Badge } from "@ionic-native/badge/ngx";
import { ServerService } from "../server/server.service";

const TOKEN_KEY = "auth-token";

export interface OcOAuth {
  
  // Your unique rewritten code here...

}
@Injectable({
  providedIn: "root",
})
export class AuthenticationService {
  
  // Your unique rewritten code here...

}

Answer №1

Your code appears to be lengthy, making it difficult to provide direct assistance. However, I can offer an explanation on what steps you should take. Upon successful login, retrieve and store a token. When the app is opened, verify the stored token's availability. If the token exists, navigate to the main screen; otherwise, redirect to the login page.

login() {
   const attempt = login(username,pw) 
   if(attempt.status === 200) { 
   //if username and pw is correct web service must be return token
   this.storage.set("token", attempt.token)
   navigate("desired location")
} else {
   //Error when username or pw wrong.
}

If you are using Ionic framework, check the token in app.component.ts

const token = await this.storage.get("token")
const checkTokenIsAvailable = await checkToken(token)
if(checkTokenIsAvailable) {
    navigate("desired location")
    //Token is still available
} else { 
    navigate("login screen")
}

That sums it up.

Answer №2

Once the platform is fully ready in your app.component.ts file, include the following code:

if(this.authenticationService.isAuthenticated())
{
//Direct to Home Page
}
else{
//Direct to Login Page
}

Answer №3

After troubleshooting, I successfully resolved the problem with the subscribe() method. I included this code inside platfrom.ready:

this.authService.authenticationState.subscribe((state) => {
        if (state) {
          this.navCtrl.navigateRoot("/tabs/tabs/home");
        } else {
          this.navCtrl.navigateRoot("");
        }
      });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a Typescript error while attempting to utilize mongoose functions

An example of a User interface is shown below: import {Document} from "mongoose"; export interface IUser extends Document{ email: string; password: string; strategy: string; userId: string; isValidPassword(password: string): ...

The return type in Typescript for dynamically generated return values

If I have a function in Typescript 2.0 like this: doSomething(): any { const apple: Apple = ... const pears: Pear[] = ... return { apple: apple, pears: pears } } I am aware that the function will always produce an object ...

A guide to parsing a JSON Array (and not a JSON Object) on Android

I am struggling to find a way to parse a JSONArray that looks like this: [{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...] Typically, I would know how to parse JSON if it were structured differently, such as a JSON object returned instead ...

Tips for setting up a Nuxt build with TypeScript capabilities

Trying to create a Nuxt.js app by using the "npm run build" command, specifically executing "nuxt build," has become quite challenging for me. Sadly, the production build continuously fails because it seems like Nuxt is struggling with compiling Typescrip ...

Troubleshooting a unique CSS problem on an Android PhoneGap

We are currently working on an Android application using PhoneGap, HTML, CSS, and jQuery Mobile. After compiling the application in Eclipse, everything seems to work correctly. However, I am facing an issue where my CSS styles are not updating when recompi ...

Is it considered appropriate to return null in a didReceiveResponse callback function?

In my implementation, I have a callback called didReceiveResponse within a class that extends RESTDataSource. In this method, I return null when the response status is 404. However, due to the typing definition of RESTDataSource.didReceiveResponse, it seem ...

Managing the dispatch of a successful action in a component

In my component, I have a form that adds items to a list. Once an item is successfully added, I want to reset the form using form.resetForm();. However, I am struggling to determine when the action of adding the item has been successful. I attempted to sub ...

When the back button is pressed on android, the navbar does not immediately refresh the active class

When using a webapp on Chrome for Android, pressing the back button results in double active items in the navbar. Clicking outside of the navbar removes the old active item. I attempted to resolve the issue by adding [routerLinkActiveOptions]="{ exact: tr ...

Stop allowing the transmission of unfamiliar string constants, but still permit the transmission of adaptable strings

Consider the TypeScript code snippet below: const namesList = { john: 25, emma: 30, jacob: 35, } type NameType = keyof typeof namesList function getPersonAge< Name extends string, Result = Name extends NameType ? number ...

Encountering the ObjectUnsubscribedErrorImpl while utilizing angular datatable with angular version 7

I am encountering an issue when trying to display a DataTable in a modal window. Initially, everything works as expected and I can see the screen perfectly. However, after closing the modal window and opening it again, the DataTable no longer shows the sea ...

Utilize Page.evaluate() to send multiple arguments

I am facing an issue with the Playwright-TS code below. I need to pass the email id dynamically to the tester method and have it inside page.evaluate, but using email:emailId in the code throws an undefined error. apiData = { name: faker.name.firstNa ...

Battle of the Blobs: Exploring Blob Source in Google Apps Script

I've been exploring clasp, a tool that allows developers to work with Google Apps Script using TypeScript. Currently, I am working on a script that converts a Google Sheet into a PDF Blob and then uploads it to Google Drive. While the code is execut ...

"Exploring the TypeScript typing system with a focus on the typeof operator

My goal is to create a function that will return the typeof React Component, requiring it to adhere to a specific props interface. The function should return a type rather than an instance of that type. Consider the following: interface INameProps { ...

Retrieving the current time in PHP and MySQL for Android applications

I am currently working on a project involving Android, PHP, and MySQL. I have a question regarding a PHP file where I need to retrieve the current time that a user registered in the application. I plan to use "now()" in the PHP file with the datatype in t ...

Using keyof to access static properties within TypeScript classes

While experimenting with this TypeScript playground code sample, I encountered an issue with defining the greeterBuilderName variable. How can I specify that I want properties of the Greeter function itself (such as prototype, warm_greeter, etc.) when keyo ...

The Crimson Thread when incorporating tsx into Next.js

https://i.sstatic.net/zXvPT.png While working with TSX in React and TypeScript, I encountered an issue. A red line appeared on the screen even though the project runs successfully. Can anyone explain why this red line is appearing and why the classes in T ...

Enhancing django auth.models.User by adding additional attributes

When it comes to extending django's auth.models.User, the big question is whether to inherit from AbstractUser or User. In my current implementation, I am directly inheriting from User. However, I'm wondering if it would be better to have a OneTo ...

I need help understanding how to access the map[#var] when using *ngFor="var of list"

If I define a local variable using *ngFor in my template, how can I utilize it as a key to access a map? The template code shown below leads to a Parser Error: Unexpected token # at column 12 in ... <li *ngFor="#item of my_list"> <div [class]="m ...

Is there a way to retrieve the id attribute of an option element from the source component?

When a user makes a selection, I am trying to access the id attribute of the HTMLOptionElement. However, it always returns 0 instead of the actual id I passed (such as 1 or 2) from the select tag: <div class="col-8"> <select (cha ...

Using a static parameterized method to call an Intent and initiate a new activity

How can I call an Intent in a static parameterized method to start a new activity? I have a method called zodiacSign in my MainActivity with two parameters that successfully calls another activity called HoroscopeFinder. However, I now want to open a new a ...