Saving User-Token securely in a NativeScript application

In my {N}-App, I am looking to create a login system for users. After a successful login, the user receives a token required for making requests. Currently, I store this token using the application-settings module. Now, I want the UI to dynamically switch between the "Login Screen" and "Personal Information" screens based on the user's login status. The features of the application are accessible even without logging in, positioning the login tab on the sidebar.

I believe the route needs to be redirected to another component or the component overlay should change depending on whether the user token is saved. Is there a way to achieve this? I assume certain configurations need to be made in the component annotation within the .ts file, which may require modification of the routing setup.

I realize that there is some redundancy in defining the tab name both in the Route and the routing directory, indicating a need for routing adjustments regardless.

One idea I had was:

//router definition
path: "Main", component: MainPage, children: [
    (appSettings.getBoolean("isLoggedIn") == true) ?
        {path:  "Login", component: LoginPage} : 
        {path: "My Account", component: LoginPage}
    ]

Unfortunately, this solution did not work as expected. Are there any other suggestions?

Edit:

Perhaps I haven't articulated my challenge clearly. My application features a sidebar with a "Login" label. When a user clicks on it and logs in, I want the "Login" label to be replaced with an "Account" link where the user can view personal information. This account access does not grant permission to new pages, so the objective is to simply swap the sidebar entry and page overlay accordingly.

Answer №1

We were able to accomplish something similar by utilizing Angular's auth guard. Check out a helpful answer here.

To set up the auth guard, you can follow this example:

@Injectable()
export class AuthGuard implements CanActivate {
    auth: any = {};
    
    constructor(private authService: AuthService, private router: Router) {}
    
    canActivate() {
        if (/*user is logged in*/) {
            this.router.navigate(['/dashboard']);
            return true;
        } else {
            this.router.navigate(['/login']);
        }
        return false;
    }
}

In your router configuration, you would implement it like this:

const routes: Routes = [
    { path: '', redirectTo: '/login', pathMatch: 'full' },
    { path: AppKeys.Paths.login, loadChildren: () => require(AppKeys.Paths.loginModule)['LoginModule'], canLoad: [AuthGuard]}
];

AFTER EDIT

If I'm understanding your issue correctly, you can achieve what you need with a simpler solution. You can utilize the routerLink directive and conditional text within the listview item, for example:

<Button text="{{ isLoggedin ? 'login' : 'personal info' }}" [nsRouterLink]="[isLoggedin ? '/login' : '/personalinfo']"></Button>

In the component, you would have an isLoggedin variable initialized with the value stored in the app settings.

This code hasn't been tested and may need adjustments (switching from button to listview item, paths, etc.), but it conveys the general idea behind the implementation :)

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

What is the best way to apply a CSS class to a ComponentRef that has been generated in Angular 5

I am attempting to dynamically add a CSS class to a component right after its creation by utilizing ViewContainerRef and ComponentFactoryResolver. My goal is to determine the class based on which other Components have already been added to myViewContainerR ...

Troubleshooting `TypeError: document.createRange is not a function` error when testing material ui popper using react-testing-library

I am currently working with a material-ui TextField that triggers the opening of a Popper when focused. My challenge now is to test this particular interaction using react-testing-library. Component: import ClickAwayListener from '@material-ui/core/ ...

Angular2: Promise Rejection: Quotes cannot be used for evaluation in this component

I'm currently working on a component in Angular that includes an input parameter: import {Component, Input} from '@angular/core'; @Component({ selector: 'comment', template: ` <div class="col-lg-6 col-md-6 ...

Guide to accessing a nested and potentially optional object property with a default value and specifying its data type

Just a simple query here... my goal is to extract data.user.roles, but there's a possibility that data may be empty. In such cases, I want an empty array as the output. Additionally, I need to specify the type of user - which in this instance is any. ...

Filtering data on objects in Angular can be achieved by utilizing the built-in

Retrieving data from the backend using this function: private fetchData(): void { this.dataService.fetchData().pipe( tap((response: any) => { this.persons = response.results; this.familyMembersTrue = this.persons.filter(x =&g ...

Is it possible to constrain generic indexed access parameters?

Consider the following scenario: type Group = | { type: "string"; payload: string; } | { type: "number"; payload: number; }; A function can be created as shown below: const groupFunction = <T exte ...

What is the best method to adjust the width of the PrimeNG ConfirmDialog widget from a logic perspective

Currently utilizing "primeng": "^11.2.0" and implementing the ConfirmDialog code below this.confirm.confirm({ header: 'Announcement', message: this.userCompany.announcement.promptMsg, acceptLabel: this.userCompany.announcement ...

Having trouble with setting an image as a background in CSS for Nativescript on iOS?

In my NativeScript app, I am trying to set an image as the background using the CSS property background-image: url("res://ic_more"). It works perfectly on Android, but unfortunately, it does not display on iOS devices. I have confirmed that the image is l ...

Having trouble uploading a pdf file into a .tsx file

As a beginner in learning TypeScript, I recently embarked on building a portfolio website using React JS and TypeScript. However, I encountered a problem when trying to import a PDF file from my images into the resume.tsx file within my project folder. htt ...

Typescript: searching for a specific type within an array of objects

The title may be a bit unclear, but I'm struggling to find a better way to explain it. I have a predefined set of classes from a third-party library that I cannot modify. The specific content of these classes is not relevant, as it's just for i ...

Guide to waiting for API responses with redux-saga

I have a React-Typescript app with backend calls using React Saga. I'm facing an issue where when one of my frontend functions makes a backend call, the next function starts executing before the previous one finishes. Currently, I'm using the SE ...

Fixing the forwardRef issue with react-router-dom and material-ui

Despite implementing the forwardRef as recommended in various posts and Material-UI website examples, I am still encountering a warning in the console that has me puzzled. I am working on setting up a drawer with a list of items that are React Router link ...

Ways to refresh ngOnInit in order to renew Interpolation

Is there a way to trigger a reset of ngOnInit() upon changing a variable? I am trying to reset ngOnInit() when the theme variable changes. Here is my code: Settings.ts export class SettingsPage implements OnInit{ phraseColor: string; ngOnInit() { ...

Modify database record when an eligible token is supplied

I have a question about the efficiency of my code, specifically line 16 (as commented). Would using $row to compare with a variable mentioned above be more efficient than writing another SQL query? When I tried using a variable and $row['field name&a ...

Why aren't my arrays' characteristics being recognized when I create an instance of this class?

There is a puzzling issue with the arrays in my class. Despite creating them, when I try to access them in another class they are not recognized, only the otherProp is visible. To make matters worse, attempting to add elements to the arrays results in an ...

Retrieve an array of specific column values from an array of objects using Typescript

How can I extract an array from an array of objects? Data var result1 = [ {id:1, name:'Sandra', type:'user', username:'sandra'}, {id:2, name:'John', type:'admin', username:'johnny2'}, ...

Error in Redux reducer file caused by an incorrect data type in action.payload

I have encountered a type error in my reducers' file where it says that my 'Property 'address' does not exist on type 'number | { connection: boolean; address: string; }'. This issue is arising in my React application while us ...

Error: Unable to access properties from an undefined source while trying to read 'reRenderOnLangChange'

I encountered an issue in my Angular project where my unit tests are failing with the following error message: TypeError: Cannot read properties of undefined (reading 'reRenderOnLangChange') at shouldListenToLangChanges (node_modules/@ngneat/tr ...

Discovering the number of items that have been filtered in isotope-layout using React and Typescript

Currently, I am utilizing the isotope-layout library within a React (Typescript) project. Although I have successfully implemented filtering on my page, I am unsure of how to retrieve the count of the filtered items. Upon loading the page, Isotope is init ...

Setting up a Typescript project using webpack

Greetings! I am looking to set up Typescript with composite config and webpack (everything worked fine with just a single tsconfig.json). I must admit that I am new to TypeScript and have been more familiar with JavaScript. My main issue is getting the des ...