mirror of
https://github.com/jambonz/jambonz-api-server.git
synced 2026-01-25 02:08:24 +00:00
feature/user-api-calls (#80)
* initial changes for jwt auth * return permissions as an array of string * basic GET, POST, DELETE user api calls * add permission checks * hide hashed_password * cleanup * add check if admin user is active * return account and serviceProvider sid un user object * add more values to user PUT * logout user after self delete, fix scope assignment * add admin scope user tests * fix test case and align jwt and api key data model in req.user * fixes for ibm speech * add limits license_count and voice_call_minutes * update limits enum again * rebase to main * allow predefined carriers and speech credentials for Account user * reverse the hasAccountPermissions changes * SpeechCredentials permissions * fix /Users/me api non-saas jambonz Co-authored-by: Dave Horton <daveh@beachdognet.com> Co-authored-by: eglehelms <e.helms@cognigy.com>
This commit is contained in:
@@ -22,6 +22,10 @@ DROP TABLE IF EXISTS lcr_routes;
|
||||
|
||||
DROP TABLE IF EXISTS password_settings;
|
||||
|
||||
DROP TABLE IF EXISTS user_permissions;
|
||||
|
||||
DROP TABLE IF EXISTS permissions;
|
||||
|
||||
DROP TABLE IF EXISTS predefined_sip_gateways;
|
||||
|
||||
DROP TABLE IF EXISTS predefined_smpp_gateways;
|
||||
@@ -79,7 +83,7 @@ CREATE TABLE account_limits
|
||||
(
|
||||
account_limits_sid CHAR(36) NOT NULL UNIQUE ,
|
||||
account_sid CHAR(36) NOT NULL,
|
||||
category ENUM('api_rate','voice_call_session', 'device','voice_call_minutes','voice_call_session_licensed', 'voice_call_minutes_licensed') NOT NULL,
|
||||
category ENUM('api_rate','voice_call_session', 'device') NOT NULL,
|
||||
quantity INTEGER NOT NULL,
|
||||
PRIMARY KEY (account_limits_sid)
|
||||
);
|
||||
@@ -145,6 +149,14 @@ require_digit BOOLEAN NOT NULL DEFAULT false,
|
||||
require_special_character BOOLEAN NOT NULL DEFAULT false
|
||||
);
|
||||
|
||||
CREATE TABLE permissions
|
||||
(
|
||||
permission_sid CHAR(36) NOT NULL UNIQUE ,
|
||||
name VARCHAR(32) NOT NULL UNIQUE ,
|
||||
description VARCHAR(255),
|
||||
PRIMARY KEY (permission_sid)
|
||||
);
|
||||
|
||||
CREATE TABLE predefined_carriers
|
||||
(
|
||||
predefined_carrier_sid CHAR(36) NOT NULL UNIQUE ,
|
||||
@@ -254,7 +266,7 @@ CREATE TABLE service_provider_limits
|
||||
(
|
||||
service_provider_limits_sid CHAR(36) NOT NULL UNIQUE ,
|
||||
service_provider_sid CHAR(36) NOT NULL,
|
||||
category ENUM('api_rate','voice_call_session', 'device','voice_call_minutes','voice_call_session_licensed', 'voice_call_minutes_licensed') NOT NULL,
|
||||
category ENUM('api_rate','voice_call_session', 'device') NOT NULL,
|
||||
quantity INTEGER NOT NULL,
|
||||
PRIMARY KEY (service_provider_limits_sid)
|
||||
);
|
||||
@@ -318,6 +330,14 @@ is_active BOOLEAN NOT NULL DEFAULT true,
|
||||
PRIMARY KEY (user_sid)
|
||||
);
|
||||
|
||||
CREATE TABLE user_permissions
|
||||
(
|
||||
user_permissions_sid CHAR(36) NOT NULL UNIQUE ,
|
||||
user_sid CHAR(36) NOT NULL,
|
||||
permission_sid CHAR(36) NOT NULL,
|
||||
PRIMARY KEY (user_permissions_sid)
|
||||
);
|
||||
|
||||
CREATE TABLE voip_carriers
|
||||
(
|
||||
voip_carrier_sid CHAR(36) NOT NULL UNIQUE ,
|
||||
@@ -481,6 +501,7 @@ ALTER TABLE call_routes ADD FOREIGN KEY application_sid_idxfk (application_sid)
|
||||
CREATE INDEX dns_record_sid_idx ON dns_records (dns_record_sid);
|
||||
ALTER TABLE dns_records ADD FOREIGN KEY account_sid_idxfk_4 (account_sid) REFERENCES accounts (account_sid);
|
||||
|
||||
CREATE INDEX permission_sid_idx ON permissions (permission_sid);
|
||||
CREATE INDEX predefined_carrier_sid_idx ON predefined_carriers (predefined_carrier_sid);
|
||||
CREATE INDEX predefined_sip_gateway_sid_idx ON predefined_sip_gateways (predefined_sip_gateway_sid);
|
||||
CREATE INDEX predefined_carrier_sid_idx ON predefined_sip_gateways (predefined_carrier_sid);
|
||||
@@ -552,6 +573,12 @@ CREATE INDEX service_provider_sid_idx ON users (service_provider_sid);
|
||||
ALTER TABLE users ADD FOREIGN KEY service_provider_sid_idxfk_6 (service_provider_sid) REFERENCES service_providers (service_provider_sid);
|
||||
|
||||
CREATE INDEX email_activation_code_idx ON users (email_activation_code);
|
||||
CREATE INDEX user_permissions_sid_idx ON user_permissions (user_permissions_sid);
|
||||
CREATE INDEX user_sid_idx ON user_permissions (user_sid);
|
||||
ALTER TABLE user_permissions ADD FOREIGN KEY user_sid_idxfk (user_sid) REFERENCES users (user_sid) ON DELETE CASCADE;
|
||||
|
||||
ALTER TABLE user_permissions ADD FOREIGN KEY permission_sid_idxfk (permission_sid) REFERENCES permissions (permission_sid);
|
||||
|
||||
CREATE INDEX voip_carrier_sid_idx ON voip_carriers (voip_carrier_sid);
|
||||
CREATE INDEX account_sid_idx ON voip_carriers (account_sid);
|
||||
ALTER TABLE voip_carriers ADD FOREIGN KEY account_sid_idxfk_10 (account_sid) REFERENCES accounts (account_sid);
|
||||
|
||||
122
db/jambones.sqs
122
db/jambones.sqs
File diff suppressed because one or more lines are too long
@@ -76,24 +76,28 @@ const checkApiTokens = (logger, token, done) => {
|
||||
}
|
||||
|
||||
// found api key
|
||||
const scope = [];
|
||||
let scope;
|
||||
//const scope = [];
|
||||
if (results[0].account_sid === null && results[0].service_provider_sid === null) {
|
||||
scope.push.apply(scope, ['admin', 'service_provider', 'account']);
|
||||
//scope.push.apply(scope, ['admin', 'service_provider', 'account']);
|
||||
scope = 'admin';
|
||||
}
|
||||
else if (results[0].service_provider_sid) {
|
||||
scope.push.apply(scope, ['service_provider', 'account']);
|
||||
//scope.push.apply(scope, ['service_provider', 'account']);
|
||||
scope = 'service_provider';
|
||||
}
|
||||
else {
|
||||
scope.push('account');
|
||||
//scope.push('account');
|
||||
scope = 'account';
|
||||
}
|
||||
|
||||
const user = {
|
||||
account_sid: results[0].account_sid,
|
||||
service_provider_sid: results[0].service_provider_sid,
|
||||
hasScope: (s) => scope.includes(s),
|
||||
hasAdminAuth: scope.length === 3,
|
||||
hasServiceProviderAuth: scope.includes('service_provider'),
|
||||
hasAccountAuth: scope.includes('account') && !scope.includes('service_provider')
|
||||
hasScope: (s) => s === scope,
|
||||
hasAdminAuth: scope === 'admin',
|
||||
hasServiceProviderAuth: scope === 'service_provider',
|
||||
hasAccountAuth: scope === 'account'
|
||||
};
|
||||
logger.info(user, `successfully validated with scope ${scope}`);
|
||||
return done(null, user, {scope});
|
||||
|
||||
@@ -7,16 +7,16 @@ const isAdminScope = (req, res, next) => {
|
||||
message: 'insufficient privileges'
|
||||
});
|
||||
};
|
||||
const isAdminOrSPScope = (req, res, next) => {
|
||||
if (req.user.hasScope('admin') || req.user.hasScope('service_provider')) return next();
|
||||
res.status(403).json({
|
||||
status: 'fail',
|
||||
message: 'insufficient privileges'
|
||||
});
|
||||
};
|
||||
// const isAdminOrSPScope = (req, res, next) => {
|
||||
// if (req.user.hasScope('admin') || req.user.hasScope('service_provider')) return next();
|
||||
// res.status(403).json({
|
||||
// status: 'fail',
|
||||
// message: 'insufficient privileges'
|
||||
// });
|
||||
// };
|
||||
|
||||
api.use('/BetaInviteCodes', isAdminScope, require('./beta-invite-codes'));
|
||||
api.use('/ServiceProviders', isAdminOrSPScope, require('./service-providers'));
|
||||
api.use('/ServiceProviders', require('./service-providers'));
|
||||
api.use('/VoipCarriers', require('./voip-carriers'));
|
||||
api.use('/Webhooks', require('./webhooks'));
|
||||
api.use('/SipGateways', require('./sip-gateways'));
|
||||
@@ -44,7 +44,7 @@ api.use('/Subscriptions', require('./subscriptions'));
|
||||
api.use('/Invoices', require('./invoices'));
|
||||
api.use('/InviteCodes', require('./invite-codes'));
|
||||
api.use('/PredefinedCarriers', require('./predefined-carriers'));
|
||||
api.use('/PasswordSettings', isAdminScope, require('./password-settings'));
|
||||
api.use('/PasswordSettings', require('./password-settings'));
|
||||
|
||||
// messaging
|
||||
api.use('/Smpps', require('./smpps')); // our smpp server info
|
||||
|
||||
@@ -31,9 +31,9 @@ router.post('/', async(req, res) => {
|
||||
const account_sid = parseAccountSid(req);
|
||||
let service_provider_sid;
|
||||
if (!account_sid) {
|
||||
if (!req.user.hasServiceProviderAuth) {
|
||||
if (!req.user.hasServiceProviderAuth && !req.user.hasAdminAuth) {
|
||||
logger.error('POST /SpeechCredentials invalid credentials');
|
||||
return res.send(403);
|
||||
return res.sendStatus(403);
|
||||
}
|
||||
service_provider_sid = parseServiceProviderSid(req);
|
||||
}
|
||||
|
||||
@@ -41,14 +41,15 @@ router.post('/', async(req, res) => {
|
||||
const [p] = await promisePool.query(retrievePemissionsSql, r[0].user_sid);
|
||||
const permissions = p.map((x) => x.name);
|
||||
const obj = {user_sid: r[0].user_sid, scope: 'admin', force_change, permissions};
|
||||
if (r[0].service_provider_sid) {
|
||||
if (r[0].service_provider_sid && r[0].account_sid) {
|
||||
obj.scope = 'account';
|
||||
obj.service_provider_sid = r[0].service_provider_sid;
|
||||
obj.account_sid = r[0].account_sid;
|
||||
}
|
||||
else if (r[0].service_provider_sid) {
|
||||
obj.scope = 'service_provider';
|
||||
obj.service_provider_sid = r[0].service_provider_sid;
|
||||
}
|
||||
else if (r[0].account_sid) {
|
||||
obj.scope = 'account';
|
||||
obj.account_sid = r[0].account_sid;
|
||||
}
|
||||
const payload = {
|
||||
scope: obj.scope,
|
||||
permissions,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
const router = require('express').Router();
|
||||
const {promisePool} = require('../../db');
|
||||
const {DbErrorUnprocessableRequest} = require('../../utils/errors');
|
||||
const {DbErrorUnprocessableRequest, DbErrorForbidden} = require('../../utils/errors');
|
||||
const Webhook = require('../../models/webhook');
|
||||
const ServiceProvider = require('../../models/service-provider');
|
||||
const Account = require('../../models/account');
|
||||
@@ -27,8 +27,27 @@ WHERE voip_carrier_sid IN (
|
||||
WHERE service_provider_sid = ?
|
||||
)`;
|
||||
|
||||
/* only admin users can add a service provider */
|
||||
async function validateAdd(req) {
|
||||
if (!req.user.hasAdminAuth) {
|
||||
throw new DbErrorForbidden('only admin users can add a service provider');
|
||||
}
|
||||
}
|
||||
|
||||
async function validateUpdate(req) {
|
||||
if (req.user.hasScope('admin')) return ;
|
||||
if (req.user.hasScope('service_provider')) {
|
||||
const service_provider_sid = parseServiceProviderSid(req);
|
||||
if (service_provider_sid === req.user.service_provider_sid) return ;
|
||||
}
|
||||
throw new DbErrorForbidden('insufficient permissions to update service provider');
|
||||
}
|
||||
|
||||
/* can not delete a service provider if it has any active accounts */
|
||||
async function noActiveAccounts(req, sid) {
|
||||
if (!req.user.hasAdminAuth) {
|
||||
throw new DbErrorForbidden('only admin users can delete a service provider');
|
||||
}
|
||||
const activeAccounts = await ServiceProvider.getForeignKeyReferences('accounts.service_provider_sid', sid);
|
||||
if (activeAccounts > 0) throw new DbErrorUnprocessableRequest('cannot delete service provider with active accounts');
|
||||
|
||||
@@ -43,7 +62,7 @@ decorate(router, ServiceProvider, ['delete'], preconditions);
|
||||
|
||||
router.use('/:sid/RecentCalls', hasServiceProviderPermissions, require('./recent-calls'));
|
||||
router.use('/:sid/Alerts', hasServiceProviderPermissions, require('./alerts'));
|
||||
router.use('/:sid/SpeechCredentials', hasServiceProviderPermissions, require('./speech-credentials'));
|
||||
router.use('/:sid/SpeechCredentials', require('./speech-credentials'));
|
||||
router.use('/:sid/Limits', hasServiceProviderPermissions, require('./limits'));
|
||||
router.use('/:sid/PredefinedCarriers', hasServiceProviderPermissions, require('./add-from-predefined-carrier'));
|
||||
router.get('/:sid/Accounts', async(req, res) => {
|
||||
@@ -134,6 +153,7 @@ router.get('/:sid/ApiKeys', async(req, res) => {
|
||||
router.post('/', async(req, res) => {
|
||||
const logger = req.app.locals.logger;
|
||||
try {
|
||||
await validateAdd(req);
|
||||
|
||||
// create webhooks if provided
|
||||
const obj = Object.assign({}, req.body);
|
||||
@@ -155,8 +175,15 @@ router.post('/', async(req, res) => {
|
||||
/* list */
|
||||
router.get('/', async(req, res) => {
|
||||
const logger = req.app.locals.logger;
|
||||
|
||||
try {
|
||||
const results = await ServiceProvider.retrieveAll();
|
||||
logger.debug({results, user: req.user}, 'ServiceProvider.retrieveAll');
|
||||
if (req.user.hasScope('service_provider') || req.user.hasScope('account')) {
|
||||
logger.debug(`Filtering results for ${req.user.service_provider_sid}`);
|
||||
return res.status(200).json(results.filter((e) => req.user.service_provider_sid === e.service_provider_sid));
|
||||
}
|
||||
|
||||
res.status(200).json(results);
|
||||
} catch (err) {
|
||||
sysError(logger, res, err);
|
||||
@@ -181,6 +208,8 @@ router.put('/:sid', async(req, res) => {
|
||||
const sid = req.params.sid;
|
||||
const logger = req.app.locals.logger;
|
||||
try {
|
||||
await validateUpdate(req);
|
||||
|
||||
// create webhooks if provided
|
||||
const obj = Object.assign({}, req.body);
|
||||
for (const prop of ['registration_hook']) {
|
||||
|
||||
@@ -119,9 +119,9 @@ router.post('/', async(req, res) => {
|
||||
const account_sid = req.user.account_sid || req.body.account_sid;
|
||||
let service_provider_sid;
|
||||
if (!account_sid) {
|
||||
if (!req.user.hasServiceProviderAuth) {
|
||||
if (!req.user.hasServiceProviderAuth && !req.user.hasAdminAuth) {
|
||||
logger.error('POST /SpeechCredentials invalid credentials');
|
||||
return res.send(403);
|
||||
return res.sendStatus(403);
|
||||
}
|
||||
service_provider_sid = parseServiceProviderSid(req);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
const router = require('express').Router();
|
||||
const User = require('../../models/user');
|
||||
const jwt = require('jsonwebtoken');
|
||||
const request = require('request');
|
||||
const {DbErrorBadRequest} = require('../../utils/errors');
|
||||
const {generateHashedPassword, verifyPassword} = require('../../utils/password-utils');
|
||||
const {promisePool} = require('../../db');
|
||||
@@ -11,6 +12,11 @@ FROM users user
|
||||
JOIN accounts AS account ON account.account_sid = user.account_sid
|
||||
LEFT JOIN service_providers as sp ON account.service_provider_sid = sp.service_provider_sid
|
||||
WHERE user.user_sid = ?`;
|
||||
const retrieveMyDetails2 = `SELECT *
|
||||
FROM users user
|
||||
LEFT JOIN accounts AS account ON account.account_sid = user.account_sid
|
||||
LEFT JOIN service_providers as sp ON sp.service_provider_sid = user.service_provider_sid
|
||||
WHERE user.user_sid = ?`;
|
||||
const retrieveSql = 'SELECT * from users where user_sid = ?';
|
||||
const retrieveProducts = `SELECT *
|
||||
FROM account_products
|
||||
@@ -23,7 +29,15 @@ const updateSql = 'UPDATE users set hashed_password = ?, force_change = false WH
|
||||
const retrieveStaticIps = 'SELECT * FROM account_static_ips WHERE account_sid = ?';
|
||||
|
||||
const validateRequest = async(user_sid, payload) => {
|
||||
const {old_password, new_password, name, email, email_activation_code} = payload;
|
||||
const {
|
||||
old_password,
|
||||
new_password,
|
||||
initial_password,
|
||||
name,
|
||||
email,
|
||||
email_activation_code,
|
||||
force_change,
|
||||
is_active} = payload;
|
||||
|
||||
const [r] = await promisePool.query(retrieveSql, user_sid);
|
||||
if (r.length === 0) return null;
|
||||
@@ -37,10 +51,11 @@ const validateRequest = async(user_sid, payload) => {
|
||||
throw new DbErrorBadRequest('can not change password when using oauth2');
|
||||
}
|
||||
|
||||
if ((email && !email_activation_code) || (email_activation_code && !email)) {
|
||||
if (email_activation_code && !email) {
|
||||
throw new DbErrorBadRequest('email and email_activation_code both required');
|
||||
}
|
||||
if (!name && !new_password && !email) throw new DbErrorBadRequest('no updates requested');
|
||||
if (!name && !new_password && !email && !initial_password && !force_change && !is_active)
|
||||
throw new DbErrorBadRequest('no updates requested');
|
||||
|
||||
return user;
|
||||
};
|
||||
@@ -69,14 +84,14 @@ router.get('/', async(req, res) => {
|
||||
if (results.length === 0) throw new Error('failure retrieving users list');
|
||||
|
||||
usersList = results.map((user) => {
|
||||
const {user_sid, name, email, force_change, is_active} = user;
|
||||
const {user_sid, name, email, force_change, is_active, account_sid, service_provider_sid} = user;
|
||||
let scope;
|
||||
if (!user.account_sid && !user.service_provider_sid) {
|
||||
scope = 'admin';
|
||||
} else if (user.service_provider_sid) {
|
||||
if (account_sid && service_provider_sid) {
|
||||
scope = 'account';
|
||||
} else if (service_provider_sid) {
|
||||
scope = 'service_provider';
|
||||
} else {
|
||||
scope = 'account';
|
||||
scope = 'admin';
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -85,7 +100,9 @@ router.get('/', async(req, res) => {
|
||||
email,
|
||||
scope,
|
||||
force_change,
|
||||
is_active
|
||||
is_active,
|
||||
account_sid,
|
||||
service_provider_sid
|
||||
};
|
||||
});
|
||||
} catch (err) {
|
||||
@@ -100,80 +117,116 @@ router.get('/me', async(req, res) => {
|
||||
|
||||
if (!user_sid) return res.sendStatus(403);
|
||||
|
||||
let payload;
|
||||
try {
|
||||
const [r] = await promisePool.query({sql: retrieveMyDetails, nestTables: true}, user_sid);
|
||||
logger.debug(r, 'retrieved user details');
|
||||
const payload = r[0];
|
||||
const {user, account, sp} = payload;
|
||||
['hashed_password', 'salt', 'phone_activation_code', 'email_activation_code', 'account_sid'].forEach((prop) => {
|
||||
delete user[prop];
|
||||
});
|
||||
['email_validated', 'phone_validated', 'force_change'].forEach((prop) => user[prop] = !!user[prop]);
|
||||
['is_active'].forEach((prop) => account[prop] = !!account[prop]);
|
||||
account.root_domain = sp.root_domain;
|
||||
delete payload.sp;
|
||||
|
||||
/* get api keys */
|
||||
const [keys] = await promisePool.query('SELECT * from api_keys WHERE account_sid = ?', account.account_sid);
|
||||
payload.api_keys = keys.map((k) => {
|
||||
return {
|
||||
api_key_sid: k.api_key_sid,
|
||||
//token: k.token.replace(/.(?=.{4,}$)/g, '*'),
|
||||
token: k.token,
|
||||
last_used: k.last_used,
|
||||
created_at: k.created_at
|
||||
};
|
||||
});
|
||||
|
||||
/* get products */
|
||||
const [products] = await promisePool.query({sql: retrieveProducts, nestTables: true}, account.account_sid);
|
||||
if (!products.length || !products[0].account_subscriptions) {
|
||||
throw new Error('account is missing a subscription');
|
||||
}
|
||||
const account_subscription = products[0].account_subscriptions;
|
||||
payload.subscription = {
|
||||
status: 'active',
|
||||
account_subscription_sid: account_subscription.account_subscription_sid,
|
||||
start_date: account_subscription.effective_start_date,
|
||||
products: products.map((prd) => {
|
||||
return {
|
||||
name: prd.products.name,
|
||||
units: prd.products.unit_label,
|
||||
quantity: prd.account_products.quantity
|
||||
};
|
||||
})
|
||||
};
|
||||
if (account_subscription.pending) {
|
||||
Object.assign(payload.subscription, {
|
||||
status: 'suspended',
|
||||
suspend_reason: account_subscription.pending_reason
|
||||
if (process.env.JAMBONES_HOSTING) {
|
||||
const [r] = await promisePool.query({sql: retrieveMyDetails, nestTables: true}, user_sid);
|
||||
logger.debug(r, 'retrieved user details');
|
||||
payload = r[0];
|
||||
const {user, account, sp} = payload;
|
||||
['hashed_password', 'salt', 'phone_activation_code', 'email_activation_code', 'account_sid'].forEach((prop) => {
|
||||
delete user[prop];
|
||||
});
|
||||
}
|
||||
const {
|
||||
last4,
|
||||
exp_month,
|
||||
exp_year,
|
||||
card_type,
|
||||
stripe_statement_descriptor
|
||||
} = account_subscription;
|
||||
if (last4) {
|
||||
const real_last4 = decrypt(last4);
|
||||
Object.assign(payload.subscription, {
|
||||
last4: real_last4,
|
||||
['email_validated', 'phone_validated', 'force_change'].forEach((prop) => user[prop] = !!user[prop]);
|
||||
['is_active'].forEach((prop) => account[prop] = !!account[prop]);
|
||||
account.root_domain = sp.root_domain;
|
||||
delete payload.sp;
|
||||
|
||||
/* get api keys */
|
||||
const [keys] = await promisePool.query('SELECT * from api_keys WHERE account_sid = ?', account.account_sid);
|
||||
payload.api_keys = keys.map((k) => {
|
||||
return {
|
||||
api_key_sid: k.api_key_sid,
|
||||
//token: k.token.replace(/.(?=.{4,}$)/g, '*'),
|
||||
token: k.token,
|
||||
last_used: k.last_used,
|
||||
created_at: k.created_at
|
||||
};
|
||||
});
|
||||
|
||||
/* get products */
|
||||
const [products] = await promisePool.query({sql: retrieveProducts, nestTables: true}, account.account_sid);
|
||||
if (!products.length || !products[0].account_subscriptions) {
|
||||
throw new Error('account is missing a subscription');
|
||||
}
|
||||
const account_subscription = products[0].account_subscriptions;
|
||||
payload.subscription = {
|
||||
status: 'active',
|
||||
account_subscription_sid: account_subscription.account_subscription_sid,
|
||||
start_date: account_subscription.effective_start_date,
|
||||
products: products.map((prd) => {
|
||||
return {
|
||||
name: prd.products.name,
|
||||
units: prd.products.unit_label,
|
||||
quantity: prd.account_products.quantity
|
||||
};
|
||||
})
|
||||
};
|
||||
if (account_subscription.pending) {
|
||||
Object.assign(payload.subscription, {
|
||||
status: 'suspended',
|
||||
suspend_reason: account_subscription.pending_reason
|
||||
});
|
||||
}
|
||||
const {
|
||||
last4,
|
||||
exp_month,
|
||||
exp_year,
|
||||
card_type,
|
||||
statement_descriptor: stripe_statement_descriptor
|
||||
stripe_statement_descriptor
|
||||
} = account_subscription;
|
||||
if (last4) {
|
||||
const real_last4 = decrypt(last4);
|
||||
Object.assign(payload.subscription, {
|
||||
last4: real_last4,
|
||||
exp_month,
|
||||
exp_year,
|
||||
card_type,
|
||||
statement_descriptor: stripe_statement_descriptor
|
||||
});
|
||||
}
|
||||
|
||||
/* get static ips */
|
||||
const [static_ips] = await promisePool.query(retrieveStaticIps, account.account_sid);
|
||||
payload.static_ips = static_ips.map((r) => r.public_ipv4);
|
||||
}
|
||||
else {
|
||||
const [r] = await promisePool.query({sql: retrieveMyDetails2, nestTables: true}, user_sid);
|
||||
logger.debug(r, 'retrieved user details');
|
||||
payload = r[0];
|
||||
const {user} = payload;
|
||||
['hashed_password', 'salt', 'phone_activation_code', 'email_activation_code'].forEach((prop) => {
|
||||
delete user[prop];
|
||||
});
|
||||
['email_validated', 'phone_validated', 'force_change'].forEach((prop) => user[prop] = !!user[prop]);
|
||||
}
|
||||
logger.debug({payload}, 'returning user details');
|
||||
res.json(payload);
|
||||
} catch (err) {
|
||||
sysError(logger, res, err);
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/:user_sid', async(req, res) => {
|
||||
const logger = req.app.locals.logger;
|
||||
const token = req.user.jwt;
|
||||
const decodedJwt = jwt.verify(token, process.env.JWT_SECRET);
|
||||
const {user_sid} = req.params;
|
||||
|
||||
try {
|
||||
const [user] = await User.retrieve(user_sid);
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
const {hashed_password, ...rest} = user;
|
||||
if (!user) throw new Error('failure retrieving user');
|
||||
|
||||
if (decodedJwt.scope === 'admin' ||
|
||||
decodedJwt.scope === 'account' && decodedJwt.account_sid === user.account_sid ||
|
||||
decodedJwt.scope === 'service_provider' && decodedJwt.service_provider_sid === user.service_provider_sid) {
|
||||
res.status(200).json(rest);
|
||||
} else {
|
||||
res.sendStatus(403);
|
||||
}
|
||||
|
||||
/* get static ips */
|
||||
const [static_ips] = await promisePool.query(retrieveStaticIps, account.account_sid);
|
||||
payload.static_ips = static_ips.map((r) => r.public_ipv4);
|
||||
|
||||
logger.debug({payload}, 'returning user details');
|
||||
|
||||
res.json(payload);
|
||||
} catch (err) {
|
||||
sysError(logger, res, err);
|
||||
}
|
||||
@@ -182,9 +235,30 @@ router.get('/me', async(req, res) => {
|
||||
router.put('/:user_sid', async(req, res) => {
|
||||
const logger = req.app.locals.logger;
|
||||
const {user_sid} = req.params;
|
||||
const {old_password, new_password, name, email, email_activation_code} = req.body;
|
||||
const user = await User.retrieve(user_sid);
|
||||
const token = req.user.jwt;
|
||||
const decodedJwt = jwt.verify(token, process.env.JWT_SECRET);
|
||||
const {
|
||||
old_password,
|
||||
new_password,
|
||||
initial_password,
|
||||
email_activation_code,
|
||||
email,
|
||||
name,
|
||||
is_active,
|
||||
force_change,
|
||||
account_sid,
|
||||
service_provider_sid
|
||||
} = req.body;
|
||||
|
||||
if (req.user.user_sid && req.user.user_sid !== user_sid) return res.sendStatus(403);
|
||||
//if (req.user.user_sid && req.user.user_sid !== user_sid) return res.sendStatus(403);
|
||||
|
||||
if (decodedJwt.scope !== 'admin' &&
|
||||
!(decodedJwt.scope === 'account' && decodedJwt.account_sid === user[0].account_sid) &&
|
||||
!(decodedJwt.scope === 'service_provider' && decodedJwt.service_provider_sid === user[0].service_provider_sid) &&
|
||||
(req.user.user_sid && req.user.user_sid !== user_sid)) {
|
||||
return res.sendStatus(403);
|
||||
}
|
||||
|
||||
try {
|
||||
const user = await validateRequest(user_sid, req.body);
|
||||
@@ -209,10 +283,51 @@ router.put('/:user_sid', async(req, res) => {
|
||||
if (0 === r.changedRows) throw new Error('database update failed');
|
||||
}
|
||||
|
||||
if (email) {
|
||||
if (initial_password) {
|
||||
const passwordHash = await generateHashedPassword(initial_password);
|
||||
const r = await promisePool.execute(
|
||||
'UPDATE users SET email = ?, email_activation_code = ?, email_validated = 0 WHERE user_sid = ?',
|
||||
[email, email_activation_code, user_sid]);
|
||||
'UPDATE users SET hashed_password = ? WHERE user_sid = ?',
|
||||
[passwordHash, user_sid]
|
||||
);
|
||||
if (0 === r.changedRows) throw new Error('database update failed');
|
||||
}
|
||||
|
||||
if (is_active) {
|
||||
const r = await promisePool.execute('UPDATE users SET is_active = ? WHERE user_sid = ?', [is_active, user_sid]);
|
||||
if (0 === r.changedRows) throw new Error('database update failed');
|
||||
}
|
||||
|
||||
if (force_change) {
|
||||
const r = await promisePool.execute(
|
||||
'UPDATE users SET force_change = ? WHERE user_sid = ?',
|
||||
[force_change, user_sid]);
|
||||
if (0 === r.changedRows) throw new Error('database update failed');
|
||||
}
|
||||
|
||||
if (account_sid || account_sid === null) {
|
||||
const r = await promisePool.execute(
|
||||
'UPDATE users SET account_sid = ? WHERE user_sid = ?',
|
||||
[account_sid, user_sid]);
|
||||
if (0 === r.changedRows) throw new Error('database update failed');
|
||||
}
|
||||
|
||||
if (service_provider_sid || service_provider_sid === null) {
|
||||
const r = await promisePool.execute(
|
||||
'UPDATE users SET service_provider_sid = ? WHERE user_sid = ?',
|
||||
[service_provider_sid, user_sid]);
|
||||
if (0 === r.changedRows) throw new Error('database update failed');
|
||||
}
|
||||
|
||||
if (email) {
|
||||
if (email_activation_code) {
|
||||
const r = await promisePool.execute(
|
||||
'UPDATE users SET email = ?, email_activation_code = ?, email_validated = 0 WHERE user_sid = ?',
|
||||
[email, email_activation_code, user_sid]);
|
||||
if (0 === r.changedRows) throw new Error('database update failed');
|
||||
}
|
||||
const r = await promisePool.execute(
|
||||
'UPDATE users SET email = ? WHERE user_sid = ?',
|
||||
[email, user_sid]);
|
||||
if (0 === r.changedRows) throw new Error('database update failed');
|
||||
|
||||
if (process.env.NODE_ENV !== 'test') {
|
||||
@@ -225,5 +340,94 @@ router.put('/:user_sid', async(req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/', async(req, res) => {
|
||||
const logger = req.app.locals.logger;
|
||||
const passwordHash = await generateHashedPassword(req.body.initial_password);
|
||||
const payload = {
|
||||
...req.body,
|
||||
provider: 'local',
|
||||
hashed_password: passwordHash,
|
||||
};
|
||||
const allUsers = await User.retrieveAll();
|
||||
const token = req.user.jwt;
|
||||
const decodedJwt = jwt.verify(token, process.env.JWT_SECRET);
|
||||
delete payload.initial_password;
|
||||
|
||||
try {
|
||||
const email = allUsers.find((e) => e.email === payload.email);
|
||||
if (email) {
|
||||
logger.debug({payload}, 'user with this email already exists');
|
||||
return res.sendStatus(403);
|
||||
}
|
||||
|
||||
if (decodedJwt.scope === 'admin') {
|
||||
logger.debug({payload}, 'POST /users');
|
||||
const uuid = await User.make(payload);
|
||||
res.status(201).json({user_sid: uuid});
|
||||
}
|
||||
else if (decodedJwt.scope === 'account') {
|
||||
logger.debug({payload}, 'POST /users');
|
||||
const uuid = await User.make({
|
||||
...payload,
|
||||
account_sid: decodedJwt.account_sid,
|
||||
});
|
||||
res.status(201).json({user_sid: uuid});
|
||||
}
|
||||
else if (decodedJwt.scope === 'service_provider') {
|
||||
logger.debug({payload}, 'POST /users');
|
||||
const uuid = await User.make({
|
||||
...payload,
|
||||
service_provider_sid: decodedJwt.service_provider_sid,
|
||||
});
|
||||
res.status(201).json({user_sid: uuid});
|
||||
}
|
||||
else {
|
||||
throw new DbErrorBadRequest(`invalid scope: ${decodedJwt.scope}`);
|
||||
}
|
||||
} catch (err) {
|
||||
sysError(logger, res, err);
|
||||
}
|
||||
});
|
||||
|
||||
router.delete('/:user_sid', async(req, res) => {
|
||||
const logger = req.app.locals.logger;
|
||||
const {user_sid} = req.params;
|
||||
const token = req.user.jwt;
|
||||
const decodedJwt = jwt.verify(token, process.env.JWT_SECRET);
|
||||
const allUsers = await User.retrieveAll();
|
||||
const activeAdminUsers = allUsers.filter((e) => !e.account_sid && !e.service_provider_sid && e.is_active);
|
||||
const user = await User.retrieve(user_sid);
|
||||
|
||||
try {
|
||||
if (decodedJwt.scope === 'admin' && activeAdminUsers.length === 1) {
|
||||
throw new Error('cannot delete this admin user - there are no other active admin users');
|
||||
}
|
||||
|
||||
if (decodedJwt.scope === 'admin' ||
|
||||
(decodedJwt.scope === 'account' && decodedJwt.account_sid === user[0].account_sid) ||
|
||||
(decodedJwt.scope === 'service_provider' && decodedJwt.service_provider_sid === user[0].service_provider_sid)) {
|
||||
await User.remove(user_sid);
|
||||
//logout user after self-delete
|
||||
if (decodedJwt.user_sid === user_sid) {
|
||||
request({
|
||||
url:'http://localhost:3000/v1/logout',
|
||||
method: 'POST',
|
||||
}, (err) => {
|
||||
if (err) {
|
||||
logger.error(err, 'could not log out user');
|
||||
return res.sendStatus(500);
|
||||
}
|
||||
logger.debug({user}, 'user deleted and logged out');
|
||||
});
|
||||
}
|
||||
return res.sendStatus(204);
|
||||
} else {
|
||||
throw new DbErrorBadRequest(`invalid scope: ${decodedJwt.scope}`);
|
||||
}
|
||||
} catch (err) {
|
||||
sysError(logger, res, err);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
module.exports = router;
|
||||
|
||||
@@ -149,6 +149,7 @@ const parseAccountSid = (req) => {
|
||||
|
||||
const hasAccountPermissions = (req, res, next) => {
|
||||
if (req.user.hasScope('admin')) return next();
|
||||
if (req.user.hasScope('service_provider')) return next();
|
||||
if (req.user.hasScope('account')) {
|
||||
const account_sid = parseAccountSid(req);
|
||||
if (account_sid === req.user.account_sid) return next();
|
||||
|
||||
@@ -546,6 +546,42 @@ paths:
|
||||
explode: false
|
||||
schema:
|
||||
type: string
|
||||
get:
|
||||
summary: retrieve user information
|
||||
operationId: getUser
|
||||
requestBody:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
name:
|
||||
type: string
|
||||
email:
|
||||
type: string
|
||||
is_active:
|
||||
type: boolean
|
||||
force_change:
|
||||
type: boolean
|
||||
scope:
|
||||
type: string
|
||||
permissions:
|
||||
type: array
|
||||
responses:
|
||||
204:
|
||||
description: user information
|
||||
403:
|
||||
description: user information
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/GeneralError'
|
||||
500:
|
||||
description: system error
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/GeneralError'
|
||||
put:
|
||||
summary: update user information
|
||||
operationId: updateUser
|
||||
@@ -567,11 +603,21 @@ paths:
|
||||
new_password:
|
||||
type: string
|
||||
description: new password
|
||||
name:
|
||||
type: string
|
||||
is_active:
|
||||
type: boolean
|
||||
force_change:
|
||||
type: boolean
|
||||
scope:
|
||||
type: string
|
||||
permissions:
|
||||
type: array
|
||||
responses:
|
||||
204:
|
||||
description: user updated
|
||||
403:
|
||||
description: password change failed
|
||||
description: user update failed
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
@@ -582,6 +628,63 @@ paths:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/GeneralError'
|
||||
post:
|
||||
summary: create a new user
|
||||
operationId: createUser
|
||||
requestBody:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
name:
|
||||
type: string
|
||||
email:
|
||||
type: string
|
||||
is_active:
|
||||
type: boolean
|
||||
force_change:
|
||||
type: boolean
|
||||
scope:
|
||||
type: string
|
||||
permissions:
|
||||
type: array
|
||||
force_change:
|
||||
type: boolean
|
||||
old_password:
|
||||
type: string
|
||||
description: existing password, which is to be replaced
|
||||
responses:
|
||||
204:
|
||||
description: user created
|
||||
403:
|
||||
description: user creation failed
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/GeneralError'
|
||||
500:
|
||||
description: system error
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/GeneralError'
|
||||
delete:
|
||||
summary: delete a user
|
||||
operationId: deleteUser
|
||||
responses:
|
||||
204:
|
||||
description: user deleted
|
||||
404:
|
||||
description: user not found
|
||||
403:
|
||||
description: unauthorized
|
||||
500:
|
||||
description: system error
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/GeneralError'
|
||||
/Users/me:
|
||||
get:
|
||||
summary: retrieve details about logged-in user and associated account
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
"scripts": {
|
||||
"start": "node app.js",
|
||||
"test": "NODE_ENV=test JAMBONES_AUTH_USE_JWT=1 APPLY_JAMBONZ_DB_LIMITS=1 JWT_SECRET=foobarbazzle JAMBONES_MYSQL_HOST=127.0.0.1 JAMBONES_MYSQL_PORT=3360 JAMBONES_MYSQL_USER=jambones_test JAMBONES_MYSQL_PASSWORD=jambones_test JAMBONES_MYSQL_DATABASE=jambones_test JAMBONES_REDIS_HOST=localhost JAMBONES_REDIS_PORT=16379 JAMBONES_TIME_SERIES_HOST=127.0.0.1 JAMBONES_LOGLEVEL=error JAMBONES_CREATE_CALL_URL=http://localhost/v1/createCall K8S=true K8S_FEATURE_SERVER_SERVICE_NAME=127.0.0.1 K8S_FEATURE_SERVER_SERVICE_PORT=3100 node test/ ",
|
||||
"integration-test": "NODE_ENV=test JAMBONES_TIME_SERIES_HOST=127.0.0.1 AWS_REGION='us-east-1' JAMBONES_CURRENCY=USD JWT_SECRET=foobarbazzle JAMBONES_MYSQL_HOST=127.0.0.1 JAMBONES_MYSQL_PORT=3360 JAMBONES_MYSQL_USER=jambones_test JAMBONES_MYSQL_PASSWORD=jambones_test JAMBONES_MYSQL_DATABASE=jambones_test JAMBONES_REDIS_HOST=localhost JAMBONES_REDIS_PORT=16379 JAMBONES_LOGLEVEL=debug JAMBONES_CREATE_CALL_URL=http://localhost/v1/createCall node test/serve-integration.js",
|
||||
"integration-test": "NODE_ENV=test JAMBONES_AUTH_USE_JWT=1 JAMBONES_TIME_SERIES_HOST=127.0.0.1 AWS_REGION='us-east-1' JAMBONES_CURRENCY=USD JWT_SECRET=foobarbazzle JAMBONES_MYSQL_HOST=127.0.0.1 JAMBONES_MYSQL_PORT=3360 JAMBONES_MYSQL_USER=jambones_test JAMBONES_MYSQL_PASSWORD=jambones_test JAMBONES_MYSQL_DATABASE=jambones_test JAMBONES_REDIS_HOST=localhost JAMBONES_REDIS_PORT=16379 JAMBONES_LOGLEVEL=debug JAMBONES_CREATE_CALL_URL=http://localhost/v1/createCall node test/serve-integration.js",
|
||||
"upgrade-db": "node ./db/upgrade-jambonz-db.js",
|
||||
"coverage": "./node_modules/.bin/nyc --reporter html --report-dir ./coverage npm run test",
|
||||
"jslint": "eslint app.js lib",
|
||||
|
||||
@@ -79,13 +79,14 @@ test('service provider tests', async(t) => {
|
||||
}
|
||||
});
|
||||
//console.log(`result: ${JSON.stringify(result)}`);
|
||||
t.ok(result.statusCode === 422, 'cannot add two service providers with the same name');
|
||||
t.ok(result.statusCode === 422, 'cannot add two service providers with the same root domain');
|
||||
|
||||
/* query all service providers */
|
||||
result = await request.get('/ServiceProviders', {
|
||||
auth: authAdmin,
|
||||
json: true,
|
||||
});
|
||||
console.log(JSON.stringify(result));
|
||||
t.ok(result.length === 2 , 'successfully queried all service providers');
|
||||
|
||||
/* query one service providers */
|
||||
|
||||
174
test/users.js
174
test/users.js
@@ -1,8 +1,10 @@
|
||||
const test = require('tape') ;
|
||||
const jwt = require('jsonwebtoken');
|
||||
const request = require('request-promise-native').defaults({
|
||||
baseUrl: 'http://127.0.0.1:3000/v1'
|
||||
});
|
||||
const exec = require('child_process').exec ;
|
||||
const {generateHashedPassword} = require('../lib/utils/password-utils');
|
||||
|
||||
|
||||
process.on('unhandledRejection', (reason, p) => {
|
||||
@@ -21,7 +23,7 @@ test('add an admin user', (t) => {
|
||||
|
||||
test('user tests', async(t) => {
|
||||
const app = require('../app');
|
||||
let sid;
|
||||
const password = await generateHashedPassword('abcd1234-');
|
||||
try {
|
||||
let result;
|
||||
|
||||
@@ -35,16 +37,180 @@ test('user tests', async(t) => {
|
||||
}
|
||||
});
|
||||
t.ok(result.statusCode === 200 && result.body.token, 'successfully logged in as admin');
|
||||
const authAdmin = {bearer: result.body.token};
|
||||
const decodedJwt = jwt.verify(result.body.token, process.env.JWT_SECRET);
|
||||
|
||||
/* add admin user */
|
||||
result = await request.post(`/Users`, {
|
||||
resolveWithFullResponse: true,
|
||||
json: true,
|
||||
auth: authAdmin,
|
||||
body: {
|
||||
name: 'admin2',
|
||||
email: 'admin2@jambonz.com',
|
||||
is_active: true,
|
||||
force_change: true,
|
||||
initial_password: password,
|
||||
}
|
||||
});
|
||||
t.ok(result.statusCode === 201 && result.body.user_sid, 'admin user created');
|
||||
const admin_user_sid = result.body.user_sid;
|
||||
|
||||
/* add a service provider */
|
||||
result = await request.post('/ServiceProviders', {
|
||||
resolveWithFullResponse: true,
|
||||
auth: authAdmin,
|
||||
json: true,
|
||||
body: {
|
||||
name: 'sp',
|
||||
}
|
||||
});
|
||||
t.ok(result.statusCode === 201, 'successfully created service provider');
|
||||
const sp_sid = result.body.sid;
|
||||
|
||||
/* add service_provider user */
|
||||
result = await request.post(`/Users`, {
|
||||
resolveWithFullResponse: true,
|
||||
json: true,
|
||||
auth: authAdmin,
|
||||
body: {
|
||||
name: 'service_provider',
|
||||
email: 'sp@jambonz.com',
|
||||
is_active: true,
|
||||
force_change: true,
|
||||
initial_password: password,
|
||||
service_provider_sid: sp_sid,
|
||||
}
|
||||
});
|
||||
t.ok(result.statusCode === 201 && result.body.user_sid, 'service_provider scope user created');
|
||||
const sp_user_sid = result.body.sid;
|
||||
|
||||
/* add an account */
|
||||
result = await request.post('/Accounts', {
|
||||
resolveWithFullResponse: true,
|
||||
auth: authAdmin,
|
||||
json: true,
|
||||
body: {
|
||||
name: 'sample_account',
|
||||
service_provider_sid: sp_sid,
|
||||
registration_hook: {
|
||||
url: 'http://example.com/reg',
|
||||
method: 'get'
|
||||
},
|
||||
webhook_secret: 'foobar'
|
||||
}
|
||||
});
|
||||
t.ok(result.statusCode === 201, 'successfully created account');
|
||||
const account_sid = result.body.sid;
|
||||
|
||||
/* add account user */
|
||||
result = await request.post(`/Users`, {
|
||||
resolveWithFullResponse: true,
|
||||
json: true,
|
||||
auth: authAdmin,
|
||||
body: {
|
||||
name: 'account',
|
||||
email: 'account@jambonz.com',
|
||||
is_active: true,
|
||||
force_change: true,
|
||||
initial_password: password,
|
||||
service_provider_sid: sp_sid,
|
||||
account_sid: account_sid
|
||||
}
|
||||
});
|
||||
t.ok(result.statusCode === 201 && result.body.user_sid, 'account scope user created');
|
||||
const account_user_sid = result.body.sid;
|
||||
|
||||
/* retrieve list of users */
|
||||
const authAdmin = {bearer: result.body.token};
|
||||
result = await request.get(`/Users`, {
|
||||
resolveWithFullResponse: true,
|
||||
json: true,
|
||||
auth: authAdmin,
|
||||
});
|
||||
//console.log(result.body);
|
||||
t.ok(result.statusCode === 200 && result.body.length === 1, 'successfully user list');
|
||||
t.ok(result.statusCode === 200 && result.body.length, 'successfully user list');
|
||||
|
||||
/* delete account user */
|
||||
result = await request.delete(`/Users/${account_user_sid}`, {
|
||||
resolveWithFullResponse: true,
|
||||
json: true,
|
||||
auth: authAdmin,
|
||||
});
|
||||
t.ok(result.statusCode === 204, 'account scope user deleted');
|
||||
|
||||
/* delete sp user */
|
||||
result = await request.delete(`/Users/${sp_user_sid}`, {
|
||||
resolveWithFullResponse: true,
|
||||
json: true,
|
||||
auth: authAdmin,
|
||||
});
|
||||
t.ok(result.statusCode === 204, 'account scope user deleted');
|
||||
|
||||
/* delete admin user */
|
||||
result = await request.delete(`/Users/${admin_user_sid}`, {
|
||||
resolveWithFullResponse: true,
|
||||
json: true,
|
||||
auth: authAdmin,
|
||||
});
|
||||
t.ok(result.statusCode === 204, 'account scope user deleted');
|
||||
|
||||
// /* self delete as admin user */
|
||||
// result = await request.delete(`/Users/${decodedJwt.user_sid}`, {
|
||||
// resolveWithFullResponse: true,
|
||||
// json: true,
|
||||
// auth: authAdmin,
|
||||
// });
|
||||
// t.ok(result.statusCode === 500 && result.error.msg === 'cannot delete this admin user - there are no other active admin users');
|
||||
|
||||
/* add another service_provider user */
|
||||
result = await request.post(`/Users`, {
|
||||
resolveWithFullResponse: true,
|
||||
json: true,
|
||||
auth: authAdmin,
|
||||
body: {
|
||||
name: 'service_provider1',
|
||||
email: 'sp1@jambonz.com',
|
||||
is_active: true,
|
||||
force_change: false,
|
||||
initial_password: password,
|
||||
service_provider_sid: sp_sid,
|
||||
}
|
||||
});
|
||||
t.ok(result.statusCode === 201 && result.body.user_sid, 'service_provider scope user created');
|
||||
|
||||
/* logout as sp to get a jwt */
|
||||
result = await request.post('/logout', {
|
||||
resolveWithFullResponse: true,
|
||||
auth: authAdmin,
|
||||
json: true,
|
||||
});
|
||||
t.ok(result.statusCode === 204, 'successfully logged out');
|
||||
|
||||
// /* login as sp user to get a jwt */
|
||||
// result = await request.post('/login', {
|
||||
// resolveWithFullResponse: true,
|
||||
// json: true,
|
||||
// body: {
|
||||
// username: 'service_provider1',
|
||||
// password: 'abcd1234-',
|
||||
// }
|
||||
// });
|
||||
// t.ok(result.statusCode === 200 && result.body.token, 'successfully logged in as sp');
|
||||
// const authSPUser = {bearer: result.body.token};
|
||||
|
||||
// result = await request.post(`/Users`, {
|
||||
// resolveWithFullResponse: true,
|
||||
// json: true,
|
||||
// auth: authSPUser,
|
||||
// body: {
|
||||
// name: 'sp2',
|
||||
// email: 'sp2@jambonz.com',
|
||||
// is_active: true,
|
||||
// force_change: false,
|
||||
// initial_password: password,
|
||||
// }
|
||||
// });
|
||||
// t.ok(result.statusCode === 403, 'sp user cannot create admin users');
|
||||
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
t.end(err);
|
||||
|
||||
Reference in New Issue
Block a user