UNPKG

snap-oauth-2

Version:

![Digital Identity on Blockchain](https://auth.snapxplatform.com/images/logo.svg)

106 lines (96 loc) 2.98 kB
const request = require('request') dataObject = {} class snapxauth { constructor (clientId, clientSecret, redirectUri) { dataObject.client_id = clientId dataObject.client_secret = clientSecret dataObject.redirect_uri = redirectUri dataObject.grant_type = 'authorization_code' dataObject.scope = 'offline' } getAccessToken (code) { console.log('get access token is calling') dataObject.code = code return new Promise((resolve, reject) => { if (!code) return reject('grant code is not valid') request.post( { headers: { 'content-type': 'application/json' }, url: `http://localhost:3000/oauth/token`, body: JSON.stringify(dataObject) }, function (error, response, body) { if (!body) return reject('grant code is not valid') body = JSON.parse(body) if (body.error) { return reject(body.error_description) } if (body) { return resolve(body) } } ) }) } getUserInfo (token) { return new Promise((resolve, reject) => { if (!token) return reject('access token is not valid') request.get( { headers: { Authorization: `Bearer ${token}` }, url: `http://localhost:3000/api/userinfo/` }, function (error, response, body) { console.log(body) if (!body) return reject('grant code is not valid') body = JSON.parse(body) if (body.id) return resolve(body) return reject('data not found') } ) }) } getUserData (code) { return new Promise((resolve, reject) => { if (!code) reject('grant code is not valid') this.getAccessToken(code) .then(token => { console.log('THIS IS ACCESS TOKEN ') console.log(token.access_token.value) console.log('THIS IS ACCESS TOKEN ') this.getUserInfo(token.access_token.value) .then(userData => { console.log('getting user info') return resolve(userData) }) .catch(err => { console.log('getting user info error') return reject(err) }) }) .catch(err => { return reject(err) }) }) } renewAccessToken (refresh_token) { return new Promise((resolve, reject) => { if (!refresh_token) return reject('refresh_token is not valid') request.get( { headers: { Authorization: `Bearer ${refresh_token}` }, url: `http://localhost:3000/oauth/refresh_token` }, function (error, response, body) { body = JSON.parse(body) if (body.message) { return reject(body.messsage) } if (body) return resolve(body) return reject('refresh_token not found') } ) }) } } module.exports = snapxauth