mirror of
https://github.com/Permissionless-Software-Foundation/x402-base-facilitator.git
synced 2026-09-21 16:52:01 -07:00
Merge pull request #29 from christroutner/unstable
Bug fix for admin-handling in the tests
This commit is contained in:
+6
-1
@@ -1,3 +1,4 @@
|
||||
// npm libraries
|
||||
const Koa = require('koa')
|
||||
const bodyParser = require('koa-bodyparser')
|
||||
const convert = require('koa-convert')
|
||||
@@ -8,8 +9,10 @@ const passport = require('koa-passport')
|
||||
const mount = require('koa-mount')
|
||||
const serve = require('koa-static')
|
||||
const cors = require('kcors')
|
||||
|
||||
// Local libraries
|
||||
const config = require('../config') // this first.
|
||||
const adminLib = require('../src/lib/admin')
|
||||
const config = require('../config')
|
||||
const errorMiddleware = require('../src/middleware')
|
||||
|
||||
async function startServer () {
|
||||
@@ -47,6 +50,8 @@ async function startServer () {
|
||||
|
||||
// MIDDLEWARE END
|
||||
|
||||
console.log(`Running server in environment: ${config.env}`)
|
||||
|
||||
await app.listen(config.port)
|
||||
console.log(`Server started on ${config.port}`)
|
||||
|
||||
|
||||
+3
-2
@@ -5,11 +5,12 @@
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"start": "node index.js",
|
||||
"test": "KOA_ENV=test nyc --reporter=text --timeout 15000 ./node_modules/.bin/mocha --exit",
|
||||
"test": "npm run prep-test && KOA_ENV=test nyc --reporter=text --timeout 15000 ./node_modules/.bin/mocha --exit",
|
||||
"lint": "eslint src/**/*.js",
|
||||
"docs": "./node_modules/.bin/apidoc -i src/ -o docs",
|
||||
"coverage": "nyc report --reporter=text-lcov | coveralls",
|
||||
"coverage:report": "nyc --reporter=html mocha --exit"
|
||||
"coverage:report": "nyc --reporter=html mocha --exit",
|
||||
"prep-test":"node util/users/delete-all-test-users.js"
|
||||
},
|
||||
"keywords": [
|
||||
"koa-api-boilerplate",
|
||||
|
||||
+8
-2
@@ -58,6 +58,9 @@ async function createSystemUser () {
|
||||
// Save the user model.
|
||||
await user.save()
|
||||
|
||||
// console.log(`admin user created: ${JSON.stringify(result.body, null, 2)}`)
|
||||
// console.log(`with password: ${context.password}`)
|
||||
|
||||
// Write out the system user information to a JSON file that external
|
||||
// applications like the Task Manager and the test scripts can access.
|
||||
await jsonFiles.writeJSON(context, JSON_PATH)
|
||||
@@ -114,9 +117,9 @@ async function deleteExistingSystemUser () {
|
||||
|
||||
async function loginAdmin () {
|
||||
// console.log(`loginAdmin() running.`)
|
||||
try {
|
||||
let existingUser
|
||||
let existingUser
|
||||
|
||||
try {
|
||||
// Read the exising file
|
||||
existingUser = await jsonFiles.readJSON(JSON_PATH)
|
||||
// console.log(`existingUser: ${JSON.stringify(existingUser, null, 2)}`)
|
||||
@@ -138,6 +141,9 @@ async function loginAdmin () {
|
||||
return result
|
||||
} catch (err) {
|
||||
console.error(`Error in admin.js/loginAdmin().`)
|
||||
|
||||
// console.error(`existingUser: ${JSON.stringify(existingUser, null, 2)}`)
|
||||
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,16 +102,17 @@ async function ensureTargetUserOrAdmin (ctx, next) {
|
||||
// console.log(`ctx.state.user: ${JSON.stringify(ctx.state.user, null, 2)}`)
|
||||
// Ensure the calling user and the target user are the same.
|
||||
if (ctx.state.user._id.toString() !== targetId.toString()) {
|
||||
console.log(`Calling user and target user do not match!`)
|
||||
console.log(`Calling user: ${ctx.state.user._id}`)
|
||||
console.log(`Target user: ${targetId}`)
|
||||
// console.log(`Calling user and target user do not match!`)
|
||||
// console.log(`Calling user: ${ctx.state.user._id}`)
|
||||
// console.log(`Target user: ${targetId}`)
|
||||
|
||||
// If they don't match, then the calling user better be an admin.
|
||||
if (ctx.state.user.type !== 'admin') {
|
||||
ctx.throw(401, 'not admin')
|
||||
} else {
|
||||
console.log(`It's ok. The user is an admin.`)
|
||||
}
|
||||
// else {
|
||||
// console.log(`It's ok. The user is an admin.`)
|
||||
// }
|
||||
}
|
||||
|
||||
return next()
|
||||
|
||||
+2
-12
@@ -11,19 +11,9 @@ const LOCALHOST = `http://localhost:${config.port}`
|
||||
|
||||
describe('Auth', () => {
|
||||
before(async () => {
|
||||
await app.startServer()
|
||||
// await utils.cleanDb() // This should be first instruction.
|
||||
|
||||
utils.cleanDb()
|
||||
|
||||
/*
|
||||
authUser(request, (err, { user, token }) => {
|
||||
if (err) { return done(err) }
|
||||
|
||||
context.user = user
|
||||
context.token = token
|
||||
done()
|
||||
})
|
||||
*/
|
||||
await app.startServer() // This should be second instruction.
|
||||
|
||||
const userObj = {
|
||||
username: 'test',
|
||||
|
||||
+45
-4
@@ -2,6 +2,7 @@ const testUtils = require('./utils')
|
||||
const rp = require('request-promise')
|
||||
const assert = require('chai').assert
|
||||
const config = require('../config')
|
||||
const adminLib = require('../src/lib/admin')
|
||||
|
||||
const util = require('util')
|
||||
util.inspect.defaultOptions = { depth: 1 }
|
||||
@@ -12,7 +13,7 @@ const context = {}
|
||||
|
||||
describe('Users', () => {
|
||||
before(async () => {
|
||||
testUtils.cleanDb()
|
||||
// console.log(`config: ${JSON.stringify(config, null, 2)}`)
|
||||
|
||||
// Create a second test user.
|
||||
const userObj = {
|
||||
@@ -20,9 +21,22 @@ describe('Users', () => {
|
||||
password: 'pass2'
|
||||
}
|
||||
const testUser = await testUtils.createUser(userObj)
|
||||
// console.log(`testUser2: ${JSON.stringify(testUser, null, 2)}`)
|
||||
|
||||
context.user2 = testUser.user
|
||||
context.token2 = testUser.token
|
||||
context.id2 = testUser.user._id
|
||||
|
||||
// Get the JWT used to log in as the admin 'system' user.
|
||||
const adminJWT = await testUtils.getAdminJWT()
|
||||
// console.log(`adminJWT: ${adminJWT}`)
|
||||
context.adminJWT = adminJWT
|
||||
|
||||
// const admin = await testUtils.loginAdminUser()
|
||||
// context.adminJWT = admin.token
|
||||
|
||||
// const admin = await adminLib.loginAdmin()
|
||||
// console.log(`admin: ${JSON.stringify(admin, null, 2)}`)
|
||||
})
|
||||
|
||||
describe('POST /users', () => {
|
||||
@@ -74,8 +88,14 @@ describe('Users', () => {
|
||||
context.token = result.body.token
|
||||
|
||||
assert(result.statusCode === 200, 'Status Code 200 expected.')
|
||||
assert(result.body.user.username === 'supercoolname', 'Username of test expected')
|
||||
assert(result.body.user.password === undefined, 'Password expected to be omited')
|
||||
assert(
|
||||
result.body.user.username === 'supercoolname',
|
||||
'Username of test expected'
|
||||
)
|
||||
assert(
|
||||
result.body.user.password === undefined,
|
||||
'Password expected to be omited'
|
||||
)
|
||||
assert.property(result.body, 'token', 'Token property exists.')
|
||||
} catch (err) {
|
||||
console.log(
|
||||
@@ -476,7 +496,7 @@ describe('Users', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('should delete user', async () => {
|
||||
it('should delete own user', async () => {
|
||||
const {
|
||||
user: { _id },
|
||||
token
|
||||
@@ -498,5 +518,26 @@ describe('Users', () => {
|
||||
|
||||
assert.equal(result.body.success, true)
|
||||
})
|
||||
|
||||
it('should delete other account when admin', async () => {
|
||||
const id = context.id2
|
||||
const adminJWT = context.adminJWT
|
||||
|
||||
const options = {
|
||||
method: 'DELETE',
|
||||
uri: `${LOCALHOST}/users/${id}`,
|
||||
resolveWithFullResponse: true,
|
||||
json: true,
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
Authorization: `Bearer ${adminJWT}`
|
||||
}
|
||||
}
|
||||
|
||||
const result = await rp(options)
|
||||
// console.log(`result: ${util.inspect(result.body)}`)
|
||||
|
||||
assert.equal(result.body.success, true)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
+23
-23
@@ -1,32 +1,18 @@
|
||||
const mongoose = require('mongoose')
|
||||
const rp = require('request-promise')
|
||||
const config = require('../config')
|
||||
|
||||
const LOCALHOST = 'http://localhost:5000'
|
||||
|
||||
// Remove all collections from the DB.
|
||||
function cleanDb () {
|
||||
async function cleanDb () {
|
||||
for (const collection in mongoose.connection.collections) {
|
||||
if (mongoose.connection.collections.hasOwnProperty(collection)) {
|
||||
mongoose.connection.collections[collection].deleteMany()
|
||||
await mongoose.connection.collections[collection].deleteMany()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function authUser (agent, callback) {
|
||||
agent
|
||||
.post('/users')
|
||||
.set('Accept', 'application/json')
|
||||
.send({ user: { username: 'test', password: 'pass' } })
|
||||
.end((err, res) => {
|
||||
if (err) { return callback(err) }
|
||||
|
||||
callback(null, {
|
||||
user: res.body.user,
|
||||
token: res.body.token
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// This function is used to create new users.
|
||||
// userObj = {
|
||||
// username,
|
||||
@@ -93,10 +79,7 @@ async function loginTestUser () {
|
||||
|
||||
async function loginAdminUser () {
|
||||
try {
|
||||
process.env.NODE_ENV = process.env.NODE_ENV || 'dev'
|
||||
console.log(`env: ${process.env.NODE_ENV}`)
|
||||
|
||||
const FILENAME = `../config/system-user-${process.env.NODE_ENV}.json`
|
||||
const FILENAME = `../config/system-user-${config.env}.json`
|
||||
const adminUserData = require(FILENAME)
|
||||
console.log(`adminUserData: ${JSON.stringify(adminUserData, null, 2)}`)
|
||||
|
||||
@@ -128,10 +111,27 @@ async function loginAdminUser () {
|
||||
}
|
||||
}
|
||||
|
||||
// Retrieve the admin user JWT token from the JSON file it's saved at.
|
||||
async function getAdminJWT () {
|
||||
try {
|
||||
// process.env.KOA_ENV = process.env.KOA_ENV || 'dev'
|
||||
// console.log(`env: ${process.env.KOA_ENV}`)
|
||||
|
||||
const FILENAME = `../config/system-user-${config.env}.json`
|
||||
const adminUserData = require(FILENAME)
|
||||
// console.log(`adminUserData: ${JSON.stringify(adminUserData, null, 2)}`)
|
||||
|
||||
return adminUserData.token
|
||||
} catch (err) {
|
||||
console.error('Error in test/utils.js/getAdminJWT()')
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
cleanDb,
|
||||
authUser,
|
||||
createUser,
|
||||
loginTestUser,
|
||||
loginAdminUser
|
||||
loginAdminUser,
|
||||
getAdminJWT
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
const mongoose = require('mongoose')
|
||||
|
||||
// Force test environment
|
||||
process.env.KOA_ENV = 'test'
|
||||
const config = require('../../config')
|
||||
|
||||
const User = require('../../src/models/users')
|
||||
|
||||
async function deleteUsers () {
|
||||
// Connect to the Mongo Database.
|
||||
mongoose.Promise = global.Promise
|
||||
mongoose.set('useCreateIndex', true) // Stop deprecation warning.
|
||||
await mongoose.connect(config.database, { useNewUrlParser: true })
|
||||
|
||||
// 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()
|
||||
}
|
||||
|
||||
mongoose.connection.close()
|
||||
}
|
||||
deleteUsers()
|
||||
@@ -1,34 +0,0 @@
|
||||
const mongoose = require('mongoose')
|
||||
|
||||
const config = require('../config')
|
||||
|
||||
// Connect to the Mongo Database.
|
||||
mongoose.Promise = global.Promise
|
||||
mongoose.connect(config.database, () => {
|
||||
// mongoose.connection.db.dropDatabase()
|
||||
})
|
||||
|
||||
console.log(`config: ${JSON.stringify(config, null, 2)}`)
|
||||
|
||||
/*
|
||||
// Wipe the DB.
|
||||
function cleanDb () {
|
||||
for (const collection in mongoose.connection.collections) {
|
||||
if (mongoose.connection.collections.hasOwnProperty(collection)) {
|
||||
mongoose.connection.collections[collection].remove()
|
||||
}
|
||||
}
|
||||
console.log(`Database wiped.`)
|
||||
}
|
||||
cleanDb()
|
||||
*/
|
||||
|
||||
mongoose.connection.close()
|
||||
|
||||
console.log(`
|
||||
Here's how to wipe the db:
|
||||
1. mongo
|
||||
2. use p2pvps-server-dev
|
||||
3. db.dropDatabase()
|
||||
4. exit
|
||||
`)
|
||||
@@ -0,0 +1,6 @@
|
||||
|
||||
Here's how to wipe the db:
|
||||
1. mongo
|
||||
2. use koa-server-dev
|
||||
3. db.dropDatabase()
|
||||
4. exit
|
||||
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
Utility app to wipe the test database.
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
const mongoose = require('mongoose')
|
||||
|
||||
// Force test environment
|
||||
process.env.KOA_ENV = 'test'
|
||||
const config = require('../config')
|
||||
|
||||
async function cleanDb () {
|
||||
// Connect to the Mongo Database.
|
||||
mongoose.Promise = global.Promise
|
||||
mongoose.set('useCreateIndex', true) // Stop deprecation warning.
|
||||
await mongoose.connect(config.database, { useNewUrlParser: true })
|
||||
|
||||
console.log(`mongoose.connection.collections: ${JSON.stringify(mongoose.connection.collections, null, 2)}`)
|
||||
|
||||
for (const collection in mongoose.connection.collections) {
|
||||
if (mongoose.connection.collections.hasOwnProperty(collection)) {
|
||||
const thisCollection = mongoose.connection.collections[collection]
|
||||
console.log(`thisCollection: ${JSON.stringify(thisCollection, null, 2)}`)
|
||||
|
||||
await collection.deleteMany()
|
||||
}
|
||||
}
|
||||
|
||||
mongoose.connection.close()
|
||||
}
|
||||
cleanDb()
|
||||
Reference in New Issue
Block a user