Unlocking Twitter Integration: Leveraging Twitter API for Login with Firebase Authentication (Part 11) in Your Angular-15 Ionic-7 App

Welcome back to our ongoing series on building a multiplatform application with Angular-15 and Ionic-7! We've covered a lot of ground so far, from setting up the development environment to implementing core functionalities. Today, we're venturing into an exciting new phase as we integrate the Twitter API with Firebase Authentication to enable seamless login capabilities in our app.

Authentication plays a pivotal role in any application, ensuring that users can securely access their personalized data and interact with the app's features. While Firebase Authentication provides a comprehensive suite of authentication methods, including email/password, Google, and Facebook login, integrating additional platforms can broaden the app's reach and cater to a wider user base.


In this eleventh installment, we embark on a journey to integrate the Twitter API into our Angular-15 Ionic-7 app, leveraging its rich functionality to offer users the option to log in using their Twitter credentials. By enabling this feature, we eliminate the need for users to create new accounts or remember additional login details, providing a seamless and convenient experience.

Angular-15, a powerful JavaScript framework for building dynamic web applications, and Ionic-7, a robust platform for developing hybrid mobile apps, form the foundation of our project. Together, they offer a unified and streamlined development experience, enabling us to create applications that can run on multiple platforms using a single codebase.

Throughout this tutorial, we'll guide you through the step-by-step process of integrating the Twitter API with Firebase Authentication in our Angular-15 Ionic-7 app. We'll begin by setting up a Twitter Developer account and obtaining the necessary API keys and credentials. Next, we'll explore the Firebase Authentication system and configure it to support Twitter login.

With the foundations in place, we'll dive into the implementation details. We'll cover topics such as handling Twitter API authentication flow, retrieving user profile information, and mapping Twitter account to Firebase user accounts. Additionally, we'll address important considerations such as handling errors, implementing security measures, and optimizing the login experience.

By the end of this article, you'll have a comprehensive understanding of how to leverage the Twitter API and Firebase Authentication to empower your app with seamless Twitter login functionality. You'll be able to offer users a convenient and secure way to access your app using their existing Twitter accounts.

So, get ready to unlock the power of Twitter integration in your Angular-15 Ionic-7 app. Join us in Part 11 of our series as we delve into the intricacies of integrating the Twitter API with Firebase Authentication. Let's revolutionize the way users login to our app and take our application's functionality to new heights!

Tutorial:

Till now, I have used Firebase authentication for standard Email-Password, Google, and Facebook. Next, I will implement login by using the Twitter API. First, I will create a developer account on Use Cases, Tutorials, & Documentation | Twitter Developer Platform, deleted the existing boilerplate app on the developer portal, and create a new app which is demonstrated in Figure 43:

Figure 43: Twitter developer portal with a new standalone app


On this portal, I will access the API key and API secret Id from the keys panel within the app which is demonstrated in Figure 44:

Figure 44: App’s API key and Secret


I will copy these credentials and go back to the firebase console under authentication and sign-in method. I will add Twitter as a new provider. Then I will add the copied API key and API secret into the provider settings which is demonstrated in Figure 45:

Figure 45: Twitter provider enabled in firebase console

From this provider settings, I will copy and paste the callback URI to the User Authentication settings under Settings on the twitterr developer portal to connect the app with firebase authentication handler, which is demonstrated in Figure 46:

Figure 46: Add callback URI under app info in user authentication settings


I have used the following firebase documentation to implement this feature:

Authenticate Using Twitter in JavaScript  |  Firebase

Once this basic setup is complete, I open up my VS code editor and access the Twitter Authentication provider in my previously created auth.service.ts file like this:

import {
  Auth,
  signInWithPopup,
  signOut,
} from '@angular/fire/auth';
import { TwitterAuthProvider } from 'firebase/auth';

@Injectable({
  providedIn: 'root',
})
export class AuthService {
 
  constructor(private auth: Auth) {} //inject the auth service

  //login with twitter using firebase
  async loginWithTwitter() {
    const provider = new TwitterAuthProvider();
    const user = await signInWithPopup(this.auth, provider);
    // console.log(user);
    return user;
  }

  // logout with twitter using firebase
  async logoutWithTwitter() {
    const user = await signOut(this.auth);
    // console.log(user);
    return user;
  }
}

The above code imports necessary modules from the @angular/fire/auth and firebase/auth libraries. Specifically, it imports the Auth service from @angular/fire/auth that is used for authentication in AngularFire, as well as the TwitterAuthProvider module from firebase/auth that provides an authentication provider for Twitter. The constructor of the AuthService injects the Auth service. The loginWithTwitter() method of the AuthService initiates the Twitter authentication process by creating a new instance of the TwitterAuthProvider, and then calling the signInWithPopup() method of the Auth service, passing in the TwitterAuthProvider. This opens a pop-up window that allows the user to sign in with their Twitter credentials, and then returns the authenticated user. The logoutWithTwitter() method of the AuthService logs the user out by calling the signOut() method of the Auth service, which ends the user's authenticated session.

Next, I will import this service into the previously created login.page.ts and use it to create the logic for Twitter login and logout in the following way:

import { AuthService } from 'src/app/services/auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.page.html',
  styleUrls: ['./login.page.scss'],
  standalone: true,
  imports: [IonicModule, CommonModule, FormsModule, ReactiveFormsModule],
})
export class LoginPage implements OnInit {
  public progress = 0;
  
twitterUser: any = null; // the twitter user object that will be returned from the twitter login plugin

  constructor(
    private router: Router,
    private authService: AuthService,
    private toastCtrl: ToastController
  ) { }

// twitter login  from auth service
  async twitterLogin() {
    const user = await this.authService.loginWithTwitter();
    if (user) {
      this.twitterUser = user;
      // console.log('twitterUser', this.twitterUser);

      // display a progress bar for 5 seconds
      setInterval(() => {
        this.progress += 0.01;
        // Reset the progress bar when it reaches 100%
        // to continuously show the demo
        if (this.progress > 1) {
          setTimeout(() => {
            this.progress = 0;
          }, 1000);
        }
      }, 50);

      //navigate to the tab4 page after 5 seconds of showing the data
      setTimeout(() => {
        this.router.navigate(['/tabs/tab4']);
      }, 5000);

      //display a toast message to the user
      const toast = await this.toastCtrl.create({
        message: 'You are signed in with Twitter.',
        duration: 3000,
        position: 'bottom',
      });
      await toast.present();
    }
  }

  // twitter logout from auth service
  async twitterLogout() {
    await this.authService.logoutWithTwitter();
    this.twitterUser = null;

    //navigate to the login page
    setTimeout(() => {
      this.router.navigate(['/login']);
    }, 3000);

    //display a toast message to the user
    const toast = await this.toastCtrl.create({
      message: 'You are signed out of Twitter.',
      duration: 3000,
      position: 'bottom',
    });
    await toast.present();
  }
}

The above code has a progress variable that is initially set to 0 and a twitterUser variable that is initially set to null. The constructor of the component injects the Router, AuthService, and ToastController services. The twitterLogin() method calls the loginWithTwitter() method of the injected AuthService to initiate the Twitter login process. If the login is successful, the twitterUser variable is set to the returned user object. The method then uses setInterval() to increment the progress variable every 50 milliseconds, simulating a progress bar. When the progress reaches 100%, it resets to 0 and the method uses setTimeout() to navigate to the tab4 page after 5 seconds. The method also displays a toast message to the user using the injected ToastController. The twitterLogout() method calls the logoutWithTwitter() method of the AuthService to log the user out of Twitter. It then sets the twitterUser variable to null and uses setTimeout() to navigate to the login page after 3 seconds. The method also displays a toast message to the user using the ToastController.

Next, I will use the above logic in the template file of login.page.html like this:

<ion-header [translucent]="false">
  <ion-toolbar>
    <ion-title>Login/Sign Up</ion-title>
    <ion-progress-bar [value]="progress"></ion-progress-bar>
    <ion-buttons slot="start">
      <ion-back-button defaultHref="/"></ion-back-button>
    </ion-buttons>
    <ion-buttons slot="end">
      <ion-menu-button menu="main-menu"></ion-menu-button>
    </ion-buttons>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true" class="ion-padding">
 
  <!-- Twitter Login -->
  <ion-card class="ion-padding">
    <ion-button
      class="ion-margin-top"
      (click)="twitterLogin()"
      expand="full"
      fill="solid"
      shape="round"
      *ngIf="!twitterUser"
    >
      <ion-icon slot="start" name="logo-twitter"></ion-icon>
      Twitter Login
    </ion-button>

    <ion-button
      *ngIf="twitterUser"
      (click)="twitterLogout()"
      expand="block"
      fill="outline"
      shape="round"
    >
      Twitter Logout
    </ion-button>

    <ion-item *ngIf="twitterUser" lines="none">
      <ion-avatar slot="start">
        <img title="user" [src]="twitterUser.user.photoURL" />
      </ion-avatar>
      <ion-label>
        <p>{{twitterUser.user.displayName}}</p>
      </ion-label>
    </ion-item>
  </ion-card>
</ion-content>

In the above code, Twitter Login functionality is implemented using an IonCard component that contains an IonButton component. When clicked, the button executes the twitterLogin() function from the component's code. If a user is logged in with Twitter, the code will display a Twitter Logout button. The Twitter user's photo and display name are displayed within an IonItem component with an IonAvatar and IonLabel component. The progress bar is displayed for 5 seconds after a user logs in with Twitter, and then the page navigates to a different page within the app. The Twitter login and logout buttons display toast messages to the user to indicate whether they have signed in or signed out of Twitter. This is demonstrated in Figure 47 and 48:

Figure 47: Twitter login pop up appears


Figure 48: Twitter login successful with user data

Conclusion:

In this eleventh installment of our series on building a multiplatform application with Angular-15 and Ionic-7, we explored the integration of the Twitter API with Firebase Authentication. By leveraging the power of these tools, we enabled users to seamlessly log in to our app using their Twitter credentials.

Throughout this tutorial, we embarked on a step-by-step journey, starting with setting up a Twitter Developer account and obtaining the necessary API keys and credentials. We then dove into configuring Firebase Authentication to support Twitter login. With the foundations laid, we delved into the implementation details, covering the authentication flow, retrieving user profile information, and mapping Twitter accounts to Firebase user accounts.

By integrating the Twitter API with Firebase Authentication, we've empowered our app with a convenient and secure login experience. Users can now access the app using their existing Twitter accounts, eliminating the need for additional account creation or password management. This enhancement not only enhances the user experience but also expands the potential user base by catering to Twitter users.

As we conclude this article, it's important to note that the integration of the Twitter API with Firebase Authentication opens up a world of possibilities beyond just login functionality. You can leverage the Twitter API to implement features such as sharing content, displaying user timelines, and interacting with the Twitter platform directly from your app.

Remember to consider error handling, security measures, and optimization techniques to ensure a smooth and secure login experience for your users. Stay up-to-date with the latest updates from both Twitter and Firebase to take advantage of new features and improvements that can enhance your app further.

We hope this tutorial has provided you with valuable insights and practical knowledge on integrating the Twitter API with Firebase Authentication in your Angular-15 Ionic-7 app. By embracing the power of these technologies, you can offer users a seamless and personalized experience that encourages engagement and loyalty.

Thank you for joining us on this journey as we explored the fascinating world of app development with Angular-15, Ionic-7, Twitter API, and Firebase Authentication. Be sure to stay tuned for future installments where we'll continue to explore new features and functionalities to make our app even more robust and user-friendly.

Happy coding!

Popular Posts

Perform CRUD (Create, Read, Update, Delete) Operations using PHP, MySQL and MAMP : Part 4. My First Angular-15 Ionic-7 App

Visualize Your Data: Showcasing Interactive Charts for Numerical Data using Charts JS Library (Part 23) in Your Angular-15 Ionic-7 App

How to Build a Unit Converter for Your Baking Needs with HTML, CSS & Vanilla JavaScript