mirror of
https://github.com/Permissionless-Software-Foundation/bch-dex.git
synced 2026-09-22 09:11:59 -07:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
578aade39b | ||
|
|
b09890a527 | ||
|
|
a32bd840b9 | ||
|
|
0bdc232938 | ||
|
|
f543cfce73 | ||
|
|
0f5e694682 | ||
|
|
615638d705 | ||
|
|
9b46bbd7bb | ||
|
|
1b58bda5a7 | ||
|
|
c1f15a4079 | ||
|
|
18ea03a4d6 | ||
|
|
3d911d1062 | ||
|
|
935ab94159 | ||
|
|
18dad062f6 | ||
|
|
1e8fc1825c | ||
|
|
f64795706d | ||
|
|
67a9914a8b | ||
|
|
b01d15a67d | ||
|
|
e4c9d15e60 | ||
|
|
cf88fadfdc | ||
|
|
4977ae7003 | ||
|
|
f0f6970a08 | ||
|
|
fcb4acb11d | ||
|
|
28e012feb6 | ||
|
|
958c637c24 | ||
|
|
34381e6e93 | ||
|
|
8843b3e2b0 | ||
|
|
3f91653d23 |
@@ -31,24 +31,32 @@ The above software is orchestrated using [Docker](https://www.docker.com/) and D
|
||||
|
||||
Setup instructions:
|
||||
|
||||
1. Follow the direction in [this Gist](https://gist.github.com/christroutner/a39f656850dc022b60f25c9663dd1cdd) to install Node.js, Docker, and Docker Compose.
|
||||
1. Clone the repository with `git clone https://github.com/Permissionless-Software-Foundation/bch-dex` and enter it with `cd bch-dex`.
|
||||
1. Install dependencies by running `npm install`
|
||||
1. Create a wallet:
|
||||
- Follow the direction in [this Gist](https://gist.github.com/christroutner/a39f656850dc022b60f25c9663dd1cdd) to install Node.js, Docker, and Docker Compose.
|
||||
- Clone the repository with `git clone https://github.com/Permissionless-Software-Foundation/bch-dex` and enter it with `cd bch-dex`.
|
||||
- Install dependencies by running `npm install`
|
||||
- Create a wallet:
|
||||
- `cd production/scripts`
|
||||
- `node create-wallet.js`
|
||||
1. Change directory to the `production/docker` folder.
|
||||
1. Pull the Docker images down from Docker Hub: `docker-compose pull`
|
||||
1. Build the core software: `docker-compose build --no-cache`
|
||||
1. Start the Docker containers with `docker-compose up -d`
|
||||
1. Open a web browser and navigate the `http://localhost:4500`. You'll be able to see new Offers as they come in and are detected by bch-dex.
|
||||
1. To take the other side of the trade, click the `Take` button in the UI.
|
||||
1. You can add the 12-word mnemonic from the `wallet.json` file to the the web wallet, which will mirror your wallet in the UI, and allow you to perform basic wallet functions (send and receive BCH and tokens).
|
||||
- Change directory to the `production/docker` folder.
|
||||
- Pull the Docker images down from Docker Hub: `docker-compose pull`
|
||||
- Build the back end: `docker-compose build --no-cache bch-dex`
|
||||
- Build the front end: `docker-compose build --no-cache dex-ui`
|
||||
- Start the Docker containers with `docker-compose up -d`
|
||||
- It will take about 10 minutes for the bch-dex to sync with the network and display tokens for sale.
|
||||
- Open a web browser and navigate to `http://localhost:4500`.
|
||||
- You will be presented with a login screen. Click the sign-up tab, enter an email and password to create an account. This information is stored locally on bch-dex, it is not set to a third party.
|
||||
- Once logged in, you can retrieve your BCH and SLP addresses, to fund your wallet.
|
||||
|
||||
|
||||
## Blockchain Infrastructure
|
||||
|
||||
bch-dex requires a [Cash Stack](https://cashstack.info) back end in order to connect to the blockchain. By default, the Docker containers connect to [free-bch.fullstack.cash](https://free-bch.fullstack.cash/). Several community-provided servers are provided and can be [viewed here](https://consumers.psfoundation.info/consumers.json). The back end can be changed by setting the `CONSUMER_URL` environment variable in the `docker-compose.yml` file.
|
||||
|
||||
## Environment Variables
|
||||
|
||||
- `DISABLE_NEW_ACCOUNTS` - If set, only the admin user can create new accounts. The sign-up tab becomes non-functional. Useful for controlling access to your instance of bch-dex.
|
||||
- `ADMIN_PASSWORD` - Sets the password for the admin user. This can be used with the [createUser.js script](/util/users/production/createUser.js) to add new users to the system, if the `DISABLE_NEW_ACCOUNTS` env var is set.
|
||||
|
||||
## License
|
||||
|
||||
[MIT](./LICENSE.md)
|
||||
|
||||
Vendored
+3
-1
@@ -47,7 +47,8 @@ export default {
|
||||
useFullStackCash: process.env.USE_FULLSTACKCASH ? true : false,
|
||||
consumerUrl: process.env.CONSUMER_URL
|
||||
? process.env.CONSUMER_URL
|
||||
: 'https://free-bch.fullstack.cash',
|
||||
// : 'https://free-bch.fullstack.cash',
|
||||
: 'https://dev-consumer.psfoundation.info',
|
||||
// : 'https://wa-usa-bch-consumer.fullstackcash.nl',
|
||||
|
||||
// P2WDB URL that will accept API calls from the p2wdb npm library.
|
||||
@@ -184,6 +185,7 @@ export default {
|
||||
// Nostr
|
||||
nostrRelay: process.env.NOSTR_RELAY ? process.env.NOSTR_RELAY : 'wss://nostr-relay.psfoundation.info',
|
||||
nostrTopic: process.env.NOSTR_TOPIC ? process.env.NOSTR_TOPIC : 'bch-dex-test-topic-02',
|
||||
nostrGlobalFeed: process.env.NOSTR_GLOBAL_FEED ? process.env.NOSTR_GLOBAL_FEED : 'slpdex-socialmedia',
|
||||
|
||||
// Account Configuration
|
||||
disableNewAccounts: process.env.DISABLE_NEW_ACCOUNTS ? true : false,
|
||||
|
||||
@@ -70,4 +70,7 @@ EXPOSE 80
|
||||
# Copy the files built in the first container to the new NGINX container.
|
||||
COPY --from=builder /home/safeuser/bch-dex-ui-v3/build /usr/share/nginx/html
|
||||
|
||||
# Copy the NGINX configuration file.
|
||||
COPY default.conf /etc/nginx/conf.d/default.conf
|
||||
|
||||
#USER safeuser
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
server_name localhost;
|
||||
|
||||
#access_log /var/log/nginx/host.access.log main;
|
||||
|
||||
location / {
|
||||
root /usr/share/nginx/html;
|
||||
index index.html index.htm;
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
#error_page 404 /404.html;
|
||||
|
||||
# redirect server error pages to the static page /50x.html
|
||||
#
|
||||
error_page 500 502 503 504 /50x.html;
|
||||
location = /50x.html {
|
||||
root /usr/share/nginx/html;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,8 @@ import Users from './models/users.js'
|
||||
import Entries from './models/entry.js'
|
||||
import Order from './models/order.js'
|
||||
import Offer from './models/offer.js'
|
||||
import Usage from './models/usage.js'
|
||||
import SmAccount from './models/smAccount.js'
|
||||
|
||||
class LocalDB {
|
||||
constructor () {
|
||||
@@ -15,6 +17,8 @@ class LocalDB {
|
||||
this.Entry = Entries
|
||||
this.Order = Order
|
||||
this.Offer = Offer
|
||||
this.Usage = Usage
|
||||
this.SmAccount = SmAccount
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
Social Media Account Model.
|
||||
|
||||
This model is used to track content creators using the DEX
|
||||
Nostr social media channel.
|
||||
*/
|
||||
|
||||
import mongoose from 'mongoose'
|
||||
|
||||
const SmAccount = new mongoose.Schema({
|
||||
npub: { type: String, required: true },
|
||||
bchAddr: { type: String, required: true, default: '' },
|
||||
pubkey: { type: String, required: true },
|
||||
pfp: { type: String, default: '' },
|
||||
createdAt: { type: Date, default: Date.now },
|
||||
updatedAt: { type: Date, default: Date.now },
|
||||
followerCnt: { type: Number, default: 0 },
|
||||
followingCnt: { type: Number, default: 0 },
|
||||
posts: { type: Number, default: 0 },
|
||||
likes: { type: Number, default: 0 },
|
||||
comments: { type: Number, default: 0 },
|
||||
reposts: { type: Number, default: 0 }
|
||||
})
|
||||
|
||||
export default mongoose.model('smAccount', SmAccount)
|
||||
@@ -0,0 +1,15 @@
|
||||
/*
|
||||
Usage data model
|
||||
*/
|
||||
|
||||
// Global npm libraries
|
||||
import mongoose from 'mongoose'
|
||||
|
||||
const Usage = new mongoose.Schema({
|
||||
ip: { type: String },
|
||||
url: { type: String },
|
||||
method: { type: String },
|
||||
timestamp: { type: Date }
|
||||
})
|
||||
|
||||
export default mongoose.model('usage', Usage)
|
||||
@@ -12,6 +12,7 @@ class NostrAdapter {
|
||||
constructor (localConfig = { nostrRelay: '', nostrTopic: '' }) {
|
||||
this.relayWs = localConfig.nostrRelay //
|
||||
this.topic = localConfig.nostrTopic
|
||||
this.globalFeed = localConfig.nostrGlobalFeed
|
||||
|
||||
if (!this.relayWs) {
|
||||
throw new Error(
|
||||
@@ -39,6 +40,10 @@ class NostrAdapter {
|
||||
this.post = this.post.bind(this)
|
||||
this.read = this.read.bind(this)
|
||||
this.eventId2note = this.eventId2note.bind(this)
|
||||
this.pubkey2npub = this.pubkey2npub.bind(this)
|
||||
this.npub2pubkey = this.npub2pubkey.bind(this)
|
||||
this.readGlobalFeed = this.readGlobalFeed.bind(this)
|
||||
this.getFollowers = this.getFollowers.bind(this)
|
||||
}
|
||||
|
||||
// Create nostr keys.
|
||||
@@ -131,6 +136,117 @@ class NostrAdapter {
|
||||
eventId2note (eventId) {
|
||||
return nip19.noteEncode(eventId)
|
||||
}
|
||||
|
||||
// Convert a pubkey into a `npubabc..` syntax that Astral expects.
|
||||
pubkey2npub (pubkey) {
|
||||
return nip19.npubEncode(pubkey)
|
||||
}
|
||||
|
||||
npub2pubkey (npub) {
|
||||
return nip19.decode(npub)
|
||||
}
|
||||
|
||||
// Read the global feed.
|
||||
async readGlobalFeed (inObj = {}) {
|
||||
try {
|
||||
const { limit = 10 } = inObj
|
||||
|
||||
if (typeof limit !== 'number' || limit < 1) {
|
||||
throw new Error('Limit must be greater than 0')
|
||||
}
|
||||
|
||||
const relays = [this.relayWs]
|
||||
const pool = this.RelayPool(relays)
|
||||
|
||||
const nostrData = new Promise((resolve, reject) => {
|
||||
const messages = []
|
||||
|
||||
pool.on('open', (relay) => {
|
||||
// relay.subscribe('REQ', { ids: [eventId] })
|
||||
relay.subscribe('REQ', { limit, kinds: [1], '#t': [this.globalFeed] })
|
||||
})
|
||||
|
||||
pool.on('eose', (relay) => {
|
||||
relay.close()
|
||||
resolve(messages)
|
||||
})
|
||||
|
||||
pool.on('event', (relay, subId, ev) => {
|
||||
// console.log('ev: ', ev)
|
||||
|
||||
const { content, id, tags, pubkey } = ev
|
||||
|
||||
const msg = {
|
||||
content,
|
||||
id,
|
||||
tags,
|
||||
npub: this.pubkey2npub(pubkey),
|
||||
pubkey
|
||||
}
|
||||
|
||||
messages.push(msg)
|
||||
})
|
||||
})
|
||||
|
||||
const messages = await nostrData
|
||||
|
||||
return messages
|
||||
} catch (error) {
|
||||
console.log(`Error in nostr.js/readGlobalFeed() ${error.message} `)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async getFollowers (inObj = {}) {
|
||||
try {
|
||||
const { pubkey } = inObj
|
||||
|
||||
if (!pubkey || typeof pubkey !== 'string') {
|
||||
throw new Error('pubkey must be a string!')
|
||||
}
|
||||
|
||||
const relays = [this.relayWs]
|
||||
const pool = this.RelayPool(relays)
|
||||
|
||||
const nostrData = new Promise((resolve, reject) => {
|
||||
const followers = []
|
||||
|
||||
pool.on('open', (relay) => {
|
||||
// Query for kind 3 events where the target pubkey appears in tags
|
||||
// This finds all contact lists that include the target pubkey
|
||||
relay.subscribe('subid', {
|
||||
limit: 100,
|
||||
kinds: [3],
|
||||
'#p': [pubkey] // Filter by tag 'p' containing the target pubkey
|
||||
})
|
||||
})
|
||||
|
||||
pool.on('eose', relay => {
|
||||
relay.close()
|
||||
resolve(followers)
|
||||
})
|
||||
|
||||
pool.on('event', (relay, subId, ev) => {
|
||||
// Each event represents a contact list from someone who follows the target
|
||||
// The author of this event is a follower
|
||||
const follower = {
|
||||
pubkey: ev.pubkey,
|
||||
npub: this.pubkey2npub(ev.pubkey),
|
||||
contactList: ev.tags,
|
||||
createdAt: ev.created_at
|
||||
}
|
||||
|
||||
followers.push(follower)
|
||||
})
|
||||
})
|
||||
|
||||
const followers = await nostrData
|
||||
return followers
|
||||
} catch (error) {
|
||||
console.log(`Error in nostr.js/getFollowers() ${error.message} `)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default NostrAdapter
|
||||
|
||||
@@ -18,6 +18,7 @@ import OfferRouter from './offer/index.js'
|
||||
import OrderRouter from './order/index.js'
|
||||
import P2WDBRouter from './p2wdb/index.js'
|
||||
import UsageRESTController from './usage/index.js'
|
||||
import SmAccountRouter from './smAccount/index.js'
|
||||
|
||||
class RESTControllers {
|
||||
constructor (localConfig = {}) {
|
||||
@@ -86,6 +87,9 @@ class RESTControllers {
|
||||
// Attach the REST API Controllers associated with the /usage route
|
||||
const usageRESTController = new UsageRESTController(dependencies)
|
||||
usageRESTController.attach(app)
|
||||
|
||||
const smAccountRouter = new SmAccountRouter(dependencies)
|
||||
smAccountRouter.attach(app)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
/*
|
||||
REST API Controller library for the /order route
|
||||
*/
|
||||
|
||||
// const { wlogger } = require('../../../adapters/wlogger')
|
||||
|
||||
let _this
|
||||
|
||||
class SmAccountRESTControllerLib {
|
||||
constructor (localConfig = {}) {
|
||||
// Dependency Injection.
|
||||
this.adapters = localConfig.adapters
|
||||
if (!this.adapters) {
|
||||
throw new Error(
|
||||
'Instance of Adapters library required when instantiating /order REST Controller.'
|
||||
)
|
||||
}
|
||||
this.useCases = localConfig.useCases
|
||||
if (!this.useCases) {
|
||||
throw new Error(
|
||||
'Instance of Use Cases library required when instantiating /order REST Controller.'
|
||||
)
|
||||
}
|
||||
|
||||
// Encapsulate dependencies
|
||||
this.SmAccountModel = this.adapters.localdb.SmAccount
|
||||
// this.userUseCases = this.useCases.user
|
||||
|
||||
_this = this
|
||||
}
|
||||
|
||||
/**
|
||||
* @api {get} /sm/list/all/{page} List all Social Media Accounts
|
||||
* @apiPermission public
|
||||
* @apiName ListAccounts
|
||||
* @apiGroup REST Social Media Accounts
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* curl -H "Content-Type: application/json" -X GET localhost:5700/sm/list/all/0
|
||||
*
|
||||
*/
|
||||
// curl -X GET http://localhost:5700/sm/list/all/0
|
||||
async listAccounts (ctx) {
|
||||
try {
|
||||
let page = ctx.params.page
|
||||
if (!page) page = 0
|
||||
|
||||
const offers = await _this.useCases.smAccount.listAccounts(page)
|
||||
|
||||
ctx.body = offers
|
||||
} catch (err) {
|
||||
console.log('Error in listAccounts REST API handler: ', err)
|
||||
_this.handleError(ctx, err)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api {get} /sm/npub/{npub} Get Social Media Account by Npub
|
||||
* @apiPermission public
|
||||
* @apiName GetAccountByNpub
|
||||
* @apiGroup REST Social Media Accounts
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* curl -H "Content-Type: application/json" -X GET localhost:5700/sm/npub/npub1y3xq402pu9aqms3khetnt5gzm54t63pzcla56wwfmwshde0ws77qkff5gc
|
||||
*
|
||||
*/
|
||||
// curl -X GET http://localhost:5700/sm/npub/npub1y3xq402pu9aqms3khetnt5gzm54t63pzcla56wwfmwshde0ws77qkff5gc
|
||||
async getAccountByNpub (ctx) {
|
||||
try {
|
||||
const npub = ctx.params.npub
|
||||
if (!npub) {
|
||||
ctx.throw(400, 'Npub is required')
|
||||
}
|
||||
|
||||
const account = await _this.useCases.smAccount.getAccountByNpub(npub)
|
||||
|
||||
if (!account) {
|
||||
ctx.throw(404, 'Account not found')
|
||||
}
|
||||
|
||||
ctx.body = account
|
||||
} catch (err) {
|
||||
// console.log('Error in getAccountByNpub REST API handler: ', err)
|
||||
_this.handleError(ctx, err)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api {get} /sm/bchAddr/{bchAddr} Get Social Media Account by BCH address
|
||||
* @apiPermission public
|
||||
* @apiName GetAccountByBchAddr
|
||||
* @apiGroup REST Social Media Accounts
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* curl -H "Content-Type: application/json" -X GET localhost:5700/sm/bchAddr/bitcoincash:qz6lf6gpmn3secx73g7ucfcgy8mrh3sz2y2ylk643x
|
||||
*
|
||||
*/
|
||||
// curl -X GET http://localhost:5700/sm/bchAddr/bitcoincash:qz6lf6gpmn3secx73g7ucfcgy8mrh3sz2y2ylk643x
|
||||
async getAccountByBchAddr (ctx) {
|
||||
try {
|
||||
const bchAddr = ctx.params.bchAddr
|
||||
if (!bchAddr) {
|
||||
ctx.throw(400, 'BCH address is required')
|
||||
}
|
||||
|
||||
const account = await _this.useCases.smAccount.getAccountByBchAddr(bchAddr)
|
||||
|
||||
if (!account) {
|
||||
ctx.throw(404, 'Account not found')
|
||||
}
|
||||
|
||||
ctx.body = account
|
||||
} catch (err) {
|
||||
// console.log('Error in getAccountByBchAddr REST API handler: ', err)
|
||||
_this.handleError(ctx, err)
|
||||
}
|
||||
}
|
||||
|
||||
// DRY error handler
|
||||
handleError (ctx, err) {
|
||||
console.log('err', err)
|
||||
|
||||
// If an HTTP status is specified by the buisiness logic, use that.
|
||||
if (err.status) {
|
||||
if (err.message) {
|
||||
ctx.throw(err.status, err.message)
|
||||
} else {
|
||||
ctx.throw(err.status)
|
||||
}
|
||||
} else {
|
||||
// By default use a 422 error if the HTTP status is not specified.
|
||||
ctx.throw(422, err.message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default SmAccountRESTControllerLib
|
||||
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
REST API library for /order route.
|
||||
*/
|
||||
|
||||
// Public npm libraries.
|
||||
import Router from 'koa-router'
|
||||
|
||||
// Local libraries.
|
||||
import SmAccountRESTControllerLib from './controller.js'
|
||||
import Validators from '../middleware/validators.js'
|
||||
|
||||
let _this
|
||||
|
||||
class SmAccountRouter {
|
||||
constructor (localConfig = {}) {
|
||||
// Dependency Injection.
|
||||
this.adapters = localConfig.adapters
|
||||
if (!this.adapters) {
|
||||
throw new Error(
|
||||
'Instance of Adapters library required when instantiating /sm REST Controller.'
|
||||
)
|
||||
}
|
||||
this.useCases = localConfig.useCases
|
||||
if (!this.useCases) {
|
||||
throw new Error(
|
||||
'Instance of Use Cases library required when instantiating /sm REST Controller.'
|
||||
)
|
||||
}
|
||||
|
||||
const dependencies = {
|
||||
adapters: this.adapters,
|
||||
useCases: this.useCases
|
||||
}
|
||||
|
||||
// Encapsulate dependencies.
|
||||
this.validators = new Validators()
|
||||
this.smAccountRESTController = new SmAccountRESTControllerLib(dependencies)
|
||||
|
||||
// Instantiate the router and set the base route.
|
||||
const baseUrl = '/sm'
|
||||
this.router = new Router({ prefix: baseUrl })
|
||||
|
||||
this.listAccounts = this.listAccounts.bind(this)
|
||||
_this = this
|
||||
}
|
||||
|
||||
attach (app) {
|
||||
if (!app) {
|
||||
throw new Error(
|
||||
'Must pass app object when attached REST API controllers.'
|
||||
)
|
||||
}
|
||||
|
||||
// Define the routes and attach the controller.
|
||||
this.router.get('/list/all/:page', _this.smAccountRESTController.listAccounts)
|
||||
this.router.get('/npub/:npub', _this.smAccountRESTController.getAccountByNpub)
|
||||
this.router.get('/bchAddr/:bchAddr', _this.smAccountRESTController.getAccountByBchAddr)
|
||||
|
||||
// Attach the Controller routes to the Koa app.
|
||||
app.use(_this.router.routes())
|
||||
app.use(_this.router.allowedMethods())
|
||||
}
|
||||
|
||||
async listAccounts (ctx, next) {
|
||||
// await _this.validators.ensureUser(ctx, next)
|
||||
await _this.smAccountRESTController.listAccounts(ctx, next)
|
||||
}
|
||||
}
|
||||
|
||||
export default SmAccountRouter
|
||||
@@ -22,6 +22,14 @@ class TimerControllers {
|
||||
}
|
||||
|
||||
this.debugLevel = localConfig.debugLevel
|
||||
|
||||
// Constants
|
||||
this.cleanUsageInterval = 60000 * 60 // 1 hour
|
||||
this.backupUsageInterval = 60000 * 10 // 10 minutes
|
||||
this.newSmAccountsInterval = 60000 * 60 // 60 minutes
|
||||
this.updateSmAccountsInterval = 60000 * 10 // 10 minutes
|
||||
|
||||
// Encapsulate dependencies
|
||||
this.config = config
|
||||
|
||||
// Bind 'this' object to all subfunctions
|
||||
@@ -30,15 +38,18 @@ class TimerControllers {
|
||||
this.gcOffers = this.gcOffers.bind(this)
|
||||
this.checkDupOffers = this.checkDupOffers.bind(this)
|
||||
this.loadOffers = this.loadOffers.bind(this)
|
||||
// Bind 'this' object to all subfunctions.
|
||||
// this.exampleTimerFunc = this.exampleTimerFunc.bind(this)
|
||||
this.cleanUsage = this.cleanUsage.bind(this)
|
||||
this.backupUsage = this.backupUsage.bind(this)
|
||||
this.newSmAccounts = this.newSmAccounts.bind(this)
|
||||
this.updateSmAccounts = this.updateSmAccounts.bind(this)
|
||||
|
||||
// State
|
||||
this.gcOrdersInt = null
|
||||
this.gcOffersInt = null
|
||||
this.checkDupOffersInt = null
|
||||
this.loadOffersInt = null
|
||||
this.newSmAccountsInt = null
|
||||
this.updateSmAccountsInt = null
|
||||
}
|
||||
|
||||
// Start all the time-based controllers.
|
||||
@@ -47,11 +58,10 @@ class TimerControllers {
|
||||
this.gcOffersInt = setInterval(this.gcOffers, 60000 * 5)
|
||||
// this.checkDupOffersInt = setInterval(this.checkDupOffers, 60000 * 4.5)
|
||||
this.loadOffersInt = setInterval(this.loadOffers, 60000 * 2)
|
||||
// Any new timer control functions can be added here. They will be started
|
||||
// when the server starts.
|
||||
// this.optimizeWalletHandle = setInterval(this.exampleTimerFunc, 60000 * 60)
|
||||
this.cleanUsageHandle = setInterval(this.cleanUsage, 60000 * 60) // 1 hour
|
||||
|
||||
this.cleanUsageHandle = setInterval(this.cleanUsage, this.cleanUsageInterval)
|
||||
this.backupUsageHandle = setInterval(this.backupUsage, this.backupUsageInterval)
|
||||
this.newSmAccountsInt = setInterval(this.newSmAccounts, this.newSmAccountsInterval)
|
||||
this.updateSmAccountsInt = setInterval(this.updateSmAccounts, this.updateSmAccountsInterval)
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -61,6 +71,9 @@ class TimerControllers {
|
||||
// clearInterval(this.checkDupOffers)
|
||||
clearInterval(this.optimizeWalletHandle)
|
||||
clearInterval(this.cleanUsageHandle)
|
||||
clearInterval(this.backupUsageHandle)
|
||||
clearInterval(this.newSmAccountsInt)
|
||||
clearInterval(this.updateSmAccountsInt)
|
||||
}
|
||||
|
||||
// Garbage Collect the Orders.
|
||||
@@ -75,6 +88,26 @@ class TimerControllers {
|
||||
}
|
||||
}
|
||||
|
||||
// Clean the usage state so that stats reflect the last 24 hours.
|
||||
cleanUsage () {
|
||||
try {
|
||||
clearInterval(this.cleanUsageHandle)
|
||||
|
||||
const now = new Date()
|
||||
console.log(`cleanUsage() Timer Controller executing at ${now.toLocaleString()}`)
|
||||
|
||||
this.useCases.usage.cleanUsage()
|
||||
|
||||
this.cleanUsageHandle = setInterval(this.cleanUsage, this.cleanUsageInterval)
|
||||
|
||||
return true
|
||||
} catch (err) {
|
||||
console.error('Error in time-controller.js/cleanUsage(): ', err)
|
||||
|
||||
this.cleanUsageHandle = setInterval(this.cleanUsage, this.cleanUsageInterval)
|
||||
}
|
||||
}
|
||||
|
||||
// Garbage Collect the Offers.
|
||||
gcOffers () {
|
||||
try {
|
||||
@@ -111,22 +144,55 @@ class TimerControllers {
|
||||
}
|
||||
}
|
||||
|
||||
// Clean the usage state so that stats reflect the last 24 hours.
|
||||
cleanUsage () {
|
||||
// Backup the usage stats to the database
|
||||
async backupUsage () {
|
||||
try {
|
||||
const now = new Date()
|
||||
console.log(`cleanUsage() Timer Controller executing at ${now.toLocaleString()}`)
|
||||
clearInterval(this.backupUsageHandle)
|
||||
|
||||
this.useCases.usage.cleanUsage()
|
||||
console.log('backupUsage() Timer Controller executing at ', new Date().toLocaleString())
|
||||
|
||||
// Clear the database of old usage data.
|
||||
await this.useCases.usage.clearUsage()
|
||||
|
||||
// Save the current usage snapshot to the database.
|
||||
await this.useCases.usage.saveUsage()
|
||||
|
||||
this.backupUsageHandle = setInterval(this.backupUsage, this.backupUsageInterval)
|
||||
|
||||
return true
|
||||
} catch (err) {
|
||||
console.error('Error in time-controller.js/cleanUsage(): ', err)
|
||||
console.error('Error in time-controller.js/backupUsage(): ', err)
|
||||
|
||||
this.backupUsageHandle = setInterval(this.backupUsage, this.backupUsageInterval)
|
||||
|
||||
// Note: Do not throw an error. This is a top-level function.
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Check for new Social Media Accounts.
|
||||
async newSmAccounts () {
|
||||
try {
|
||||
await this.useCases.smAccount.checkForNewSmAccounts()
|
||||
return true
|
||||
} catch (err) {
|
||||
console.error('Error in time-controller.js/newSmAccounts(): ', err)
|
||||
|
||||
// Note: Do not throw an error. This is a top-level function.
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Update the Social Media Accounts.
|
||||
async updateSmAccounts () {
|
||||
try {
|
||||
await this.useCases.smAccount.updateSmAccounts()
|
||||
return true
|
||||
} catch (err) {
|
||||
console.error('Error in time-controller.js/updateSmAccounts(): ', err)
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default TimerControllers
|
||||
|
||||
@@ -10,6 +10,7 @@ import EntryUseCases from './entry.js'
|
||||
import OfferUseCases from './offer/index.js'
|
||||
import OrderUseCases from './order.js'
|
||||
import { UsageUseCases } from './usage-use-cases.js'
|
||||
import SmAccountUseCases from './smAccount-use-cases.js'
|
||||
|
||||
class UseCases {
|
||||
constructor (localConfig = {}) {
|
||||
@@ -27,10 +28,14 @@ class UseCases {
|
||||
localConfig.order = this.order
|
||||
this.offer = new OfferUseCases(localConfig)
|
||||
this.usage = new UsageUseCases(localConfig)
|
||||
this.smAccount = new SmAccountUseCases(localConfig)
|
||||
}
|
||||
|
||||
// Run any startup Use Cases at the start of the app.
|
||||
async start () {
|
||||
// Load the usage stats from the database
|
||||
await this.usage.loadUsage()
|
||||
|
||||
console.log('Async Use Cases have been started.')
|
||||
|
||||
return true
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
/*
|
||||
Social Media Account Use Cases.
|
||||
*/
|
||||
|
||||
class smAccountUseCases {
|
||||
constructor (localConfig = {}) {
|
||||
// console.log('User localConfig: ', localConfig)
|
||||
|
||||
// Dependency injection.
|
||||
this.adapters = localConfig.adapters
|
||||
if (!this.adapters) {
|
||||
throw new Error(
|
||||
'Instance of adapters must be passed in when instantiating Order Use Cases library.'
|
||||
)
|
||||
}
|
||||
|
||||
// Bind 'this' object to all methods
|
||||
this.checkForNewSmAccounts = this.checkForNewSmAccounts.bind(this)
|
||||
this.listAccounts = this.listAccounts.bind(this)
|
||||
this.getAccountByNpub = this.getAccountByNpub.bind(this)
|
||||
this.getAccountByBchAddr = this.getAccountByBchAddr.bind(this)
|
||||
this.updateSmAccounts = this.updateSmAccounts.bind(this)
|
||||
}
|
||||
|
||||
// Check for new Social Media Accounts.
|
||||
async checkForNewSmAccounts () {
|
||||
try {
|
||||
console.log('Checking for new Social Media Accounts...')
|
||||
|
||||
const messages = await this.adapters.nostr.readGlobalFeed()
|
||||
for (let i = 0; i < messages.length; i++) {
|
||||
const msg = messages[i]
|
||||
// const { content, id, tags, npub, pubkey } = msg
|
||||
const { tags, npub, pubkey } = msg
|
||||
let bchAddr = null
|
||||
// console.log('msg: ', JSON.stringify(msg, null, 2))
|
||||
|
||||
// Find the 'u' tag if it exists
|
||||
const uTag = tags.find(tag => tag[0] === 'u')
|
||||
|
||||
// If 'u' tag exists and contains a BCH address
|
||||
if (uTag && uTag[1].includes('bitcoincash:')) {
|
||||
bchAddr = uTag[1]
|
||||
// console.log('BCH address found:', bchAddr)
|
||||
}
|
||||
|
||||
const SmAccount = await this.adapters.localdb.SmAccount
|
||||
|
||||
if (bchAddr) {
|
||||
const smAccount = await SmAccount.findOne({ npub })
|
||||
if (!smAccount) {
|
||||
console.log(`Creating new Social Media Account with npub: ${npub} and bchAddr: ${bchAddr}`)
|
||||
const newSmAccount = new SmAccount({ npub, bchAddr, pubkey })
|
||||
await newSmAccount.save()
|
||||
} else {
|
||||
console.log(`Social Media Account with npub: ${npub} already exists`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
} catch (err) {
|
||||
console.error('Error in smAccount-use-cases.js/checkForNewSmAccounts(): ', err)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
// List all Social Media Accounts.
|
||||
async listAccounts (page = 0) {
|
||||
try {
|
||||
const SmAccount = await this.adapters.localdb.SmAccount
|
||||
const accounts = await SmAccount.find({}).skip(page * 10).limit(10)
|
||||
return accounts
|
||||
} catch (err) {
|
||||
console.error('Error in smAccount-use-cases.js/listAccounts(): ', err)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
// Get a Social Media Account by Npub.
|
||||
async getAccountByNpub (npub) {
|
||||
try {
|
||||
const SmAccount = await this.adapters.localdb.SmAccount
|
||||
const account = await SmAccount.findOne({ npub })
|
||||
return account
|
||||
} catch (err) {
|
||||
console.error('Error in smAccount-use-cases.js/getAccountByNpub(): ', err)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
// Get a Social Media Account by BCH address.
|
||||
async getAccountByBchAddr (bchAddr) {
|
||||
try {
|
||||
const SmAccount = await this.adapters.localdb.SmAccount
|
||||
const account = await SmAccount.findOne({ bchAddr })
|
||||
console.log('Account found: ', account)
|
||||
|
||||
return account
|
||||
} catch (err) {
|
||||
console.error('Error in smAccount-use-cases.js/getAccountByBchAddr(): ', err)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
// Update metadata about social media accounts being tracked.
|
||||
async updateSmAccounts () {
|
||||
try {
|
||||
console.log('Updating Social Media Accounts...')
|
||||
const SmAccount = await this.adapters.localdb.SmAccount
|
||||
const accounts = await SmAccount.find({})
|
||||
for (let i = 0; i < accounts.length; i++) {
|
||||
const account = accounts[i]
|
||||
// console.log(`Account ${i}: `, account)
|
||||
|
||||
// Get the number of accounts following this account
|
||||
const pubkey = account.pubkey
|
||||
const followList = await this.adapters.nostr.getFollowers({ pubkey })
|
||||
// console.log(`Follow list ${i}: `, JSON.stringify(followList, null, 2))
|
||||
|
||||
// Update the follower count for this account.
|
||||
const followerCnt = followList.length
|
||||
await SmAccount.updateOne({ _id: account._id }, { $set: { followerCnt } })
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error in smAccount-use-cases.js/updateSmAccounts(): ', err)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default smAccountUseCases
|
||||
@@ -3,6 +3,10 @@
|
||||
for tracking the usage of REST API and JSON RPC calls. This library is used
|
||||
by admins to keep an eye on how many API calls were made in a 24-hour and
|
||||
1-hour time period.
|
||||
|
||||
Usage stats are held in memory. But they are periodically backed up to the
|
||||
Mongo database. On startup, the usage stats are loaded from the database.
|
||||
This allows the usage stats to be persisted across restarts.
|
||||
*/
|
||||
|
||||
// This global variable is used to share data between the REST middleware and
|
||||
@@ -19,11 +23,17 @@ class UsageUseCases {
|
||||
)
|
||||
}
|
||||
|
||||
// Encapsulate dependencies
|
||||
this.UsageModel = this.adapters.localdb.Usage
|
||||
|
||||
// Bind 'this' object to all subfunctions
|
||||
this.cleanUsage = this.cleanUsage.bind(this)
|
||||
this.getRestSummary = this.getRestSummary.bind(this)
|
||||
this.getTopIps = this.getTopIps.bind(this)
|
||||
this.getTopEndpoints = this.getTopEndpoints.bind(this)
|
||||
this.clearUsage = this.clearUsage.bind(this)
|
||||
this.saveUsage = this.saveUsage.bind(this)
|
||||
this.loadUsage = this.loadUsage.bind(this)
|
||||
|
||||
// State
|
||||
}
|
||||
@@ -108,6 +118,70 @@ class UsageUseCases {
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
// Clear the usage database data
|
||||
async clearUsage () {
|
||||
try {
|
||||
await this.UsageModel.deleteMany({})
|
||||
|
||||
// Debugging: verify the database is empty
|
||||
// Delete this code after debugging
|
||||
const usage = await this.UsageModel.find({})
|
||||
console.log('clearUsage() usage: ', usage)
|
||||
return true
|
||||
} catch (err) {
|
||||
console.error('Error in usage-use-cases.js/clearUsage()')
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
// Save the usage data to the database
|
||||
async saveUsage (inObj = {}) {
|
||||
try {
|
||||
for (let i = 0; i < restCalls.length; i++) {
|
||||
const thisRestCall = restCalls[i]
|
||||
|
||||
// Debugging: delete this code after debugging
|
||||
// if (i === 5) {
|
||||
// console.log('saveUsage() thisRestCall: ', thisRestCall)
|
||||
// }
|
||||
|
||||
const usageData = {
|
||||
ip: thisRestCall.ip,
|
||||
url: thisRestCall.url,
|
||||
method: thisRestCall.method,
|
||||
timestamp: thisRestCall.timestamp
|
||||
}
|
||||
|
||||
const usage = new this.UsageModel(usageData)
|
||||
await usage.save()
|
||||
}
|
||||
return true
|
||||
} catch (err) {
|
||||
console.error('Error in usage-use-cases.js/saveUsage()')
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
// Load usage data from the database
|
||||
async loadUsage () {
|
||||
try {
|
||||
const usage = await this.UsageModel.find({})
|
||||
// console.log('usage: ', usage)
|
||||
|
||||
// Debugging: delete this code after debugging
|
||||
if (usage[5]) {
|
||||
console.log('loadUsage() usage[5]: ', usage[5])
|
||||
}
|
||||
|
||||
restCalls = usage
|
||||
return usage
|
||||
} catch (err) {
|
||||
console.error('Error in usage-use-cases.js/loadUsage(): ', err)
|
||||
return false
|
||||
// throw err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// This Koa middleware is called any time there is a REST API. It logs the
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
/*
|
||||
Liveness test runs before all other tests to ensure the server is running.
|
||||
*/
|
||||
|
||||
// Public npm libraries
|
||||
import { assert } from 'chai'
|
||||
import axios from 'axios'
|
||||
import testUtils from '../../utils/test-utils.js'
|
||||
|
||||
// const sinon = require('sinon')
|
||||
|
||||
// Local support libraries
|
||||
import config from '../../../config/index.js'
|
||||
// import Server from '../../../bin/server.js'
|
||||
// import testUtils from '../../utils/test-utils.js'
|
||||
// const adminLib = new AdminLib()
|
||||
|
||||
const LOCALHOST = `http://localhost:${config.port}`
|
||||
|
||||
describe('#Check Server Liveness', () => {
|
||||
// before(async () => {
|
||||
it('should confirm the server is running', async () => {
|
||||
try {
|
||||
const response = await axios.get(`${LOCALHOST}/`)
|
||||
assert(response.status === 200, 'Server is running, continuing with E2E tests.')
|
||||
} catch (err) {
|
||||
console.log('\nServer is not running, exiting tests.')
|
||||
console.log('Start the server with `npm run start:e2e:server` before running E2E tests.\n')
|
||||
console.log('Ensure running npm run docs before running the test server')
|
||||
process.exit(1)
|
||||
}
|
||||
})
|
||||
it('should confirm the server is running over test enviroment', async () => {
|
||||
try {
|
||||
const res = await testUtils.loginAdminUser()
|
||||
assert.property(res, 'user')
|
||||
assert.property(res, 'token')
|
||||
assert.property(res, 'id')
|
||||
} catch (err) {
|
||||
console.log('\nServer is not running over test enviroment, exiting tests.')
|
||||
console.log('Start the server with `npm run start:e2e:server` before running E2E tests.\n')
|
||||
process.exit(1)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -13,10 +13,8 @@ import axios from 'axios'
|
||||
|
||||
// Local support libraries
|
||||
import config from '../../../config/index.js'
|
||||
import Server from '../../../bin/server.js'
|
||||
// import Server from '../../../bin/server.js'
|
||||
import testUtils from '../../utils/test-utils.js'
|
||||
import AdminLib from '../../../src/adapters/admin.js'
|
||||
const adminLib = new AdminLib()
|
||||
|
||||
// const request = supertest.agent(app.listen())
|
||||
const context = {}
|
||||
@@ -26,10 +24,12 @@ const LOCALHOST = `http://localhost:${config.port}`
|
||||
if (!config.noMongo) {
|
||||
describe('Auth', () => {
|
||||
before(async () => {
|
||||
const app = new Server()
|
||||
// const app = new Server()
|
||||
|
||||
// This should be the first instruction. It starts the REST API server.
|
||||
await app.startServer()
|
||||
// await app.startServer()
|
||||
|
||||
// TODO:
|
||||
|
||||
// Stop the IPFS node for the rest of the e2e tests.
|
||||
// await app.controllers.adapters.ipfs.stop()
|
||||
@@ -37,9 +37,6 @@ if (!config.noMongo) {
|
||||
// Delete all previous users in the database.
|
||||
await testUtils.deleteAllUsers()
|
||||
|
||||
// Create a new admin user.
|
||||
await adminLib.createSystemUser()
|
||||
|
||||
const userObj = {
|
||||
email: 'test@test.com',
|
||||
password: 'pass',
|
||||
|
||||
@@ -175,59 +175,6 @@ if (!config.noMongo) {
|
||||
assert.equal(result.data.user.type, 'user')
|
||||
assert.property(result.data.user, 'mnemonic')
|
||||
})
|
||||
it('should reject signup when DISABLE_NEW_ACCOUNTS is true', async () => {
|
||||
try {
|
||||
process.env.DISABLE_NEW_ACCOUNTS = true
|
||||
const options = {
|
||||
method: 'POST',
|
||||
url: `${LOCALHOST}/users`,
|
||||
data: {
|
||||
email: 'test2@test.com',
|
||||
password: 'supersecretpassword',
|
||||
name: 'test3'
|
||||
}
|
||||
}
|
||||
|
||||
await axios(options)
|
||||
|
||||
assert(false, 'Unexpected result')
|
||||
} catch (err) {
|
||||
assert(err.response.status === 401, 'Error code 401 expected.')
|
||||
}
|
||||
})
|
||||
it('admin can create a user when DISABLE_NEW_ACCOUNTS is true', async () => {
|
||||
process.env.DISABLE_NEW_ACCOUNTS = true
|
||||
const options = {
|
||||
method: 'post',
|
||||
url: `${LOCALHOST}/users`,
|
||||
headers: {
|
||||
Authorization: `Bearer ${context.adminJWT}`
|
||||
},
|
||||
data: {
|
||||
user: {
|
||||
email: 'fromAdmin@test.com',
|
||||
password: 'supersecretpassword',
|
||||
name: 'test3'
|
||||
}
|
||||
}
|
||||
}
|
||||
const result = await axios(options)
|
||||
|
||||
context.user = result.data.user
|
||||
context.token = result.data.token
|
||||
|
||||
assert(result.status === 200, 'Status Code 200 expected.')
|
||||
assert(
|
||||
result.data.user.email === 'fromAdmin@test.com',
|
||||
'Email of test expected'
|
||||
)
|
||||
assert(
|
||||
result.data.user.password === undefined,
|
||||
'Password expected to be omited'
|
||||
)
|
||||
assert.property(result.data, 'token', 'Token property exists.')
|
||||
assert.equal(result.data.user.type, 'user')
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /users', () => {
|
||||
@@ -349,6 +296,9 @@ if (!config.noMongo) {
|
||||
// assert.equal(err.response.data, 'test error')
|
||||
// }
|
||||
// })
|
||||
// assert.hasAnyKeys(users[0], ['type', '_id', 'email'])
|
||||
// assert.isNumber(users.length)
|
||||
// })
|
||||
})
|
||||
|
||||
describe('GET /users/:id', () => {
|
||||
|
||||
@@ -24,17 +24,33 @@ describe('#adapters', () => {
|
||||
})
|
||||
|
||||
describe('#start', () => {
|
||||
it('should start the async adapters', async () => {
|
||||
// it('should start the async adapters', async () => {
|
||||
// // Mock dependencies
|
||||
// uut.config.getJwtAtStartup = true
|
||||
// uut.config.useIpfs = true
|
||||
// uut.config.env = 'not-a-test'
|
||||
// sandbox.stub(uut.fullStackJwt, 'getJWT').resolves()
|
||||
// sandbox.stub(uut.fullStackJwt, 'instanceBchjs').resolves()
|
||||
// sandbox.stub(uut.ipfs, 'start').resolves()
|
||||
|
||||
// const result = await uut.start()
|
||||
|
||||
// assert.equal(result, true)
|
||||
// })
|
||||
|
||||
it('should not start ipfs on test enviroment', async () => {
|
||||
// Mock dependencies
|
||||
uut.config.getJwtAtStartup = true
|
||||
uut.config.useIpfs = true
|
||||
uut.config.env = 'not-a-test'
|
||||
uut.config.env = 'test'
|
||||
|
||||
sandbox.stub(uut.fullStackJwt, 'getJWT').resolves()
|
||||
sandbox.stub(uut.fullStackJwt, 'instanceBchjs').resolves()
|
||||
sandbox.stub(uut.ipfs, 'start').resolves()
|
||||
const ipfsSpy = sandbox.stub(uut.ipfs, 'start').resolves(null)
|
||||
|
||||
const result = await uut.start()
|
||||
|
||||
assert.isTrue(ipfsSpy.notCalled)
|
||||
assert.equal(result, true)
|
||||
})
|
||||
|
||||
|
||||
+7
-19
@@ -19,26 +19,13 @@ describe('Admin', () => {
|
||||
|
||||
if (!config.noMongo) {
|
||||
describe('loginAdmin()', () => {
|
||||
it('should logind admin', async () => {
|
||||
it('should login admin', async () => {
|
||||
try {
|
||||
const error = new Error('test error')
|
||||
error.response = {
|
||||
status: 422
|
||||
}
|
||||
// sandbox.stub(uut.axios, 'request').onFirstCall().throws(error)
|
||||
sandbox.stub(uut.jsonFiles, 'readJSON').resolves({ password: 'pass' })
|
||||
sandbox.stub(uut.axios, 'request').resolves(true)
|
||||
|
||||
const result = await uut.loginAdmin()
|
||||
const user = result.data.user
|
||||
|
||||
assert.property(user, '_id')
|
||||
assert.property(user, 'email')
|
||||
assert.property(user, 'type')
|
||||
|
||||
assert.isString(user._id)
|
||||
assert.isString(user.email)
|
||||
assert.isString(user.type)
|
||||
|
||||
assert.equal(user.type, 'admin')
|
||||
assert.isTrue(result)
|
||||
} catch (err) {
|
||||
assert(false, 'Unexpected result')
|
||||
}
|
||||
@@ -48,13 +35,13 @@ describe('Admin', () => {
|
||||
try {
|
||||
// Returns an erroneous password to force
|
||||
// an auth error
|
||||
sandbox.stub(uut.axios, 'request').throws(new Error('test error'))
|
||||
sandbox.stub(uut.jsonFiles, 'readJSON').resolves({ password: 'wrong' })
|
||||
|
||||
await uut.loginAdmin()
|
||||
assert(false, 'Unexpected result')
|
||||
} catch (err) {
|
||||
assert.equal(err.response.status, 401)
|
||||
assert.include(err.response.data, 'Unauthorized')
|
||||
assert.include(err.message, 'test error')
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -84,6 +71,7 @@ describe('Admin', () => {
|
||||
}
|
||||
|
||||
sandbox.stub(uut.User, 'findOne').resolves(fakeUser)
|
||||
sandbox.stub(uut.jsonFiles, 'writeJSON').resolves(true)
|
||||
const result = await uut.createSystemUser()
|
||||
|
||||
assert.property(result, 'email')
|
||||
@@ -41,5 +41,17 @@ describe('#passport.js', () => {
|
||||
assert.include(err.message, 'cant auth user')
|
||||
}
|
||||
})
|
||||
it('should authenticate user', async () => {
|
||||
const ctx = {}
|
||||
const errMock = null
|
||||
const userMock = {
|
||||
_id: '123',
|
||||
email: 'test@test.com'
|
||||
}
|
||||
sandbox.stub(uut.passport, 'authenticate').yields(errMock, userMock)
|
||||
const user = await uut.authUser(ctx)
|
||||
assert.equal(user._id, userMock._id)
|
||||
assert.equal(user.email, userMock.email)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -55,6 +55,13 @@ describe('#User-Adapter', () => {
|
||||
|
||||
assert.notEqual(testuser.password, 'password')
|
||||
})
|
||||
it('should ignore password encrption if password property is not provided', async () => {
|
||||
const lastPassword = testuser.password
|
||||
await testuser.save()
|
||||
// console.log('testuser: ', testuser)
|
||||
|
||||
assert.equal(testuser.password, lastPassword)
|
||||
})
|
||||
})
|
||||
|
||||
describe('#validatePassword', () => {
|
||||
|
||||
@@ -38,4 +38,25 @@ describe('#Controllers', () => {
|
||||
await uut.attachControllers(app)
|
||||
})
|
||||
})
|
||||
describe('#attachRESTControllers', () => {
|
||||
it('should attach the controllers', async () => {
|
||||
const app = {
|
||||
use: () => {}
|
||||
}
|
||||
|
||||
await uut.attachRESTControllers(app)
|
||||
})
|
||||
})
|
||||
describe('#initAdapters', () => {
|
||||
it('should attach the controllers', async () => {
|
||||
sandbox.stub(uut.adapters, 'start').resolves({})
|
||||
await uut.initAdapters()
|
||||
})
|
||||
})
|
||||
describe('#initUseCases', () => {
|
||||
it('should attach the controllers', async () => {
|
||||
sandbox.stub(uut.useCases, 'start').resolves({})
|
||||
await uut.initUseCases()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -79,11 +79,22 @@ describe('#Auth-REST-Router', () => {
|
||||
await uut.authUser(ctx)
|
||||
})
|
||||
|
||||
it('should catch and throw an error', async () => {
|
||||
it('should catch and throw passport error', async () => {
|
||||
try {
|
||||
// Force an error
|
||||
sandbox.stub(uut.passport, 'authUser').rejects('test error')
|
||||
|
||||
await uut.authUser(ctx)
|
||||
} catch (err) {
|
||||
// console.log('err: ', err)
|
||||
assert.include(err.message, 'Unauthorized')
|
||||
}
|
||||
})
|
||||
it('should handle error if user is not found!', async () => {
|
||||
try {
|
||||
// Force an error
|
||||
sandbox.stub(uut.passport, 'authUser').resolves(null)
|
||||
|
||||
await uut.authUser(ctx)
|
||||
} catch (err) {
|
||||
// console.log('err: ', err)
|
||||
|
||||
@@ -20,7 +20,7 @@ describe('#RESTControllers', () => {
|
||||
let sandbox
|
||||
// let ctx
|
||||
|
||||
before(async () => {})
|
||||
before(async () => { })
|
||||
|
||||
beforeEach(() => {
|
||||
const useCases = new UseCasesMock()
|
||||
@@ -64,4 +64,19 @@ describe('#RESTControllers', () => {
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('#attachRESTControllers', () => {
|
||||
it('should attach controllers without mongo service', () => {
|
||||
uut.config.noMongo = true
|
||||
|
||||
const app = { use: () => {} }
|
||||
uut.attachRESTControllers(app)
|
||||
})
|
||||
it('should attach controllers with mongo service', () => {
|
||||
uut.config.noMongo = false
|
||||
|
||||
const app = { use: () => {} }
|
||||
uut.attachRESTControllers(app)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -153,6 +153,20 @@ describe('#Users-REST-Controller', () => {
|
||||
// Assert that expected properties exist in the returned data.
|
||||
assert.property(ctx.response.body, 'user')
|
||||
})
|
||||
it('should run next function if it exists', async () => {
|
||||
// Mock dependencies
|
||||
const nextSpy = sandbox.spy()
|
||||
sandbox.stub(uut.useCases.user, 'getUser').resolves({ _id: '123' })
|
||||
|
||||
await uut.getUser(ctx, nextSpy)
|
||||
|
||||
// Assert the expected HTTP response
|
||||
assert.equal(ctx.status, 200)
|
||||
|
||||
// Assert that expected properties exist in the returned data.
|
||||
assert.property(ctx.response.body, 'user')
|
||||
assert.isTrue(nextSpy.calledOnce)
|
||||
})
|
||||
|
||||
it('should return other error status passed by biz logic', async () => {
|
||||
try {
|
||||
|
||||
@@ -79,4 +79,73 @@ describe('#Users-REST-Router', () => {
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('#createUser', () => {
|
||||
it('should ignore admin validator when DISABLE_NEW_ACCOUNTS is not defined', async () => {
|
||||
// Stub functions
|
||||
const validationSpy = sandbox.stub(uut.validators, 'ensureAdmin').resolves(true)
|
||||
sandbox.stub(uut.userRESTController, 'createUser').resolves(true)
|
||||
|
||||
// Call function
|
||||
await uut.createUser()
|
||||
|
||||
// Assertions
|
||||
assert.isTrue(validationSpy.notCalled, 'Admin validator should not be called')
|
||||
})
|
||||
it('should ensure admin when DISABLE_NEW_ACCOUNTS is defined', async () => {
|
||||
// Set environment variable
|
||||
process.env.DISABLE_NEW_ACCOUNTS = true
|
||||
|
||||
// Stub functions
|
||||
const validationSpy = sandbox.stub(uut.validators, 'ensureAdmin').resolves(true)
|
||||
sandbox.stub(uut.userRESTController, 'createUser').resolves(true)
|
||||
|
||||
// Call function
|
||||
await uut.createUser()
|
||||
|
||||
// Assertions
|
||||
assert.isTrue(validationSpy.calledOnce, 'Admin validator should be called')
|
||||
})
|
||||
})
|
||||
|
||||
// describe('#getAll', () => {
|
||||
// it('should route to controller', async () => {
|
||||
// sandbox.stub(uut.validators, 'ensureUser').resolves(true)
|
||||
// const spy = sandbox.stub(uut.userRESTController, 'getUsers').resolves(true)
|
||||
|
||||
// await uut.getAll()
|
||||
// assert.isTrue(spy.calledOnce)
|
||||
// })
|
||||
// })
|
||||
|
||||
// describe('#getById', () => {
|
||||
// it('should route to controller', async () => {
|
||||
// sandbox.stub(uut.validators, 'ensureUser').resolves(true)
|
||||
// const spy = sandbox.stub(uut.userRESTController, 'getUser').resolves(true)
|
||||
|
||||
// await uut.getById()
|
||||
// assert.isTrue(spy.calledOnce)
|
||||
// })
|
||||
// })
|
||||
|
||||
describe('#updateUser', () => {
|
||||
it('should route to controller', async () => {
|
||||
sandbox.stub(uut.validators, 'ensureTargetUserOrAdmin').resolves(true)
|
||||
sandbox.stub(uut.userRESTController, 'getUser').resolves(true)
|
||||
const spy = sandbox.stub(uut.userRESTController, 'updateUser').resolves(true)
|
||||
|
||||
await uut.updateUser()
|
||||
assert.isTrue(spy.calledOnce)
|
||||
})
|
||||
})
|
||||
describe('#deleteUser', () => {
|
||||
it('should route to controller', async () => {
|
||||
sandbox.stub(uut.validators, 'ensureTargetUserOrAdmin').resolves(true)
|
||||
sandbox.stub(uut.userRESTController, 'getUser').resolves(true)
|
||||
const spy = sandbox.stub(uut.userRESTController, 'deleteUser').resolves(true)
|
||||
|
||||
await uut.deleteUser()
|
||||
assert.isTrue(spy.calledOnce)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -130,9 +130,26 @@ describe('#Timer-Controllers', () => {
|
||||
assert.equal(result, true)
|
||||
})
|
||||
|
||||
// it('should return false on error', async () => {
|
||||
// sandbox.stub(uut.useCases.usage, 'cleanUsage').throws(new Error('test error'))
|
||||
// const result = await uut.cleanUsage()
|
||||
|
||||
// assert.equal(result, false)
|
||||
// })
|
||||
})
|
||||
|
||||
describe('#backupUsage', () => {
|
||||
it('should kick off the Use Case', async () => {
|
||||
const result = await uut.backupUsage()
|
||||
|
||||
assert.equal(result, true)
|
||||
})
|
||||
|
||||
it('should return false on error', async () => {
|
||||
sandbox.stub(uut.useCases.usage, 'cleanUsage').throws(new Error('test error'))
|
||||
const result = await uut.cleanUsage()
|
||||
sandbox.stub(uut.useCases.usage, 'clearUsage').throws(new Error('test error'))
|
||||
// sandbox.stub(uut.useCases.usage, 'saveUsage').throws(new Error('test error'))
|
||||
|
||||
const result = await uut.backupUsage()
|
||||
|
||||
assert.equal(result, false)
|
||||
})
|
||||
|
||||
@@ -34,6 +34,12 @@ describe('#passport', () => {
|
||||
|
||||
passportCallback(id, 'password', done)
|
||||
})
|
||||
it('should handle not found user', () => {
|
||||
// Mock Users model.
|
||||
sandbox.stub(User, 'findOne').resolves(null)
|
||||
|
||||
passportCallback(id, 'password', done)
|
||||
})
|
||||
|
||||
it('should return if password is validated', () => {
|
||||
// Mock Users model.
|
||||
@@ -41,6 +47,15 @@ describe('#passport', () => {
|
||||
|
||||
passportCallback(id, 'password', done)
|
||||
})
|
||||
it('should handle error on password validation', () => {
|
||||
// Mock Users model.
|
||||
const userMock = {
|
||||
validatePassword: () => false
|
||||
}
|
||||
sandbox.stub(User, 'findOne').resolves(userMock)
|
||||
|
||||
passportCallback(id, 'password', done)
|
||||
})
|
||||
|
||||
it('should catch a high-level error', () => {
|
||||
// Force an error
|
||||
|
||||
@@ -31,7 +31,7 @@ describe('#server', () => {
|
||||
sandbox.stub(uut.controllers, 'attachControllers').resolves()
|
||||
sandbox.stub(uut, 'sleep').resolves()
|
||||
uut.config.env = 'dev'
|
||||
|
||||
uut.config.port = 5040
|
||||
const result = await uut.startServer()
|
||||
// console.log('result: ', result)
|
||||
|
||||
|
||||
@@ -74,6 +74,39 @@ const localdb = {
|
||||
}
|
||||
},
|
||||
|
||||
Usage: class Usage {
|
||||
static findById () {}
|
||||
static find () {}
|
||||
static findOne () {
|
||||
return {
|
||||
validatePassword: localdb.validatePassword
|
||||
}
|
||||
}
|
||||
|
||||
async save () {
|
||||
return {}
|
||||
}
|
||||
|
||||
generateToken () {
|
||||
return '123'
|
||||
}
|
||||
|
||||
toJSON () {
|
||||
return {}
|
||||
}
|
||||
|
||||
async remove () {
|
||||
return true
|
||||
}
|
||||
|
||||
async validatePassword () {
|
||||
return true
|
||||
}
|
||||
static async deleteMany(){
|
||||
return true
|
||||
}
|
||||
},
|
||||
|
||||
validatePassword: () => {
|
||||
return true
|
||||
},
|
||||
|
||||
@@ -77,6 +77,14 @@ class UsageUseCaseMock {
|
||||
async getTopEndpoints(existingUser, newData) {
|
||||
return true
|
||||
}
|
||||
|
||||
async clearUsage() {
|
||||
return true
|
||||
}
|
||||
|
||||
async saveUsage() {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
class UseCasesMock {
|
||||
|
||||
@@ -255,4 +255,67 @@ describe('#usage-use-case', () => {
|
||||
}
|
||||
})
|
||||
})
|
||||
describe('#clearUsage', () => {
|
||||
it('should clear the usage database data', async () => {
|
||||
const res = await uut.clearUsage()
|
||||
assert.isTrue(res)
|
||||
})
|
||||
|
||||
it('should handle error', async () => {
|
||||
try {
|
||||
sandbox.stub(uut.UsageModel, 'deleteMany').throws(new Error('uut error'))
|
||||
await uut.clearUsage()
|
||||
assert.fail('Unexpected code path')
|
||||
} catch (error) {
|
||||
assert.equal(error.message, 'uut error')
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('#saveUsage', () => {
|
||||
it('should save usage', async () => {
|
||||
// Set mock data
|
||||
restCalls.push({
|
||||
timestamp: new Date().getTime(),
|
||||
ip: 'localhost',
|
||||
url: 'fakeUrl',
|
||||
method: 'unit test'
|
||||
})
|
||||
const res = await uut.saveUsage()
|
||||
assert.isTrue(res)
|
||||
})
|
||||
|
||||
it('should handle error', async () => {
|
||||
try {
|
||||
restCalls.push(null)
|
||||
await uut.saveUsage()
|
||||
assert.fail('Unexpected code path')
|
||||
} catch (error) {
|
||||
console.log(error)
|
||||
assert.include(error.message, 'Cannot read properties')
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('#loadUsage', () => {
|
||||
it('should load usage', async () => {
|
||||
// Set mock data
|
||||
const mockObj = {
|
||||
timestamp: new Date().getTime(),
|
||||
ip: 'localhost',
|
||||
url: 'fakeUrl',
|
||||
method: 'unit test'
|
||||
}
|
||||
sandbox.stub(uut.UsageModel, 'find').returns(new Array(10).fill(null).map((_, i) => (mockObj)))
|
||||
const res = await uut.loadUsage()
|
||||
assert.equal(restCalls.length, 10)
|
||||
assert.equal(res.length, 10)
|
||||
})
|
||||
|
||||
it('should skip error', async () => {
|
||||
sandbox.stub(uut.UsageModel, 'find').throws(new Error('uut error'))
|
||||
const res = await uut.loadUsage()
|
||||
assert.isFalse(res)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
+45
-20
@@ -8,7 +8,6 @@ import axios from 'axios'
|
||||
|
||||
// Local libraries
|
||||
import config from '../../config/index.js'
|
||||
import User from '../../src/adapters/localdb/models/users.js'
|
||||
import JsonFiles from '../../src/adapters/json-files.js'
|
||||
|
||||
// Hack to get __dirname back.
|
||||
@@ -33,24 +32,6 @@ async function cleanDb () {
|
||||
}
|
||||
}
|
||||
|
||||
// Delete all users in the database. This ensures there is no previous state
|
||||
// to confuse tests.
|
||||
async function deleteAllUsers () {
|
||||
try {
|
||||
// Get all the users in the DB.
|
||||
const users = await User.find({}, '-password')
|
||||
// console.log(`users: ${JSON.stringify(users, null, 2)}`)
|
||||
|
||||
// Delete each user.
|
||||
for (let i = 0; i < users.length; i++) {
|
||||
const thisUser = users[i]
|
||||
await thisUser.remove()
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error in test-utils.js/deleteAllUsers()')
|
||||
}
|
||||
}
|
||||
|
||||
// This function is used to create new users.
|
||||
// userObj = {
|
||||
// username,
|
||||
@@ -170,12 +151,56 @@ async function getAdminJWT () {
|
||||
throw err
|
||||
}
|
||||
}
|
||||
// Fetches all users from the database.
|
||||
async function getAllUsers () {
|
||||
try {
|
||||
const adminJWT = await getAdminJWT()
|
||||
const options = {
|
||||
method: 'GET',
|
||||
url: `${LOCALHOST}/users`,
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminJWT}`
|
||||
}
|
||||
}
|
||||
const result = await axios(options)
|
||||
return result.data.users
|
||||
} catch (err) {
|
||||
console.error('Error in test/utils.js/getAllUsers()', err)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
// Deletes all users from the database.
|
||||
async function deleteAllUsers () {
|
||||
try {
|
||||
const allUsers = await getAllUsers()
|
||||
const adminJWT = await getAdminJWT()
|
||||
for (let i = 0; i < allUsers.length; i++) {
|
||||
const user = allUsers[i]
|
||||
// Skip the admin user.
|
||||
if (user.type === 'admin') {
|
||||
continue
|
||||
}
|
||||
const options = {
|
||||
method: 'DELETE',
|
||||
url: `${LOCALHOST}/users/${user._id}`,
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminJWT}`
|
||||
}
|
||||
}
|
||||
await axios(options)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error in test/utils.js/deleteAllUsers()', err)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
export default {
|
||||
cleanDb,
|
||||
createUser,
|
||||
loginTestUser,
|
||||
loginAdminUser,
|
||||
getAdminJWT,
|
||||
deleteAllUsers
|
||||
deleteAllUsers,
|
||||
getAllUsers
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user