Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save andremalveira/f1e59a85ac4713415a9f338c555c04d4 to your computer and use it in GitHub Desktop.
Save andremalveira/f1e59a85ac4713415a9f338c555c04d4 to your computer and use it in GitHub Desktop.
Get user data from github authenticated with firebase auth using accessToken (JWT)

Getting user data from github using (login with github) from Firebase Auth via accessToken (JWT) - Octokit

πŸ“‚ loginWithGithub
β”œβ”€β”€πŸ“„ firebase.client.ts/js
β”œβ”€β”€πŸ“„ login.with.github.ts/js

πŸ“„ firebase.client.ts/js

// npm i firebase
import firebase, { initializeApp } from 'firebase/app';
import { getAuth, GithubAuthProvider} from "firebase/auth";


const firebaseConfig = {
  apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
  authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
  databaseURL: process.env.NEXT_PUBLIC_FIREBASE_DATABASE_URL,
  projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
  storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
  appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app)
const GithubProvider = new GithubAuthProvider();

export { app, auth, GithubProvider }

πŸ“„login.with.github.ts/js

// npm i octokit
import { Octokit } from '@octokit/rest'
import { signInWithPopup, GithubAuthProvider} from "firebase/auth";
import { auth, getGithubProfile } from "./firebase.client.ts/js";

//GET GITHUB USER PROFILE
export const getGithubProfile = async (token?:string) => {
  const octokit = new Octokit({auth: token }) 
  return await octokit.users.getAuthenticated()
}
  
//LOGIN WITH GITHUB
const signInWithGithub = async () => {
  GithubProvider.addScope('read:user')
  
  return signInWithPopup(auth, GithubProvider)
  .then((result) => {
 
    const credential = GithubAuthProvider.credentialFromResult(result);
    const token = credential.accessToken; //Token OAuth (JWT)
    const user = result.user
        
    getGithubProfile(token).then( userProfile => console.log('Github Profile', userProfile))
    
    console.log('Authenticated User', user)
    
  }).catch((error) => {
     console.error('SignIn Error', errorMessage)
  });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment