From c1f8de07bd23fc53845671c2036e56f670908e09 Mon Sep 17 00:00:00 2001 From: Wisley Alves Date: Fri, 23 Feb 2024 14:49:13 -0300 Subject: [PATCH] fix(renovate-token): fix function to renovate token bling --- functions/index.js | 8 +-- functions/lib/bling-auth/create-access.js | 11 ++-- functions/lib/bling-auth/create-auth.js | 14 ++--- functions/lib/bling-auth/create-axios.js | 2 +- functions/lib/bling-auth/renovate-token.js | 71 ++++++++++------------ functions/routes/bling/authentication.js | 10 +-- 6 files changed, 53 insertions(+), 63 deletions(-) diff --git a/functions/index.js b/functions/index.js index ef86c2f..e8f0a0d 100644 --- a/functions/index.js +++ b/functions/index.js @@ -147,10 +147,10 @@ exports.updateTokens = functions.pubsub.schedule(cron).onRun(() => { console.log(`-- Sheduled update E-Com Plus tokens '${cron}'`) // update token job bling -const createAccess = require('./lib/bling-auth/renovate-token') -const queueCreateAccess = '1 */2 * * *' -exports.scheduledSyncBlingToken = functions.pubsub.schedule(queueCreateAccess).onRun(createAccess) -console.log(`-- Sheduled active access from bling '${queueCreateAccess}'`) +const updateBlingToken = require('./lib/bling-auth/renovate-token') +const cronUpdateBlingToken = '1 */2 * * *' +exports.syncBlingToken = functions.pubsub.schedule(cronUpdateBlingToken).onRun(updateBlingToken) +console.log(`-- Sheduled active access from bling '${cronUpdateBlingToken}'`) // schedule active check queues from Store API /* const checkIdleQueues = require('./lib/integration/check-idle-queues') diff --git a/functions/lib/bling-auth/create-access.js b/functions/lib/bling-auth/create-access.js index d196ff0..df67225 100644 --- a/functions/lib/bling-auth/create-access.js +++ b/functions/lib/bling-auth/create-access.js @@ -26,17 +26,17 @@ module.exports = function (clientId, clientSecret, code, storeId, tokenExpiratio .then(async (data) => { console.log('> Bling token => ', JSON.stringify(data)) if (documentRef) { - await documentRef.set({ + authenticate(data.access_token) + + documentRef.set({ ...data, storeId, clientId, clientSecret, updatedAt: Timestamp.now(), - expiredAt: Timestamp.fromMillis(now + ((data.expires_in - 300) * 1000)) + expiredAt: Timestamp.fromMillis(now + (7200 * 1000)) }).catch(console.error) - await authenticate(data.access_token) } - }) .catch(reject) } @@ -46,7 +46,7 @@ module.exports = function (clientId, clientSecret, code, storeId, tokenExpiratio .then((documentSnapshot) => { const expiredAt = documentSnapshot.get('expiredAt') if (documentSnapshot.exists && - now + tokenExpirationGap < expiredAt.toMillis() // token expires in 21600 ms + now + tokenExpirationGap < expiredAt.toMillis() // token expires in 21600 s ) { authenticate(documentSnapshot.get('access_token')) } else { @@ -59,4 +59,3 @@ module.exports = function (clientId, clientSecret, code, storeId, tokenExpiratio } }) } - diff --git a/functions/lib/bling-auth/create-auth.js b/functions/lib/bling-auth/create-auth.js index 4fe3ada..99ef83b 100644 --- a/functions/lib/bling-auth/create-auth.js +++ b/functions/lib/bling-auth/create-auth.js @@ -1,18 +1,18 @@ const url = require('url') -module.exports = (client_id, client_secret, code, storeId, refresh_token) => new Promise((resolve, reject) => { +module.exports = (clientId, clientSecret, code, storeId, refreshToken) => new Promise((resolve, reject) => { // https://developer.bling.com.br/aplicativos#fluxo-de-autoriza%C3%A7%C3%A3o - const axios = require('./create-axios')(undefined, client_id, client_secret) + const axios = require('./create-axios')(undefined, clientId, clientSecret) const request = isRetry => { const path = '/oauth/token' - console.log(`>> Create Auth path:${storeId}: ${path} - ${refresh_token}`) + console.log(`>> Create Auth with ${refreshToken ? 'refresh_token' : 'code'}`) const grandType = { - grant_type: refresh_token ? 'refresh_token' : 'authorization_code' + grant_type: refreshToken ? 'refresh_token' : 'authorization_code' } - if (refresh_token) { - grandType['refresh_token'] = refresh_token + if (refreshToken) { + grandType.refresh_token = refreshToken } else if (code) { - grandType['code'] = code + grandType.code = code } const params = new url.URLSearchParams(grandType) axios.post(path, params.toString()) diff --git a/functions/lib/bling-auth/create-axios.js b/functions/lib/bling-auth/create-axios.js index c95299e..40dec47 100644 --- a/functions/lib/bling-auth/create-axios.js +++ b/functions/lib/bling-auth/create-axios.js @@ -3,7 +3,7 @@ const axios = require('axios') module.exports = (accessToken, clientId, clientSecret) => { let headers = { } - + const baseURL = 'https://www.bling.com.br/Api/v3/' if (accessToken) { console.log('> token ', accessToken) diff --git a/functions/lib/bling-auth/renovate-token.js b/functions/lib/bling-auth/renovate-token.js index 2f3d13f..2ec3a8f 100644 --- a/functions/lib/bling-auth/renovate-token.js +++ b/functions/lib/bling-auth/renovate-token.js @@ -3,63 +3,54 @@ const { getFirestore, Timestamp } = require('firebase-admin/firestore') const firestoreColl = 'bling_tokens' module.exports = async () => { - const maxDocs = 15 - const now = Timestamp.now().toMillis() + const now = new Date() + const handleAuth = async (document) => { + const doc = document.data() + const { + clientId, + clientSecret, + refresh_token: refreshToken, + storeId + } = doc + console.log('> Renove Token Bling ', storeId) + const data = await auth(clientId, clientSecret, undefined, storeId, refreshToken) + console.log('> Bling new token => ', JSON.stringify(data)) + if (document.ref) { + return document.ref.set( + { + ...data, + updatedAt: Timestamp.fromDate(now), + expiredAt: Timestamp.fromDate(new Date(now.getTime() + 7200000)) + }, + { merge: true } + ).catch(console.error) + } + } if (firestoreColl) { const db = getFirestore() - const d = new Date(new Date().getTime() + 7200000) - console.log('data', d) + const date = new Date(new Date().getTime() + 7200000) + console.log('> ExpiredAt <= ', date) const documentSnapshot = await db.collection(firestoreColl) - .where('expiredAt', '<=', d) + .where('expiredAt', '<=', date) .orderBy('expiredAt') .get() + const { docs } = documentSnapshot console.log(`There is ${docs && docs.length} docs expiring in two hours`) - const maxExistedDocs = docs && docs.length > maxDocs + const maxExistedDocs = docs && docs.length > maxDocs ? maxDocs : (docs && docs.length) || 0 console.log('max existed docs', maxExistedDocs) if (maxExistedDocs) { for (let i = 0; i < maxExistedDocs; i++) { - const doc = docs[i].data(); - const { storeId, clientId, clientSecret, refreshToken, expiredAt, updatedAt } = doc - if (storeId) { - const documentRef = require('firebase-admin') - .firestore() - .doc(`${firestoreColl}/${storeId}`) - const handleAuth = async (clientId, clientSecret, code = undefined, storeId, refreshToken) => { - console.log('> Bling Auth02 ', storeId) - const data = await auth(clientId, clientSecret, code, storeId, refreshToken) - console.log('> Bling token => ', JSON.stringify(data)) - if (documentRef) { - return documentRef.set({ - ...data, - storeId, - clientId, - clientSecret, - updatedAt: Timestamp.fromMillis(now), - expiredAt: Timestamp.fromMillis(now + ((res.data.expires_in - 300) * 1000)) - }).catch(console.error) - } - } - if (documentRef) { - documentRef.get() - .then((documentSnapshot) => { - const hasToCreateOauth = (documentSnapshot.exists && - (now + 1000 * 60 * 60 * 2 + 1000 * 60 * 10 < expiredAt.toMillis())) - if (!hasToCreateOauth) { - handleAuth(clientId, clientSecret, code = undefined, storeId, documentSnapshot.get('refresh_token')) - } - }) - } else { - handleAuth(clientId, clientSecret, code, storeId) - } + const docRef = docs[i] + if (docRef.data()?.storeId) { + handleAuth(docRef) } } } } } - diff --git a/functions/routes/bling/authentication.js b/functions/routes/bling/authentication.js index d879892..2a9c4ea 100644 --- a/functions/routes/bling/authentication.js +++ b/functions/routes/bling/authentication.js @@ -1,9 +1,9 @@ const getAppData = require('./../../lib/store-api/get-app-data') -const Bling = require('../../lib/bling-auth/create-access') +// const Bling = require('../../lib/bling-auth/create-access') exports.get = async ({ appSdk, admin }, req, res) => { console.log('>> GET BLING') - const { body, query } = req + const { query } = req const { state, code } = query const storeId = parseInt(query.storeId, 10) console.log('>> Store: ', storeId, ' code: ', code, 'aplicativo', state, '<<') @@ -13,9 +13,9 @@ exports.get = async ({ appSdk, admin }, req, res) => { try { getAppData({ appSdk, storeId, auth }) .then(appData => { - const { client_id, client_secret } = appData - console.log('Pass variables', JSON.stringify({client_id, client_secret, code, storeId})) - const bling = new Bling(client_id, client_secret, code, storeId) + const { client_id: clienteId, client_secret: clientSecret } = appData + console.log('Pass variables', JSON.stringify({ clienteId, clientSecret, code, storeId })) + // const bling = new Bling(clienteId, clientSecret, code, storeId) setTimeout(() => { return res.status(200).redirect('https://app.e-com.plus/#/apps/edit/102418/') }, 4000)