Comparing version 2.0.3 to 2.0.4
@@ -50,2 +50,3 @@ 'use strict'; | ||
_this._isConnected = false; | ||
_this._code = _this._options.code; | ||
return _this; | ||
@@ -57,3 +58,2 @@ } | ||
value: function connectIfNeeded() { | ||
if (!this._isConnected) { | ||
@@ -65,5 +65,3 @@ return this.connect(); | ||
var now = new Date(); | ||
if (this._request.expires && now > this._request.expires) { | ||
if (this.isRequestExpired()) { | ||
return this.refreshToken(); | ||
@@ -75,2 +73,11 @@ } | ||
}, { | ||
key: 'isRequestExpired', | ||
value: function isRequestExpired() { | ||
if (!this.getToken()) { | ||
return false; | ||
} | ||
var now = new Date(); | ||
return this._request.expires && now > this._request.expires; | ||
} | ||
}, { | ||
key: 'request', | ||
@@ -84,2 +91,3 @@ value: function request() { | ||
console.log('this._isConnected', this._isConnected); | ||
return this.connectIfNeeded().then(function () { | ||
@@ -96,2 +104,3 @@ var _request; | ||
this._request.setToken(token, tokenHandledAt); | ||
this._isConnected = !this.isRequestExpired(); | ||
return this; | ||
@@ -102,3 +111,3 @@ } | ||
value: function setCode(code) { | ||
this._options.code = code; | ||
this._code = code; | ||
return this.connect(); | ||
@@ -151,3 +160,2 @@ } | ||
redirect_uri = _options.redirect_uri, | ||
code = _options.code, | ||
data = { | ||
@@ -157,7 +165,6 @@ client_id: client_id, | ||
redirect_uri: redirect_uri, | ||
code: code, | ||
code: this._code, | ||
grant_type: 'authorization_code' | ||
}; | ||
return this._request.post(_v2.default.auth.token, data).then(function (response) { | ||
@@ -174,3 +181,2 @@ _this3.handleToken(response); | ||
this.triggerEvent('beforeRefreshToken', this); | ||
var _options2 = this._options, | ||
@@ -180,7 +186,7 @@ client_id = _options2.client_id, | ||
redirect_uri = _options2.redirect_uri, | ||
token = this._request.getToken(); | ||
token = this.getToken(); | ||
if (!token) { | ||
console.log('no token'); | ||
return; | ||
return Promise.reject('no token'); | ||
} | ||
@@ -208,2 +214,3 @@ var refresh_token = token.refresh_token, | ||
} | ||
this.triggerEvent('newToken', response); | ||
var responseAt = response.info.headers.date; | ||
@@ -218,3 +225,3 @@ this.setToken(response.data, responseAt); | ||
if (this._server) { | ||
return; | ||
return Promise.resolve; | ||
} | ||
@@ -228,3 +235,5 @@ var options = _extends({}, this._options.server, { | ||
var handleCode = new Promise(function (resolve) { | ||
server.on('code', function (code) { | ||
server.on('code', function (event) { | ||
var code = event.code; | ||
resolve(code); | ||
@@ -254,15 +263,10 @@ }); | ||
this._lastConnectionRequestAt = new Date(); | ||
var requestPromise = void 0; | ||
if (this._isConnected) { | ||
requestPromise = this.refreshToken(); | ||
} else if (this._options.code) { | ||
requestPromise = this.fetchToken(); | ||
} else if (this._options.server) { | ||
if (!this._code && this._options.server) { | ||
return this.waitUserAction(); | ||
} else { | ||
} else if (!this._code) { | ||
return; | ||
} | ||
return requestPromise.then(function (response) { | ||
return this.fetchToken().then(function (response) { | ||
var _response$data = response.data, | ||
@@ -274,2 +278,3 @@ data = _response$data === undefined ? {} : _response$data; | ||
_this6.triggerEvent('connected', _this6); | ||
_this6._isConnected = true; | ||
return true; | ||
@@ -297,4 +302,4 @@ } | ||
AmoConnection.EVENTS = ['beforeConnect', 'beforeFetchToken', 'beforeRefreshToken', 'checkToken', 'authError', 'connected', 'error']; | ||
AmoConnection.EVENTS = ['beforeConnect', 'beforeFetchToken', 'beforeRefreshToken', 'newToken', 'checkToken', 'authError', 'connected', 'error']; | ||
module.exports = AmoConnection; |
@@ -74,3 +74,6 @@ 'use strict'; | ||
} | ||
this.triggerEvent('code', code); | ||
this.triggerEvent('code', { | ||
code: code, | ||
state: state | ||
}); | ||
} | ||
@@ -77,0 +80,0 @@ }]); |
{ | ||
"name": "amocrm-js", | ||
"version": "2.0.3", | ||
"version": "2.0.4", | ||
"description": "JS Library for AmoCRM", | ||
@@ -10,3 +10,4 @@ "main": "dist/AmoCRM.js", | ||
"scripts": { | ||
"test": "npm run build && babel-node spec/run.js", | ||
"test-build": "npm run build && babel-node spec/run.js", | ||
"test": "babel-node spec/run.js", | ||
"build": "babel src -d dist" | ||
@@ -13,0 +14,0 @@ }, |
@@ -32,2 +32,6 @@ # AmoCRM | ||
## Что такое OAuth и как всё настроить? | ||
Я снял для вас отдельное видео, ознакомьтесь с основами работы нового протокола и библиотеки: https://youtu.be/eK7xYAbxJHo | ||
### Код авторизации известен | ||
@@ -248,1 +252,21 @@ | ||
``` | ||
### Сохранение авторизации между сессиями | ||
Может быть полезным сохранять авторизацию между запусками приложения. Для этого есть событие `connection:newToken`, в которое приходит новый токен при каждом сохранении. | ||
Этот токен можно сохранять куда вам удобно (БД, файлы и тд). При инициализации соединения можно заранее установить токен для восстановления авторизации: | ||
`crm.connection.setToken(currentToken, 0)` | ||
Ниже пример реализации через сохранение в файл token.json который лежит рядом со скриптом | ||
```javascript | ||
crm.on('connection:newToken', (token) => { | ||
fs.writeFileSync('./token.json', JSON.stringify(token.data)) | ||
}) | ||
try { | ||
const currentToken = require('./token.json') | ||
crm.connection.setToken(currentToken, 0) | ||
} catch (e) { | ||
// Token file not found | ||
} | ||
``` |
@@ -23,3 +23,3 @@ import AmoCRM from '../src/AmoCRM'; | ||
fit( 'should auth with server', done => { | ||
it( 'should auth with server', done => { | ||
client.connection.setState( 'helloworld' ); | ||
@@ -26,0 +26,0 @@ const url = client.connection.getAuthUrl(); |
@@ -1,2 +0,3 @@ | ||
import AmoCRM from '../dist/AmoCRM'; | ||
// import AmoCRM from '../dist/AmoCRM'; | ||
import AmoCRM from '../src/AmoCRM'; | ||
import config from './support/config'; | ||
@@ -26,2 +27,14 @@ | ||
}); | ||
it( 'should work with 2 requests', done => { | ||
const url = client.connection.getAuthUrl(); | ||
console.log({ | ||
url | ||
}); | ||
client.request.get( '/api/v4/leads' ) | ||
.then(data => { | ||
console.log({ data }); | ||
client.request.get( '/api/v4/leads' ); | ||
}) | ||
.then( done ); | ||
}, 60 * 1000 ); | ||
}); |
@@ -16,2 +16,3 @@ 'use strict'; | ||
'beforeRefreshToken', | ||
'newToken', | ||
'checkToken', | ||
@@ -30,2 +31,3 @@ 'authError', | ||
this._isConnected = false; | ||
this._code = this._options.code; | ||
} | ||
@@ -38,3 +40,2 @@ | ||
connectIfNeeded() { | ||
if ( !this._isConnected ) { | ||
@@ -46,5 +47,3 @@ return this.connect(); | ||
const now = new Date; | ||
if ( this._request.expires && now > this._request.expires ) { | ||
if ( this.isRequestExpired()) { | ||
return this.refreshToken(); | ||
@@ -56,3 +55,12 @@ } | ||
isRequestExpired() { | ||
if ( !this.getToken()) { | ||
return false; | ||
} | ||
const now = new Date; | ||
return this._request.expires && now > this._request.expires; | ||
} | ||
request( ...args ) { | ||
console.log( 'this._isConnected', this._isConnected ); | ||
return this.connectIfNeeded() | ||
@@ -67,2 +75,3 @@ .then(() => { | ||
this._request.setToken( token, tokenHandledAt ); | ||
this._isConnected = !this.isRequestExpired(); | ||
return this; | ||
@@ -72,3 +81,3 @@ } | ||
setCode( code ) { | ||
this._options.code = code; | ||
this._code = code; | ||
return this.connect(); | ||
@@ -112,3 +121,2 @@ } | ||
redirect_uri, | ||
code | ||
} = this._options, | ||
@@ -119,6 +127,5 @@ data = { | ||
redirect_uri, | ||
code, | ||
code: this._code, | ||
grant_type: 'authorization_code', | ||
}; | ||
return this._request.post( schema.auth.token, data ) | ||
@@ -138,6 +145,6 @@ .then( response => { | ||
} = this._options, | ||
token = this._request.getToken(); | ||
token = this.getToken(); | ||
if ( !token ) { | ||
console.log('no token'); | ||
return; | ||
return Promise.reject( 'no token' ); | ||
} | ||
@@ -164,2 +171,3 @@ const { refresh_token } = token, | ||
} | ||
this.triggerEvent( 'newToken', response ); | ||
const responseAt = response.info.headers.date; | ||
@@ -171,3 +179,3 @@ this.setToken( response.data, responseAt ); | ||
if ( this._server ) { | ||
return; | ||
return Promise.resolve; | ||
} | ||
@@ -182,3 +190,4 @@ const options = { | ||
const handleCode = new Promise( resolve => { | ||
server.on('code', code => { | ||
server.on('code', event => { | ||
const { code } = event; | ||
resolve( code ); | ||
@@ -207,18 +216,11 @@ }); | ||
this._lastConnectionRequestAt = new Date; | ||
let requestPromise; | ||
if ( this._isConnected ) { | ||
requestPromise = this.refreshToken(); | ||
} | ||
else if ( this._options.code ) { | ||
requestPromise = this.fetchToken(); | ||
} | ||
else if ( this._options.server ) { | ||
if ( !this._code && this._options.server ) { | ||
return this.waitUserAction(); | ||
} | ||
else { | ||
else if ( !this._code ) { | ||
return; | ||
} | ||
return requestPromise | ||
return this.fetchToken() | ||
.then( response => { | ||
@@ -229,2 +231,3 @@ const { data = {}} = response; | ||
this.triggerEvent( 'connected', this ); | ||
this._isConnected = true; | ||
return true; | ||
@@ -231,0 +234,0 @@ } |
@@ -34,3 +34,6 @@ import http from 'http'; | ||
} | ||
this.triggerEvent( 'code', code ); | ||
this.triggerEvent( 'code', { | ||
code, | ||
state | ||
}); | ||
} | ||
@@ -37,0 +40,0 @@ } |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
201054
4112
271