theauthapi 1.0.3 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js DELETED
@@ -1,182 +0,0 @@
1
- 'use strict'
2
-
3
- const assert = require('assert')
4
- const removeSlash = require('remove-trailing-slash')
5
- const axios = require('axios')
6
- const axiosRetry = require('axios-retry')
7
- const ms = require('ms')
8
- const version = require('./package.json').version
9
- const isString = require('lodash.isstring')
10
- const NodeCache = require('node-cache')
11
-
12
- const noop = () => {}
13
-
14
- // const axios = require('axios').default;
15
-
16
- class TheAuthAPI {
17
- /**
18
- * Initialize a new `Analytics` with your Segment project's `writeKey` and an
19
- * optional dictionary of `options`.
20
- *
21
- * @param {String} writeKey
22
- * @param {Object} [options] (optional)
23
- * @property {Number} flushAt (default: 20)
24
- * @property {Number} flushInterval (default: 10000)
25
- * @property {String} host (default: 'https://api.segment.io')
26
- * @property {Boolean} enable (default: true)
27
- */
28
-
29
- constructor (writeKey, options) {
30
- options = options || {}
31
-
32
- assert(writeKey, 'You must pass your project\'s write key.')
33
- this.queue = []
34
- this.writeKey = writeKey
35
- this.host = removeSlash(options.host || 'https://api.theauthapi.com')
36
- this.timeout = options.timeout || false
37
- this.cacheTTL = options.cacheTTL || 60
38
-
39
- Object.defineProperty(this, 'enable', {
40
- configurable: false,
41
- writable: false,
42
- enumerable: true,
43
- value: typeof options.enable === 'boolean' ? options.enable : true
44
- })
45
-
46
- axiosRetry(axios, {
47
- retries: options.retryCount || 3,
48
- retryCondition: this._isErrorRetryable,
49
- retryDelay: axiosRetry.exponentialDelay
50
- })
51
-
52
- this.cache = new NodeCache({
53
- stdTTL: this.cacheTTL,
54
- checkperiod: this.cacheTTL * 0.2,
55
- useClones: false
56
- })
57
- }
58
-
59
- _validate (key, type) {
60
- try {
61
- if (!key || !isString(key)) throw new Error('must pass a string')
62
- } catch (e) {
63
- throw e
64
- }
65
- }
66
-
67
- /**
68
- * Send a track `message`.
69
- *
70
- * @param {Object} message
71
- * @param {Function} [callback] (optional)
72
- * @return {TheAnalyticsAPI}
73
- */
74
-
75
- async authenticateAPIKey (key, callback) {
76
- this._validate(key, 'api_key')
77
-
78
- callback = callback || noop
79
-
80
- const data = {
81
- credentials: { api_key: key },
82
- timestamp: new Date().getTime(),
83
- sentAt: new Date().getTime()
84
- }
85
-
86
- const done = err => {
87
- // callbacks.forEach(callback => callback(err))
88
- callback(err, data)
89
- }
90
-
91
- const headers = {}
92
-
93
- headers['user-agent'] = `theauthapi-client-node/${version}`
94
- headers['x-api-key'] = headers['api_key'] = this.writeKey
95
-
96
- const req = {
97
- method: 'POST',
98
- url: `${this.host}/auth/authenticate`,
99
- /* auth: {
100
- username: this.writeKey
101
- }, */
102
- data,
103
- headers
104
- }
105
-
106
- if (this.timeout) {
107
- req.timeout = typeof this.timeout === 'string' ? ms(this.timeout) : this.timeout
108
- }
109
-
110
- try {
111
- const resp = await axios(req)
112
- done(resp.data)
113
- return resp.data
114
- } catch (err) {
115
- if (err.response) {
116
- const error = new Error(err.response.statusText)
117
- return done(error)
118
- }
119
-
120
- done(err)
121
- }
122
- }
123
-
124
- _isErrorRetryable (error) {
125
- // Retry Network Errors.
126
- if (axiosRetry.isNetworkError(error)) {
127
- return true
128
- }
129
-
130
- if (!error.response) {
131
- // Cannot determine if the request can be retried
132
- return false
133
- }
134
-
135
- // Retry Server Errors (5xx).
136
- if (error.response.status >= 500 && error.response.status <= 599) {
137
- return true
138
- }
139
-
140
- // Retry if rate limited.
141
- if (error.response.status === 429) {
142
- return true
143
- }
144
-
145
- return false
146
- }
147
-
148
- getCache (key) {
149
- const value = this.cache.get(key)
150
- if (value) {
151
- return Promise.resolve(value)
152
- } else {
153
-
154
- }
155
- }
156
-
157
- setCache (key, value, ttl = null) {
158
- if (ttl) this.cache.set(key, value, ttl)
159
- else this.cache.set(key, value)
160
- }
161
-
162
- delCache (keys) {
163
- this.cache.del(keys)
164
- }
165
- delCacheStartWith (startStr = '') {
166
- if (!startStr) {
167
- return
168
- }
169
-
170
- const keys = this.cache.keys()
171
- for (const key of keys) {
172
- if (key.indexOf(startStr) === 0) {
173
- this.del(key)
174
- }
175
- }
176
- }
177
- flushCache () {
178
- this.cache.flushAll()
179
- }
180
- }
181
-
182
- module.exports = TheAuthAPI
package/test.js DELETED
@@ -1,139 +0,0 @@
1
- const express = require('express')
2
- // const delay = require('delay')
3
- // const pify = require('pify')
4
- const auth = require('basic-auth').auth
5
- require('dotenv').config()
6
- const test = require('ava')
7
- const version = require('./package.json').version
8
- const TheAuthAPI = require('.')
9
- /* var sinon = require('sinon')
10
- var spy = sinon.spy
11
- var stub = sinon.stub
12
-
13
- const noop = () => {}
14
-
15
- const context = {
16
- library: {
17
- name: 'theanalyticsapi',
18
- version
19
- }
20
- }
21
-
22
- const metadata = { nodeVersion: process.versions.node }
23
- */
24
- const THE_AUTH_API_KEY = process.env.THE_AUTH_API_KEY
25
- const TEST_USERS_API_KEY = process.env.TEST_USERS_API_KEY
26
-
27
- const port = 4063
28
-
29
- const createClient = options => {
30
- options = Object.assign({
31
- host: `http://localhost:${port}`
32
- }, options)
33
-
34
- const client = new TheAuthAPI('key', options)
35
- return client
36
- }
37
-
38
- test.before.cb(t => {
39
- express()
40
- .post('/auth/authenticate', (req, res) => {
41
- const batch = req.body
42
-
43
- const { name: writeKey } = auth(req)
44
- if (!writeKey) {
45
- return res.status(400).json({
46
- error: { message: 'missing write key' }
47
- })
48
- }
49
-
50
- const ua = req.headers['user-agent']
51
- if (ua !== `theauthapi-client-node/${version}`) {
52
- return res.status(400).json({
53
- error: { message: 'invalid user-agent' }
54
- })
55
- }
56
-
57
- if (batch[0] === 'error') {
58
- return res.status(400).json({
59
- error: { message: 'error' }
60
- })
61
- }
62
-
63
- if (batch[0] === 'timeout') {
64
- return setTimeout(() => res.end(), 5000)
65
- }
66
-
67
- res.json({})
68
- })
69
- .listen(port, t.end)
70
- })
71
-
72
- test('expose a constructor', t => {
73
- t.is(typeof TheAuthAPI, 'function')
74
- })
75
- /*
76
- test('require a write key', t => {
77
- t.throws(() => new TheAuthAPI(), 'You must pass your project\'s write key.')
78
- })
79
- */
80
- test('default options', t => {
81
- const client = new TheAuthAPI('key')
82
-
83
- t.is(client.writeKey, 'key')
84
- t.is(client.host, 'https://api.theauthapi.com')
85
- })
86
-
87
- test('remove trailing slashes from `host`', t => {
88
- const client = new TheAuthAPI('key', { host: 'http://google.com///' })
89
-
90
- t.is(client.host, 'http://google.com')
91
- })
92
-
93
- test('overwrite defaults with options', t => {
94
- const client = new TheAuthAPI('key', {
95
- host: 'a'
96
- })
97
-
98
- t.is(client.host, 'a')
99
- })
100
-
101
- test('test real request', async t => {
102
- const client = new TheAuthAPI(THE_AUTH_API_KEY)
103
-
104
- t.is(client.writeKey, THE_AUTH_API_KEY)
105
- t.is(client.host, 'https://api.theauthapi.com')
106
- const response = await client.authenticateAPIKey(TEST_USERS_API_KEY)
107
-
108
- t.is(response.authenticated, true)
109
- t.is(response.customAccountId, '1234-npm')
110
- t.is(response.customMetadata.env, 'dev')
111
- })
112
-
113
- test('test real request bad key', async t => {
114
- const client = new TheAuthAPI('bad key')
115
-
116
- t.is(client.writeKey, 'bad key')
117
- t.is(client.host, 'https://api.theauthapi.com')
118
- const response = await client.authenticateAPIKey(TEST_USERS_API_KEY)
119
-
120
- t.is(response.authenticated, true)
121
- t.is(response.customAccountId, '1234-npm')
122
- t.is(response.customMetadata.env, 'dev')
123
- })
124
- test('isErrorRetryable', t => {
125
- const client = createClient()
126
-
127
- t.false(client._isErrorRetryable({}))
128
-
129
- // ETIMEDOUT is retryable as per `is-retry-allowed` (used by axios-retry in `isNetworkError`).
130
- t.true(client._isErrorRetryable({ code: 'ETIMEDOUT' }))
131
-
132
- // ECONNABORTED is not retryable as per `is-retry-allowed` (used by axios-retry in `isNetworkError`).
133
- t.false(client._isErrorRetryable({ code: 'ECONNABORTED' }))
134
-
135
- t.true(client._isErrorRetryable({ response: { status: 500 } }))
136
- t.true(client._isErrorRetryable({ response: { status: 429 } }))
137
-
138
- t.false(client._isErrorRetryable({ response: { status: 200 } }))
139
- })