Skip to content

Instantly share code, notes, and snippets.

@aaishikasb
Created January 13, 2022 06:54
Show Gist options
  • Save aaishikasb/e6ee033ca73763f2206cd541166044fa to your computer and use it in GitHub Desktop.
Save aaishikasb/e6ee033ca73763f2206cd541166044fa to your computer and use it in GitHub Desktop.
import auth0 from 'auth0-js';
class Auth {
constructor() {
this.auth0 = new auth0.WebAuth({
// Update Lines 7-9 with data from the Auth0 Dashboard of your Application
domain: '<AUTH0_DOMAIN>',
audience: 'https://<AUTH0_DOMAIN>/userinfo',
clientID: '<AUTH0_CLIENT_ID>',
redirectUri: 'http://localhost:3000/callback',
responseType: 'id_token',
scope: 'openid profile'
});
this.getProfile = this.getProfile.bind(this);
this.handleAuthentication = this.handleAuthentication.bind(this);
this.isAuthenticated = this.isAuthenticated.bind(this);
this.signIn = this.signIn.bind(this);
this.signOut = this.signOut.bind(this);
}
getProfile() {
return this.profile;
}
getIdToken() {
return this.idToken;
}
isAuthenticated() {
return new Date().getTime() < this.expiresAt;
}
signIn() {
this.auth0.authorize();
}
handleAuthentication() {
return new Promise((resolve, reject) => {
this.auth0.parseHash((err, authResult) => {
if (err) return reject(err);
if (!authResult || !authResult.idToken) {
return reject(err);
}
this.idToken = authResult.idToken;
this.profile = authResult.idTokenPayload;
// set the time that the id token will expire at
this.expiresAt = authResult.idTokenPayload.exp * 1000;
resolve();
});
})
}
signOut() {
// clear id token, profile, and expiration
this.idToken = null;
this.profile = null;
this.expiresAt = null;
this.auth0.logout({
returnTo: 'http://localhost:3000',
clientID: '<AUTH0_CLIENT_ID>',
});
}
}
const auth0Client = new Auth();
export default auth0Client;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment