Skip to content

Commit

Permalink
fix(renovate-token): fix function to renovate token bling
Browse files Browse the repository at this point in the history
  • Loading branch information
wisley7l committed Feb 23, 2024
1 parent eb4421d commit c1f8de0
Show file tree
Hide file tree
Showing 6 changed files with 53 additions and 63 deletions.
8 changes: 4 additions & 4 deletions functions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down
11 changes: 5 additions & 6 deletions functions/lib/bling-auth/create-access.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand All @@ -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 {
Expand All @@ -59,4 +59,3 @@ module.exports = function (clientId, clientSecret, code, storeId, tokenExpiratio
}
})
}

14 changes: 7 additions & 7 deletions functions/lib/bling-auth/create-auth.js
Original file line number Diff line number Diff line change
@@ -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())
Expand Down
2 changes: 1 addition & 1 deletion functions/lib/bling-auth/create-axios.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
71 changes: 31 additions & 40 deletions functions/lib/bling-auth/renovate-token.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}
}
}

10 changes: 5 additions & 5 deletions functions/routes/bling/authentication.js
Original file line number Diff line number Diff line change
@@ -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, '<<')
Expand All @@ -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)
Expand Down

0 comments on commit c1f8de0

Please sign in to comment.