Embracing GitHub Integration: Sign-in with GitHub Account using GitHub API and Firebase Authentication (Part 12) in Your Angular-15 Ionic-7 App

Welcome back to our ongoing series on building a multiplatform application with Angular-15 and Ionic-7! In our previous articles, we have covered various aspects of developing a powerful and user-friendly app. Today, we are excited to dive into Part 12, where we will explore the integration of the GitHub API with Firebase Authentication to enable seamless sign-in capabilities using GitHub accounts in our app.

Authentication is a vital component of any modern application, allowing users to securely access their personalized data and engage with the app's features. While Firebase Authentication provides a comprehensive suite of authentication methods, such as email/password, Google, and Facebook login, integrating additional platforms like GitHub can expand the reach of our app and cater to a wider user base.


In this installment, we will embark on a new chapter of our app's development journey by integrating the GitHub API with Firebase Authentication. By leveraging the GitHub API, we will enable users to sign in to our app using their GitHub accounts, eliminating the need for them to create new accounts or remember additional login credentials.

To achieve this integration, we will be utilizing Angular-15, a powerful JavaScript framework for building dynamic web applications, and Ionic-7, a robust platform for developing hybrid mobile apps. These technologies provide a seamless development experience and enable us to create applications that can run on multiple platforms with a single codebase.

Throughout this tutorial, we will guide you step-by-step through the process of integrating the GitHub API with Firebase Authentication in our Angular-15 Ionic-7 app. We will cover everything from setting up a GitHub Developer account and obtaining API keys to implementing the sign-in functionality within our app.

By the end of this article, you will have a solid understanding of how to leverage the GitHub API and Firebase Authentication to offer a seamless sign-in experience to your users. So, let's dive in and empower our app with the ability to authenticate users through their GitHub accounts!

Tutorial

Since I was working with social media and Google login authentication earlier, I discovered that GitHub login is also a provider within the firebase authentication providers. So I used the following documentation to create a GitHub login feature via firebase authentication service:

Authenticate Using GitHub with JavaScript  |  Firebase

First, I went onto the GitHub developer console Developer applications (github.com) and created a new app from scratch. This is demonstrated on the developer console under OAuth apps, in Figure 49 below:

Figure 49: Gitub OAuth Apps listed


After creating the app, I will get the Client ID and Client Secret which is demonstrated in Figure 50:

Figure 50: GitHub developer settings for the app with client id and secrets

I will copy the client id and secrets from this settings page and paste them in the firebase console where I will enable GitHub as a service provider under the Sign-in method and enter the above credentials there as demonstrated in Figure 51 below:

Figure 51: Added the Github API credentials in firebase console



Figure 52: GitHub app configuration with the callback URL and Homepage URL


Once this basic app setup is done, I will write the logic to access this GitHub authentication provider in the auth.service.ts file as follows:

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

import { GithubAuthProvider } from 'firebase/auth';

@Injectable({
  providedIn: 'root',
})
export class AuthService {

  constructor(private auth: Auth) {} //inject the auth service

  async firebaseLoginWithGithub() {
    const provider = new GithubAuthProvider();
    const user = await signInWithPopup(this.auth, provider);
    // console.log(user);
    return user;
  }

  async firebaseLogoutWithGithub() {
    const user = await signOut(this.auth);
    // console.log(user);
    return user;
  }
}

The above code defines the class AuthService that provides methods for logging in and logging out with GitHub authentication using Firebase Authentication service. The class constructor takes an instance of the Auth service as a parameter, which is then stored as a private property of the class. This allows the class methods to access the authentication service. The firebaseLoginWithGithub() method uses the GithubAuthProvider class to create an authentication provider for GitHub and then calls the signInWithPopup() method of the Auth service with the provider. This opens a pop-up window for the user to authenticate with GitHub and returns a user object once authenticated.

Similarly, the firebaseLogoutWithGithub() method calls the signOut() method of the Auth service to log out the user from the Firebase authentication service.

Next, I will import this service and use it to write the logic to login and logout via GitHub on the login.page.ts file like this:

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;
  
githubUser: any = null; // the github user object that will be returned from the github login plugin

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

//github login from auth service
  async githubLogin() {
    const user = await this.authService.firebaseLoginWithGithub();
    if (user) {
      this.githubUser = user;
      // console.log(this.githubUser);

      // 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 Github.',
        duration: 3000,
        position: 'bottom',
      });
      await toast.present();
    }
  }

  //github logout from auth service
  async githubLogout() {
    await this.authService.firebaseLogoutWithGithub();
    this.githubUser = 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 Github.',
      duration: 3000,
      position: 'bottom',
    });
    await toast.present();
  }
}

This code defines the class LoginPage that is used as a component to provide login functionality using GitHub authentication through the Firebase Authentication service. The class constructor takes an instance of the Router class, AuthService class and ToastController class as parameters. The Router class is used to navigate to other pages, AuthService class is used for authentication with Firebase Authentication service and ToastController class is used to display toast messages.

The githubLogin() method calls the firebaseLoginWithGithub() method of the AuthService class to authenticate the user with GitHub using the Firebase Authentication service. Once the user is authenticated, it sets the githubUser property of the class to the user object returned by the firebaseLoginWithGithub() method. It also displays a progress bar for 5 seconds and navigates to the tab4 page after 5 seconds. Additionally, it displays a toast message to the user indicating that they are signed in with GitHub.

The progress property is used to display the progress of the progress bar. It is initialized to 0 and is incremented by 0.01 every 50ms until it reaches 1. Once it reaches 1, it is reset to 0 after 1s. I have referred to Progress Bar | Horizontal App Progress Bar for Loading Indicator (ionicframework.com) to build the progress bar.

The githubLogout() method calls the firebaseLogoutWithGithub() method of the AuthService class to log out the user from the Firebase Authentication service. It sets the githubUser property of the class to null, navigates to the login page after 3 seconds, and displays a toast message to the user indicating that they are signed out of GitHub.

Next, I will implement the above logic to the template file login.page.html to display a GitHub login and logout button in the following way:

<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">
 
  <!-- GIthub Login -->
  <ion-card class="ion-padding">
    <ion-button
      class="ion-margin-top"
      (click)="githubLogin()"
      expand="full"
      fill="solid"
      shape="round"
      *ngIf="!githubUser"
    >
      <ion-icon slot="start" name="logo-github"></ion-icon>
      Github Login
    </ion-button>

    <ion-button
      *ngIf="githubUser"
      (click)="githubLogout()"
      expand="block"
      fill="outline"
      shape="round"
    >
      Github Logout
    </ion-button>

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

The above template code contains an ion-card element that includes a GitHub login button (<ion-button>) and an item (<ion-item>) that displays the user's avatar, display name, and email after successful login.

The ngIf directive is used to conditionally display the login button, logout button, and user details item based on the githubUser property value.

The login button is displayed when the githubUser property is null, which means that the user has not yet logged in. When the button is clicked, the githubLogin() method of the component is called to authenticate the user with GitHub through the Firebase Authentication service.

The logout button is displayed when the githubUser property is not null, meaning the user is already logged in. When the logout button is clicked, the githubLogout() method of the component is called to log out the user from the Firebase Authentication service.

The ion-avatar and ion-label elements are used to display the user's avatar image, display name, and email. The user details are obtained from the githubUser object returned by the firebaseLoginWithGithub() method of the AuthService class.

Once the above template is up and running, the GitHub login works fine as demonstrated in figures 53 and 54 below:

Figure 53: Github Login page



Figure 54: Github login success with user data


Finally all possible authentication services are integrated within the application. Obviously, there are more, like Microsoft, Yahoo, etc, but the implementation remains the same for all. It is also possible to do all the authentication without involving Firebase, i.e. by directly using the specific social media application’s API keys within the application and using the authentication guard provided by the angular framework(which I will use later on when working with a PostgreSQL database and authentication service), but firebase provides streamlined authentication without involving any kind of external capacitor plugins for social media logins.

Also, the above-created login page is supposed to be placed right on the entrance of the page but I have placed it above the profile page for testing purposes. The routes can be changed from the routing page.

Conclusion:

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

Authentication is a crucial aspect of any application, and by integrating the GitHub API with Firebase Authentication, we provided users with a convenient and secure sign-in experience. Users can now access the app using their existing GitHub accounts, eliminating the need for additional account creation or password management.

Throughout this tutorial, we guided you through the process of integrating the GitHub API with Firebase Authentication in our Angular-15 Ionic-7 app. We started by setting up a GitHub Developer account and obtaining the necessary API keys and credentials. We then delved into implementing the sign-in functionality, allowing users to authenticate themselves using their GitHub accounts.

By incorporating GitHub sign-in into your app, you not only enhance the user experience but also tap into the vast developer community that GitHub provides. Users can effortlessly sign in using their GitHub accounts, and you can leverage the GitHub API to access repositories, retrieve user information, and even interact with their GitHub data within your app.

As you move forward, consider exploring additional features and functionalities that the GitHub API offers. Utilize error handling, security measures, and optimization techniques to ensure a smooth and secure sign-in experience for your users. Stay updated with the latest developments from both GitHub and Firebase to take advantage of new enhancements and features.

We hope this tutorial has provided you with valuable insights and practical knowledge on integrating the GitHub 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 sign-in experience, enhancing engagement and fostering developer interactions within your app.

Thank you for joining us on this journey as we explored the fascinating world of app development with Angular-15, Ionic-7, GitHub API, and Firebase Authentication. Stay tuned for future installments where we will 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