@appstrax/admin-services
v0.3.1
Published
The Appstrax Admin NodeJS JavaScript Library
Readme
Appstrax Admin Services Node.js Library
Table of Contents
Overview
Appstrax in partnership with CodeCapsules provides software tools and infrastructure to assist in the development, hosting and managing of your applications.
Getting Started
To use the Appstrax Services, an instance of the API is required. Each API instance has an admin panel which allows admin users to manage registered users, application data and uploaded files and application configuration accordingly.
To get this instance set-up, first send an email to [email protected] and we'll help create, host and manage your Appstrax API here: https://codecapsules.io/
Add @appstrax/admin-services as a project dependency:
npm install @appstrax/admin-servicesInitialize the appstrax-admin-services libraries:
// import the services library
import { AppstraxServices } from '@appstrax/admin-services';
// initialize the service
await AppstraxServices.init({
apiUrl: '' // the base URL of your Appstrax Services API
apiKey: '' // create your api-key in the Appstrax Services admin panel
});Users who authenticate with Google SSO (or future SSO providers) still receive
Appstrax-issued JWTs. Validate those tokens with the existing JWKS middleware
(Middleware.authenticate / /.well-known/jwks.json). Do not accept Google ID
tokens directly as API credentials.
Signing key rotation
init() warms the JWKS cache and the library keeps it for 24 hours. If a token
arrives carrying a kid that is not in the cache — which is what happens when the
API rotates its signing key — the library refetches /.well-known/jwks.json and
looks again, so a rotation is picked up without restarting your service.
That refetch is rate limited to once every 30 seconds, so a flood of tokens with
unknown kids (foreign ID tokens, for example) cannot be amplified into requests
against your API. Worst case, a rotation takes up to 30 seconds to be picked up.
A kid that is still absent after the refetch is rejected, and signatures are
verified exactly as before. If the JWKS endpoint is unreachable after the cache has
expired, the last successfully fetched key set is used for a further 10 minutes,
after which authentication fails closed. While that fallback is in use the endpoint
is retried at most once every 30 seconds rather than on every request.
The JWKS request itself is bounded by a 5 second timeout and a 1 MB response limit, so a hung or oversized endpoint cannot stall the requests waiting on it.
Session revocation
Middleware.authenticate caches each authenticated session for an hour, keyed by the
token, so a token the server has not seen is always validated against
/api/auth/session before it is trusted.
Because that cache lives in your process, a logout or password reset needs to reach it.
Mount Middleware.webhook on the route you register as the Appstrax webhook, and any
auth event drops the affected user's cached sessions immediately:
import { Middleware } from '@appstrax/admin-services/auth';
app.post('/appstrax-webhook', Middleware.webhook, (req, res) => res.sendStatus(200));You can also evict a user directly — after disabling an account, for example:
Middleware.removeCachedTokensForUser(userId);Without the webhook wired up, a revoked session stays valid in this process until the cache entry expires or the token itself expires, whichever comes first.
This library integrates with the Appstrax Auth API and is used in nodejs applications.
To get started import appstraxUsers into your project:
import { appstraxUsers, User } from '@appstrax/admin-services/auth';Create User
try {
let user = new User();
user.email = email;
user.password = password;
user.data = {
name: name,
surname: surname,
... // any other user profile fields
};
user = await appstraxUsers.create(user);
console.log('Successfully Created: ', user.id);
} catch (err) {
// something went wrong while trying to create the User
handleError(err);
}Update User
try {
user.data = {
name: name,
surname: surname,
age: 29,
career: 'Software Engineer',
};
user = await appstraxUsers.update(user);
console.log('Successfully Updated: ', user.data);
} catch (err) {
// something went wrong while trying to update the User
handleError(err);
}Delete User
try {
await appstraxUsers.delete(user.id);
console.log('Successfully Deleted.');
} catch (err) {
// something went wrong while trying to delete the User
handleError(err);
}Change User Password
try {
await appstraxUsers.changePassword(user.id, newPassword);
console.log('Successfully Changed Password.');
} catch (err) {
// something went wrong changing the password
handleError(err);
}Find User by Id
try {
user = await appstraxUsers.findById(user.id);
console.log('Successfully Found: ', user);
} catch (err) {
// something went wrong while querying the collection
handleError(err);
}Querying Users With Find
The appstraxUsers.find() function takes a FetchQuery as an argument and returns a FindResultDto
Examples
A query to search for the users table similar to:
try {
const result: FindResultDto = await appstraxUsers.find({
where: { email: { [Operator.LIKE]: "Joe" } },
order: { email: "ASC" }
offset: 0,
limit: 5,
});
this.totalUsers = result.count;
this.userData = result.data;
} catch (err) {
// something went wrong while querying the database
handleError(err);
}A query to search for the users table similar to:
try {
const result: FindResultDto = await appstraxUsers.find({
where: {
[Operator.OR]: [
{ email: { [Operator.LIKE]: "Joe" } },
{ name: { [Operator.LIKE]: "Joe" } },
{ surname: { [Operator.LIKE]: "Joe" } },
],
},
offset: 0,
limit: 5,
});
this.totalUsers = result.count;
this.userData = result.data;
} catch (err) {
// something went wrong while querying the database
handleError(err);
}This library integrates with the Appstrax Database API and is used in nodejs applications.
To get started import appstraxDb into your project:
import { appstraxDb } from '@appstrax/admin-services/database';Create Document
// create a new Document in the 'profiles' collection, returns a DocumentDto
try {
const document: DocumentDto = await appstraxDb.create('profiles', {
name: 'John',
surname: 'Doe',
career: 'Software Engineer',
});
console.log('Document Created: ', document);
} catch (err) {
// something went wrong while creating the document
handleError(err);
}Edit Document
// edit documents
try {
const document: DocumentDto = await appstraxDb.edit('profiles', document.id, {
name: 'John Frederick',
surname: 'Doe',
career: 'Software Engineer',
});
console.log('Document Edited:', document);
} catch (err) {
// something went wrong while editing the document
handleError(err);
}Delete Document
// delete documents
try {
await appstraxDb.delete('profiles', document.id);
console.log('Document Deleted.');
} catch (err) {
// something went wrong while deleting the document
handleError(err);
}Find Document By Id
// findById returns a DocumentDto from the 'profiles' collection
try {
const document: DocumentDto = await appstraxDb.findById('profiles', documentId);
console.log('Document Found: ', document);
} catch (err) {
// something went wrong while querying the 'profiles' collection
handleError(err);
}Find Documents
// find() returns a FindResultDto<DocumentDto>
try {
const result: FindResultDto = await appstraxDb.find('profiles');
console.log('Documents Found: ', results.data);
} catch (err) {
// something went wrong while querying the 'profiles' collection
handleError(err);
}
// find() accepts an optional FetchQuery as its second parameter
// in example below we find all documents where `career` includes 'Software'
try {
const result: FindResultDto = await appstraxDb.find('profiles', {
where: { career: { [Operator.LIKE]: 'Software' } },
});
console.log('Documents Found: ', result.data);
} catch (err) {
// something went wrong while querying the 'profiles' collection
handleError(err);
}CRUD Service
The CrudService is a abstract class which wraps the Create, Read, Update and Delete functions in appstraxDb. The CrudService is declared with a model which extends the Model class, this model is the type that the service Creates, Reads, Updates and Deletes.
Similarly to appstraxDb, the CrudService uses a collection name which represents the "table" that the data is stored in on the server.
To get started import CrudService & Model into your project:
import { CrudService, Model } from '@appstrax/admin-services/database';Create your custom Model & Service:
// Profile is an example of the 'type' that the CrudService is declared with
// NB. each field requires a default value. (fieldName = defaultValue)
export class Profile extends Model {
name: string = '';
surname: string = '';
career: string = '';
}
// ProfileService is an example of how to implement the CrudService
// 'profiles' is the collection name
export class ProfileService extends CrudService<Profile> {
constructor() {
super('profiles', Profile);
}
}We can now use the ProfileService as follows:
const profileService = new ProfileService();
var createdProfileId: string = '';
// example of create
try {
const profile = new Profile();
profile.name = 'Jane';
profile.surname = 'Doe';
profile.career = 'Software Engineer';
// the `save` function is used to create and update
let createdProfile = await profileService.save(profile);
createdProfileId = createdProfile.id;
console.log('Profile Created: ', createdProfileId);
} catch (err) {
// something went wrong while creating the profile
handleError(err);
}
// example of findById, returns an instantiated `Profile` or null.
try {
const profile = await profileService.findById(createdProfileId);
console.log('Profile Fetched: ', profile);
} catch (err) {
// something went wrong when fetching
handleError(err);
}
// example of find, returns a FindResultDto
try {
const findResult = await profileService.find(); // find all profiles
const profiles = findResult.data;
console.log('Profiles Fetched: ', profiles);
} catch (err) {
// something went wrong when fetching
handleError(err);
}
// example of find with a FetchQuery
try {
const findResult = await profileService.find({
where: { career: { [Operator.LIKE]: 'Software' } },
});
const profiles = findResult.data;
console.log('Profiles Fetched: ', profiles);
} catch (err) {
// something went wrong when fetching
handleError(err);
}
// example of delete
try {
await profileService.delete(createdProfileId);
console.log('Profile Deleted: ', createdProfileId);
} catch (err) {
// something went wrong while deleting the profile
handleError(err);
}This library integrates with the Appstrax Storage API and is used in nodejs applications.
To get started import appstraxStorage into your project:
import { appstraxStorage } from '@appstrax/admin-services/storage';Upload File
// Upload File
try {
const result = await appstraxStorage.uploadFile(
file,
'<folder>/',
(e) => {
var percentCompleted = Math.round((e.loaded * 100) / e.total);
console.log('Percentage Completed: ', percentCompleted);
}
);
console.log('File Uploaded: ', result.downloadUrl);
} catch (err) {
// something went wrong while uploading the file
handleError(err);
}Delete File
// Delete File using downloadUrl
try {
await appstraxStorage.deleteFile(result.downloadUrl);
console.log('File Deleted');
} catch (err) {
// something went wrong while deleting the file
handleError(err);
}Fetch Directory
// Fetch Directory by path
try {
const directoryDto = await appstraxStorage.fetchDirectory('');
console.log('Directory: ', directoryDto);
} catch (err) {
// something went wrong while fetching the directory
handleError(err);
}The appstraxStorage.fetchDirectory function returns a DirDto as defined below
interface DirDto {
totalFiles: number;
dirItems: DirItemDto[];
}
interface DirItemDto {
name: string; // the name of the file or folder
type: 'folder' | 'file';
}Create Directory
// Create Directory by path
try {
await appstraxStorage.createDirectory('/DirectoryA/DirectoryB');
} catch (err) {
// something went wrong while creating the directory
handleError(err);
}Delete Directory
// Delete Directory by path
try {
await appstraxStorage.deleteDirectory('/DirectoryA/DirectoryB');
} catch (err) {
// something went wrong while deleting the directory
handleError(err);
}The find() function accepts FetchQuery as an argument
Fetch Query
export interface FetchQuery {
where?: Where;
order?: Order;
offset?: number;
limit?: number;
}
export interface Where {
// eslint-disable-next-line @typescript-eslint/ban-types
[key: string | Operator]: object | Operator | [] | number | string | boolean;
}
export interface Order {
[key: string]: OrderDirection;
}
export enum OrderDirection {
/** Ascending Order Direction */
ASC = 'ASC',
/** Descending Order Direction */
DESC = 'DESC',
}Query Operators
export enum Operator {
/** Equal To Operator */
EQUAL = 'EQUAL',
/** Not Equal To Operator */
NOT_EQUAL = 'NOT_EQUAL',
/** And Operator */
AND = 'AND',
/** Or Operator */
OR = 'OR',
/** Greater Than Operator */
GT = 'GT',
/** Greater Than or Equal To Operator */
GTE = 'GTE',
/** Less Than Operator */
LT = 'LT',
/** Less Than or Equal To Operator */
LTE = 'LTE',
/** Like Operator */
LIKE = 'LIKE',
/** Not Like Operator */
NOT_LIKE = 'NOT_LIKE',
/** In Operator */
IN = 'IN',
}The find() function returns FindResultDto:
// querying the data returns a FindResultDto<DocumentDto> from the collection
export interface FindResultDto<T extends DocumentDto | Model> {
data: T[];
where: Where;
order: Order;
limit: number;
offset: number;
count: number;
}
export class DocumentDto {
id: string;
data: any = {};
createdAt: Date = null;
updatedAt: Date = null;
}Domains that must use SSO
An Appstrax install can require an email domain to sign in through a specific
SSO account. For addresses on such a domain, the user routes here answer 403
with the message ssoRequired:
appstraxUsers.createandappstraxUsers.update, when the user carries a passwordappstraxUsers.changePasswordappstraxUsers.sendEmailwith theforgot_passwordtemplate
The rejection names the account the user must use:
{
"message": "ssoRequired",
"provider": "microsoft",
"accountKey": "companyx",
"displayName": "Company X"
}There is no API change in this package and nothing to upgrade — but a backend that provisions users will start seeing a rejection it has not seen before. Creating a user on a restricted domain without a password still works, so pre-provisioning roles before someone's first SSO sign-in is unaffected.
