generated from ecomplus/application-starter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
auth-callback.js
84 lines (72 loc) · 2.44 KB
/
auth-callback.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// E-Com Plus Procedures to register
const { procedures } = require('./../../ecom.config')
// handle Store API errors
const errorHandling = require('./../../lib/store-api/error-handling')
exports.post = ({ appSdk }, req, res) => {
const { storeId } = req
// handle callback with E-Com Plus app SDK
// https://github.com/ecomplus/application-sdk
appSdk.handleCallback(storeId, req.body)
.then(({ isNew, authenticationId }) => {
if (isNew) {
console.log(`Installing store #${storeId}`)
/**
* You may also want to send request to external server here:
return require('axios').post(`https://yourserver.com/new-ecom-store?store_id=${storeId}`, {
store_id: storeId,
authentication_id: authenticationId
})
*/
return true
}
// not new store, just refreshing access token
if (procedures.length) {
return appSdk.getAuth(storeId, authenticationId).then(auth => {
const { row, docRef } = auth
if (!row.setted_up) {
console.log(`Try saving procedures for store #${storeId}`)
/**
* You may want to be notified when app "self" data is edited:
*/
procedures[0].triggers.push({
resource: 'applications',
resource_id: row.application_id,
field: 'hidden_data'
})
// must save procedures once only
return appSdk.saveProcedures(storeId, procedures, auth)
.then(() => docRef.set({ setted_up: true }, { merge: true }))
/**
* You may want additional request to your server with tokens after store setup:
.then(() => {
return require('axios').post(`https://yourserver.com/ecom-store-setup?store_id=${storeId}`, {
store_id: storeId,
authentication_id: authenticationId,
access_token: auth.accessToken
})
})
*/
}
})
}
})
.then(() => {
// authentication tokens were updated
res.status(204)
res.end()
})
.catch(err => {
const { message, response } = err
if (response) {
errorHandling(err)
} else {
// Firestore error ?
console.error(err)
}
res.status(500)
res.send({
error: 'auth_callback_error',
message
})
})
}