Skip to content

Commit

Permalink
Removed old session handling via cookies
Browse files Browse the repository at this point in the history
  • Loading branch information
icellan committed Apr 23, 2021
1 parent c41a6d4 commit 34418d2
Show file tree
Hide file tree
Showing 4 changed files with 3 additions and 147 deletions.
1 change: 0 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ And load the module in your project:
import TonicPow from 'tonicpow-js'

const api = new TonicPow('your-api-key')
await api.auth();
```

View [examples](examples/examples.js) of using this package.
Expand Down
93 changes: 3 additions & 90 deletions lib/api-client.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,5 @@
// Load axios, cookie jar support, and tough-cookie dependencies
// axiosCookieJarSupport is applying support to axios for cookie jar management
import { apiCookieName } from './session';

const axios = require('axios');
// .default (@mrz what does this affect?)
const axios = require('axios');// .default (@mrz what does this affect?)
export const tonicAxios = axios.create();
const axiosCookieJarSupport = require('axios-cookiejar-support').default;
const tough = require('tough-cookie');

axiosCookieJarSupport(tonicAxios);
export const cookieJar = new tough.CookieJar();

// Used internally for communication from req=>resp in axios
const internalHeaderKey = 'x-user-session-token';
Expand All @@ -22,17 +12,16 @@ export const apiVersion = 'v1';
export const getOptions = function (t, useCustomSessionToken = '') {
// Set the default options and headers
const defaultOptions = {
jar: cookieJar,
withCredentials: true,
headers: {
'api_key': t.config.apiKey,
'User-Agent': 'tonicpow-js ' + pkgVersion,
},
};

// Detect custom headers
if (t.session.customHeaders) {
Object.keys(t.session.customHeaders)
.forEach((key) => {
Object.keys(t.session.customHeaders).forEach((key) => {
defaultOptions.headers[key] = t.session.customHeaders[key];
});
}
Expand Down Expand Up @@ -64,82 +53,6 @@ export const checkError = function (e) {

// This wraps axios for cookie management for API vs User session token
export const createApiClient = function (t) {
// Modify the request before sending (cookie management)
tonicAxios.interceptors.request.use((config) => {
// Are we making a request with a custom session token?
if (typeof config.headers[internalHeaderKey] !== 'undefined') {
const cookie = apiCookieName + '=' + config.headers[internalHeaderKey]
+ '; Max-Age=' + t.session.maxAge
+ '; Path=/; HttpOnly;';
config.jar.setCookie(cookie, config.url, (err) => {
if (err) {
// console.error(err.message)
throw Error(err.message);
}
});
config.headers[internalHeaderKey] = 'set';
} else if (t.session.apiToken) {
const cookie = apiCookieName + '=' + t.session.apiToken
+ '; Max-Age=' + t.session.maxAge
+ '; Path=/; HttpOnly;';
config.jar.setCookie(cookie, config.url, (err) => {
if (err) {
// console.error(err.message)
throw Error(err.message);
}
});
}

return config;
}, (e) => {
return Promise.reject(e);
});

// Modify the response after sending (cookie management)
tonicAxios.interceptors.response.use((response) => {
// Clear custom headers
t.session.customHeaders = null;

// Save the cookie for api or user
response.config.jar.getCookies(response.config.url, { allPaths: true }, (err, cookies) => {
if (err) {
// console.error(err.message)
throw Error(err.message);
}
if (cookies.length > 0) {
for (let i = 0; i < cookies.length; i++) {
if (cookies[i].key === apiCookieName) {
// Set the user cookie if header was set
if (typeof response.config.headers[internalHeaderKey] !== 'undefined') {
// If we don't have an api cookie, then this is for the api
if (t.session.apiToken) {
t.session.userToken = cookies[i].value;
} else {
t.session.apiToken = cookies[i].value;
}
} else {
t.session.apiToken = cookies[i].value;
}
break;
}
}
} else if (typeof response.config.headers[internalHeaderKey] !== 'undefined') {
const tokenSet = (
t.session.userToken.length > 0
&& response.config.headers[internalHeaderKey] === t.session.userToken
);
if (tokenSet || response.config.headers[internalHeaderKey] === 'set') {
t.session.userToken = 'delete';
}
} else {
t.session.apiToken = 'delete';
}
});
return response;
}, (e) => {
return Promise.reject(e);
});

return {
async post(path, data, sessionToken = '') {
try {
Expand Down
52 changes: 0 additions & 52 deletions lib/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,58 +14,6 @@ class TonicPow {
this.apiClient = createApiClient(this);
}

/**
* Authenticate against the backend and create a session
*
* For more information: https://docs.tonicpow.com/#632ed94a-3afd-4323-af91-bdf307a399d2
*
* @returns {Promise}
*/
async auth() {
// Fire the auth
if (!isNode) {
throw Error('cannot do this request in a web browser');
}

if (
typeof this.session.customSessionToken === 'string'
&& this.session.customSessionToken.length > 0
) {
this.session.apiToken = this.session.customSessionToken;
} else if (this.session.apiToken && this.session.apiToken.length > 0) {
// Do nothing
} else {
await this.apiClient.post(
'/auth/session',
{
api_key: this.config.apiKey,
},
);
}

return { success: this.config.environment + ' api authenticated' };
}

/**
* Initialize a new TonicPow instance and authenticate with the given api key
*
* Called like this:
* const tonicPow = TonicPow.init(apiKey, options);
*
* This is short hand for:
* const tonicPow = new TonicPow(apiKey, options);
* await tonicPow.auth();
*
* @param apiKey
* @param options
* @returns {Promise<TonicPow>}
*/
static async init(apiKey, options = {}) {
const tonicPow = new TonicPow(apiKey, options);
await tonicPow.auth();
return tonicPow;
}

/**
* createAdvertiserProfile will make a new advertiser profile
*
Expand Down
4 changes: 0 additions & 4 deletions lib/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,6 @@ export default class Config {
&& value !== this.environments.Mock.url
&& value !== this.environments.Staging.url
) {
// console.error('invalid api url', value)
// this._apiUrl = this.environments.Live.url
throw Error('invalid api url');
}
this._apiUrl = value;
Expand All @@ -88,8 +86,6 @@ export default class Config {
} else if (value === this.environments.Live.name) {
this.apiUrl = this.environments.Live.url;
} else {
// console.error('invalid environment', value)
// this.apiUrl = this.environments.Live.url
throw Error('invalid environment');
}
this._environment = value;
Expand Down

0 comments on commit 34418d2

Please sign in to comment.