@appstrax/auth-admin
v0.0.13
Published
The @appstrax/auth-admin nodejs javascript library
Downloads
24
Readme
@appstrax/auth-admin
This is the nodejs admin library for @appstrax/auth.
Getting Started
Create your Appstrax Auth API here: https://codecapsules.io/.
Installation
npm install @appstrax/auth-admin --save
Setup
Initialize the auth
library:
// import the auth library
import { auth } from '@appstrax/auth-admin';
// initialize the auth service
auth.initialize({
baseUrl: 'YOUR API URL HERE', // eg. appstrax-auth-api-snidtu.codecapsules.co.za,
jwtSecret: 'YOUR JWT SECRET HERE', // same JWT secret as configured on the AUTH API
email: 'YOUR ADMIN EMAIL HERE', // same admin email as used on the AUTH API
password: 'YOUR ADMIN PASSWORD HERE', // same admin password as used on the AUTH API
}).then(() => {
// success, your credentials are valid
}).catch((err) => {
console.log(err);
});
User CRUD - Example
Users can be accessed using this simple user service example:
import { auth, User } from '@appstrax/auth-admin';
export class UserService {
constructor() {
auth.initialize({
jwtSecret: config.authJwtSecret,
baseUrl: config.authBaseUrl,
email: config.authAdminEmail,
password: config.authAdminPassword
}).then(() => {
console.log('appstrax auth admin - connected');
}).catch((err) => {
console.log(err);
});
}
public fetchAll(): Promise<User[]> {
// filtering coming soon
return auth.users.fetchAll();
}
public fetchById(id: string): Promise<User> {
// add any validation here
return auth.users.fetchById(id);
}
public update(user: User): Promise<User> {
// add any validation here
return auth.users.update(user);
}
public create(user: User): Promise<User> {
// add any validation here
return auth.users.create(user);
}
public delete(id: string): Promise<void> {
// add any validation here
return auth.users.delete(id);
}
}
Express - Authentication Middleware
import express, { Request, Response } from 'express';
import { auth } from '@appstrax/auth-admin';
const authenticated = auth.middleware.isAuthenticated;
const router = express.Router();
router.get('/', authenticated, (req: Request, res: Response) => {
/*
if a request to this endpoint is not authenticated, this function will not be reached.
the request will be sent a 401 response with 'Unauthorized' as the body.
if the request is authenticated this function will be reached with the following:
*/
res.locals.token; // the JWT used to authenticate
res.locals.user; // the user who made the request
...
});