Created
January 13, 2022 06:54
-
-
Save aaishikasb/e6ee033ca73763f2206cd541166044fa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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