Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

amocrm-js

Package Overview
Dependencies
Maintainers
1
Versions
59
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

amocrm-js - npm Package Compare versions

Comparing version 2.0.5 to 2.0.6

29

dist/base/AmoConnection.js

@@ -87,3 +87,2 @@ 'use strict';

console.log('this._isConnected', this._isConnected);
return this.connectIfNeeded().then(function () {

@@ -98,4 +97,4 @@ var _request;

key: 'setToken',
value: function setToken(token, tokenHandledAt) {
this._request.setToken(token, tokenHandledAt);
value: function setToken(token) {
this._request.setToken(token);
this._isConnected = !this.isRequestExpired();

@@ -202,8 +201,22 @@ return this;

value: function handleToken(response) {
if (!response.data.token_type) {
var token = response.data;
if (!token.token_type) {
return;
}
this.triggerEvent('newToken', response);
var responseAt = response.info.headers.date;
this.setToken(response.data, responseAt);
if (!token.expires_at) {
var headers = response.info.headers,
responseAt = new Date(headers.date),
responseTimestamp = responseAt.getTime(),
expiresIn = token.expires_in * 1000;
token.expires_at = responseTimestamp + expiresIn;
}
var event = _extends({}, response, {
data: token
});
this.triggerEvent('newToken', event);
this.setToken(token);
}

@@ -256,3 +269,3 @@ }, {

} else if (!this._code) {
return;
return Promise.resolve(false);
}

@@ -259,0 +272,0 @@

@@ -45,7 +45,14 @@ 'use strict';

var port = this._options.port,
handler = this.handle.bind(this);
handler = this.handle.bind(this),
onListenStart = this.onListenStart.bind(this);
this._server = _http2.default.createServer(handler).listen(port);
this._server = _http2.default.createServer(handler).listen(port, onListenStart);
}
}, {
key: 'onListenStart',
value: function onListenStart() {
// const { port } = this._options;
// console.log( `listening on port ${port}` );
}
}, {
key: 'stop',

@@ -52,0 +59,0 @@ value: function stop() {

@@ -145,4 +145,3 @@ 'use strict';

/**
* @param {Array} token
* @param {Date} tokenHandledAt
* @param {Object} token
*/

@@ -152,42 +151,22 @@

key: 'setToken',
value: function setToken(token, tokenHandledAt) {
var expiresIn = token.expires_in,
responseTimestamp = new Date(tokenHandledAt) / 1000,
expiresTimestamp = responseTimestamp + expiresIn,
expires = new Date(expiresTimestamp * 1000);
this._expires = expires;
value: function setToken(token) {
this._token = token;
}
}, {
key: 'getToken',
value: function getToken() {
return this._token;
}
}, {
key: 'setCookies',
value: function setCookies(cookies) {
this._cookies = cookies;
var expiresCookie = cookies.find(function (cookie) {
return cookie.includes('expires=');
});
if (!expiresCookie) {
if (!token) {
delete this._expires;
this.triggerEvent('expires', this);
return;
}
var expires = expiresCookie.split('; ').find(function (cookie) {
return cookie.startsWith('expires=');
});
if (!expires) {
delete this._expires;
this.triggerEvent('expires', this);
if (!token.expires_at) {
var now = new Date();
this._expires = now;
return;
}
this._expires = new Date(expires.replace('expires=', ''));
this._expires = new Date(token.expires_at);
}
}, {
key: 'getToken',
value: function getToken() {
return this._token;
}
}, {
key: 'handleResponse',

@@ -200,5 +179,2 @@ value: function handleResponse(_ref) {

if (options.saveCookies && response.headers['set-cookie']) {
this.setCookies(response.headers['set-cookie']);
}
var handler = new responseHandlerClass(rawData, response);

@@ -205,0 +181,0 @@ return handler.toJSON(options);

{
"name": "amocrm-js",
"version": "2.0.5",
"version": "2.0.6",
"description": "JS Library for AmoCRM",

@@ -5,0 +5,0 @@ "main": "dist/AmoCRM.js",

@@ -215,4 +215,3 @@ # AmoCRM

6. *crm.connection.getToken()* - возвращает текущий токен авторизации
7. *crm.connection.setToken( token, responseAt )* - задаёт токен авторизации. responseAt - экземпляр Date,
когда токен был получен (это не дата истечения срока годности).
7. *crm.connection.setToken( token )* - задаёт токен авторизации. Токен должен включать поле expires_at (timestamp, когда токен истечёт)

@@ -230,2 +229,3 @@ ## Работа с событиями

7. connection:error
8. connection:newToken

@@ -259,12 +259,12 @@ Добавление обработчика:

Этот токен можно сохранять куда вам удобно (БД, файлы и тд). При инициализации соединения можно заранее установить токен для восстановления авторизации:
`crm.connection.setToken(currentToken, 0)`
`crm.connection.setToken( currentToken )`
Ниже пример реализации через сохранение в файл token.json который лежит рядом со скриптом
```javascript
crm.on('connection:newToken', (token) => {
fs.writeFileSync('./token.json', JSON.stringify(token.data))
})
crm.on( 'connection:newToken', response => {
fs.writeFileSync( './token.json', JSON.stringify( response.data ));
});
try {
const currentToken = require('./token.json')
crm.connection.setToken(currentToken, 0)
const currentToken = require( './token.json' );
crm.connection.setToken( currentToken );
} catch (e) {

@@ -271,0 +271,0 @@ // Token file not found

@@ -44,2 +44,30 @@ import AmoCRM from '../src/AmoCRM';

});
fit( 'should get new token', async done => {
const url = client.connection.getAuthUrl();
console.log({
mode: 'should restore token',
url
});
client.connection.connect();
client.on( 'connection:newToken', response => {
if ( !response.data ) {
return;
}
console.log({
token: response.data
});
done();
});
// done();
}, 60 * 1000 );
it( 'should set old token', async done => {
client.connection.setToken( config.token );
client.connection.connect();
if ( !client.connection.isRequestExpired()) {
done();
}
// done();
}, 60 * 1000 );
});

@@ -67,4 +67,4 @@ 'use strict';

setToken( token, tokenHandledAt ) {
this._request.setToken( token, tokenHandledAt );
setToken( token ) {
this._request.setToken( token );
this._isConnected = !this.isRequestExpired();

@@ -158,8 +158,22 @@ return this;

handleToken( response ) {
if ( !response.data.token_type ) {
const token = response.data;
if ( !token.token_type ) {
return;
}
this.triggerEvent( 'newToken', response );
const responseAt = response.info.headers.date;
this.setToken( response.data, responseAt );
if ( !token.expires_at ) {
const { headers } = response.info,
responseAt = new Date( headers.date ),
responseTimestamp = responseAt.getTime(),
expiresIn = token.expires_in * 1000;
token.expires_at = responseTimestamp + expiresIn;
}
const event = {
...response,
data: token
};
this.triggerEvent( 'newToken', event );
this.setToken( token );
}

@@ -209,3 +223,3 @@

else if ( !this._code ) {
return;
return Promise.resolve( false );
}

@@ -212,0 +226,0 @@

@@ -12,6 +12,12 @@ import http from 'http';

const { port } = this._options,
handler = this.handle.bind( this );
this._server = http.createServer( handler )
.listen( port );
handler = this.handle.bind( this ),
onListenStart = this.onListenStart.bind( this );
this._server = http
.createServer( handler )
.listen( port, onListenStart );
}
onListenStart() {
// const { port } = this._options;
// console.log( `listening on port ${port}` );
}
stop() {

@@ -18,0 +24,0 @@ return new Promise(( resolve, reject ) =>

@@ -88,45 +88,25 @@ 'use strict';

/**
* @param {Array} token
* @param {Date} tokenHandledAt
* @param {Object} token
*/
setToken( token, tokenHandledAt ) {
const expiresIn = token.expires_in,
responseTimestamp = new Date( tokenHandledAt ) / 1000,
expiresTimestamp = responseTimestamp + expiresIn,
expires = new Date( expiresTimestamp * 1000 );
this._expires = expires;
setToken( token ) {
this._token = token;
}
getToken() {
return this._token;
}
setCookies( cookies ) {
this._cookies = cookies;
const expiresCookie = cookies.find( cookie => cookie.includes( 'expires=' ));
if ( !expiresCookie ) {
if ( !token ) {
delete this._expires;
this.triggerEvent( 'expires', this );
return;
}
const expires = expiresCookie.split( '; ' )
.find( cookie => cookie.startsWith( 'expires=' ));
if ( !expires ) {
delete this._expires;
this.triggerEvent( 'expires', this );
if ( !token.expires_at ) {
const now = new Date;
this._expires = now;
return;
}
this._expires = new Date( expires.replace( 'expires=', '' ));
this._expires = new Date( token.expires_at );
}
getToken() {
return this._token;
}
handleResponse({ rawData, response }, options = {}) {
const { responseHandlerClass } = this.constructor;
if ( options.saveCookies && response.headers[ 'set-cookie' ]) {
this.setCookies( response.headers[ 'set-cookie' ]);
}
const handler = new responseHandlerClass( rawData, response );

@@ -133,0 +113,0 @@ return handler.toJSON( options );

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc