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)
});
}