Reader small image

You're reading from  Angular for Enterprise Applications - Third Edition

Product typeBook
Published inJan 2024
Reading LevelExpert
PublisherPackt
ISBN-139781805127123
Edition3rd Edition
Languages
Right arrow
Author (1)
Doguhan Uluca
Doguhan Uluca
author image
Doguhan Uluca

Doguhan Uluca is a Principal Fellow at Excella in Washington, D.C., where he leads strategic initiatives and delivers critical systems. He has technical expertise in usability, mobility, performance, scalability, cybersecurity, and architecture. He is the author of the Angular for Enterprise Application Development books, has spoken at over 30 conferences, and is an Angular GDE Alumni. Doguhan has delivered solutions for Silicon Valley startups, Fortune 50 companies, and the U.S. Federal Government, and he is passionate about contributing to open-source projects and teaching.
Read more about Doguhan Uluca

Right arrow

Implementing Role-Based Navigation

In Chapter 5, Designing Authorization and Authentication, we covered how designing an effective authentication and authorization system is challenging but crucial for user satisfaction. Users expect a high standard from web authentication systems, and any errors should be clearly communicated. As applications grow, their authentication backbone should be easily maintainable and extensible to ensure a seamless user experience.

In this chapter, we will discuss the challenges of creating a great auth UX and implementing a solid baseline experience. We will continue the router-first approach to designing SPAs by implementing the auth experience of LemonMart. In Chapter 4, Creating a Router-First Line-of-Business App, we defined user roles, finished our build-out of all major routing, and completed a rough walking-skeleton navigation experience of LemonMart. This means we are well prepared to implement a role-based conditional navigation experience...

Technical requirements

The most up-to-date versions of the sample code for the book are on GitHub at the following linked repository. The repository contains the final and completed state of the code. You can verify your progress at the end of this chapter by looking for the end-of-chapter snapshot of code under the projects folder.

For Chapter 6:

  1. Clone the repository https://github.com/duluca/lemon-mart.
  2. Execute npm install on the root folder to install dependencies.
  3. You will continue building on stage8 from the last chapter:
    projects/stage7
    
  4. The end state of the project is reflected at:
    projects/stage8
    
  5. Add the stage name to any ng command to act only on that stage:
    npx ng build stage8
    

Note that the dist/stage8 folder at the root of the repository will contain the compiled result.

Beware that the source code provided in the book and the version on GitHub are likely...

Dynamic UI components and navigation

AuthService provides asynchronous auth status and user information, including a user’s name and role. We can use all this information to create a friendly and personalized user experience. In this next section, we will implement the LoginComponent so that users can enter their username and password information and attempt a login.

Implementing the login component

The LoginComponent leverages the AuthService we created and implements validation errors using reactive forms.

Remember that in app.config.ts, we provided AuthService using the class InMemoryAuthService. So, during runtime, when AuthService is injected into the LoginComponent, the in-memory service will be used.

The LoginComponent should be designed to be rendered independently of any other component because, during a routing event, if we discover that the user is not properly authenticated or authorized, we will navigate them to this component. We can...

Role-based routing using guards

This is the most elemental and important part of your application. With lazy loading, we have ensured that only the bare minimum number of assets will be loaded to enable a user to log in.

Once a user logs in, they should be routed to the appropriate landing screen as per their user role, so they’re not guessing how they need to use the application. For example, a cashier only needs access to the point of sale (POS) screen so that they can check out customers. In this case, cashiers can automatically be routed to that screen.

The following is a mock-up of the POS screen:

Figure 6.7: A POS screen mock-up

Let’s ensure users get routed to the appropriate page after logging in by updating the LoginComponent.

Update the login logic to each route per role in the function named homeRoutePerRole:

app/src/login/login.component.ts
async login(submittedForm: FormGroup) {
  ...
    this.router.navigate([
      this.redirectUrl...

A Firebase authentication recipe

We can leverage our current authentication setup and integrate it with a real authentication service. For this section, you need a free Google and Firebase account. Firebase is Google’s comprehensive mobile development platform: https://firebase.google.com. You can create a free account to host your application and leverage the Firebase authentication system.

The Firebase console, found at https://console.firebase.google.com, allows you to manage users and send a password reset email without implementing a backend for your application. Later, you can leverage Firebase functions to implement APIs in a serverless manner.

Start by adding your project to Firebase using the Firebase console:

A screenshot of a blue screen  Description automatically generated

Figure 6.8: The Firebase console

  1. Click on Add project.
  2. Provide your project name.
  3. Enable Google Analytics for your project.

It helps to create a Google Analytics account before attempting this, but it should still...

Providing a service using a factory

You can dynamically choose providers during load time, so instead of changing code to switch between authentication methods, you can parametrize environment variables so that different kinds of builds can have different authentication methods. This is especially useful when writing automated UI tests against your application, where real authentication can be difficult, if not impossible, to deal with.

First, we will create an enum in environment.ts to help define our options, and then we will use that enum to choose an auth provider during our application’s bootstrap process.

Let’s get started:

  1. Create a new enum called AuthMode:
    src/app/auth/auth.enum.ts
    export enum AuthMode {
      InMemory = 'In Memory',
      CustomServer = 'Custom Server',
      CustomGraphQL = 'Custom GraphQL',
      Firebase = 'Firebase',
    }
    
  2. Add an authMode property in environment.ts:
    src...

Summary

You should now be familiar with how to create high-quality auth experiences. In this chapter, we designed a great conditional navigation experience that you can use in your own applications, by copying the base elements to your project and implementing your own auth provider. We created a reusable UI service so that you can conveniently show alerts in the flow-control logic of your application.

We covered route guards to prevent users from stumbling onto screens they are not authorized to use, and we reaffirmed the point that the real security of your application should be implemented on the server side. You saw how you can use a factory to dynamically provide different auth providers for different environments.

Finally, we implemented a real auth provider with Firebase. In Chapter 7, Working with REST and GraphQL APIs, we will review LemonMart Server, a full-stack implementation using the minimal MEAN stack with REST and GraphQL APIs. We will complete our authentication...

Further reading

Questions

Answer the following questions as best as possible to ensure you’ve understood the key concepts from this chapter without googling anything. Do you know if you got all the answers right? Visit https://angularforenterprise.com/self-assessment for more:

  1. What is the difference between RxJS’s combineLatest and merge operators?
  2. Explain the difference between canActivate and canLoad in the context of Angular route guards.
  3. How does dynamic UI rendering improve the user experience in role-based navigation systems?
  4. What are the benefits and potential drawbacks of using a service like Firebase Authentication for user management in a web application?
  5. Describe a scenario where a service factory can be particularly useful in an Angular application.
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Angular for Enterprise Applications - Third Edition
Published in: Jan 2024Publisher: PacktISBN-13: 9781805127123
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime

Author (1)

author image
Doguhan Uluca

Doguhan Uluca is a Principal Fellow at Excella in Washington, D.C., where he leads strategic initiatives and delivers critical systems. He has technical expertise in usability, mobility, performance, scalability, cybersecurity, and architecture. He is the author of the Angular for Enterprise Application Development books, has spoken at over 30 conferences, and is an Angular GDE Alumni. Doguhan has delivered solutions for Silicon Valley startups, Fortune 50 companies, and the U.S. Federal Government, and he is passionate about contributing to open-source projects and teaching.
Read more about Doguhan Uluca