nanoweb-auth
v0.4.3
Published
Nanoweb authorization package for utilizing users functions in different storage providers such as files, SQL and NOSQL databases.
Downloads
238
Readme
Sure! Here's a comprehensive documentation for the nanoweb-auth
project:
nanoweb-auth
nanoweb-auth
is a modular authentication library designed to provide a flexible and extensible authentication system. It supports multiple storage backends, such as file system, MariaDB, and Redis, and allows for easy integration into existing applications.
Features
- Modular design with support for different storage providers
- User management with login, password, and access control
- Token-based authentication with support for refreshing tokens
- Flexible access control system
- Extensible through custom storage providers
Installation
npm install nanoweb-auth
Usage
Setting up the Provider
First, set up the provider you want to use. nanoweb-auth
comes with three built-in providers: FileSystemProvider
, MariadbProvider
, and RedisProvider
.
FileSystemProvider
const { FileSystemProvider } = require('nanoweb-auth/providers');
const provider = new FileSystemProvider('/path/to/storage/directory');
MariadbProvider
const mariadb = require('mariadb');
const { MariadbProvider } = require('nanoweb-auth/providers');
const connection = await mariadb.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'auth_db'
});
const provider = new MariadbProvider(connection);
RedisProvider
const redis = require('redis');
const { RedisProvider } = require('nanoweb-auth/providers');
const client = redis.createClient();
await client.connect();
const provider = new RedisProvider(client);
Initializing the Manager
Create a new instance of the Manager
class with the chosen provider.
const { Manager } = require('nanoweb-auth');
const manager = new Manager(provider);
User Management
Adding a User
const userData = {
login: 'john_doe',
name: 'John Doe',
email: '[email protected]',
password: 'securepassword',
accessMap: { '*': 'r' } // Read-only access to all endpoints
};
const user = await manager.addUser(userData);
console.log('User added:', user);
Updating a User
const updatedUserData = {
name: 'Johnathan Doe',
email: '[email protected]',
password: 'newsecurepassword',
accessMap: { '*': 'rw' } // Read-write access to all endpoints
};
const updatedUser = await manager.updateUser('john_doe', updatedUserData);
console.log('User updated:', updatedUser);
Deleting a User
const success = await manager.deleteUser('john_doe');
console.log('User deleted:', success);
Token Management
Creating a Token
const user = await manager.loadUser('john_doe');
const token = manager.createToken(user);
console.log('Token created:', token);
Refreshing a Token
const refreshedToken = manager.refreshToken('existing_token_id');
console.log('Token refreshed:', refreshedToken);
Access Control
Checking User Access
const user = await manager.loadUser('john_doe');
const hasAccess = user.hasAccess('/some/protected/resource', 'r'); // Check for read access
console.log('User has access:', hasAccess);
API Reference
Manager
- constructor(provider: Provider): Creates a new
Manager
instance with the specified provider. - createToken(user: User): Token: Creates a new token for the specified user.
- getToken(tokenId: string): string | undefined: Retrieves the user ID associated with the specified token.
- getTokens(): Record<string, string>: Retrieves all tokens.
- refreshToken(tokenId: string): Token: Refreshes the specified token.
- loadUser(userId: string): Promise: Loads a user by their ID.
- loadAllUsers(model: new (...args: any[]) => User): Promise<User[]>: Loads all users.
- save(model: Storable): Promise: Saves the specified model.
- findAll(model: new (...args: any[]) => Storable): Promise<Storable[]>: Finds all instances of the specified model.
- addUser(userData: { login: string, name: string, email: string, password: string, accessMap: Record<string, string> }): Promise: Adds a new user.
- updateUser(userId: string, userData: { name: string, email: string, password?: string, accessMap: Record<string, string> }): Promise: Updates an existing user.
- deleteUser(login: string): Promise: Deletes a user by their login.
- oneMoreLogin(login: string, ipOrCompleted: string | boolean): boolean: Tracks login attempts for rate limiting or security purposes.
User
- getId(): string: Retrieves the user ID.
- setAccess(url: string, access: string): void: Sets access permissions for the specified URL.
- setAccessMap(target: Record<string, string>): void: Sets the entire access map.
- hasAccess(url: string, requiredAccess?: string): boolean: Checks if the user has the specified access permissions.
- getAccessMap(): Record<string, string>: Retrieves the user's access map.
- validateLogin(login: string): string: Validates and formats the user's login.
- setPassword(password: string): void: Sets the user's password.
- checkPassword(password: string): boolean: Checks if the provided password matches the user's password.
- getPassword(): string | null: Retrieves the user's password.
- getTokens(): Record<string, Token>: Retrieves the user's tokens.
- addToken(token: Token): void: Adds a token to the user.
- deleteToken(token: Token | string): void: Deletes a token from the user.
Token
- getTokenLifeTime(): number: Retrieves the token's lifetime in milliseconds.
Providers
Provider
- save(instance: Storable): Promise: Saves the specified instance.
- load(instance: Storable): Promise<Storable | null>: Loads the specified instance.
- findAll(model: new (...args: any[]) => Storable): Promise<Storable[]>: Finds all instances of the specified model.
- install(): Promise: Installs the provider.
- uninstall(): Promise: Uninstalls the provider.
- setup(): Promise: Sets up the provider.
FileSystemProvider
- constructor(directory: string, context: any): Creates a new
FileSystemProvider
instance with the specified directory and context. - getUserDir(login: string): string: Retrieves the directory for the specified user login.
- getUserFile(login: string, relativeFilename: string): string: Retrieves the file path for the specified user file.
- saveUser(instance: User): void: Saves the specified user.
- loadUser(login: string): User | null: Loads the specified user.
- removeUser(login: string): Promise: Removes the specified user.
- findAllUsers(): Promise<User[]>: Finds all users.
- loadSessions(): Promise<Record<string, string>>: Loads all sessions.
MariadbProvider
- constructor(connection: any): Creates a new
MariadbProvider
instance with the specified connection. - saveToken(token: any, user: User): Promise: Saves the specified token for the user.
- removeUser(login: string): Promise: Removes the specified user.
- findAllUsers(): Promise<User[]>: Finds all users.
- loadSessions(): Promise<Record<string, string>>: Loads all sessions.
RedisProvider
- constructor(client: any): Creates a new
RedisProvider
instance with the specified client. - removeUser(login: string): Promise: Removes the specified user.
- findAllUsers(): Promise<User[]>: Finds all users.
- loadSessions(): Promise<Record<string, string>>: Loads all sessions.
Testing
The nanoweb-auth
library includes comprehensive tests for each provider. To run the tests, use the following command:
npm test
Contributing
Contributions are welcome! Please open an issue or submit a pull request on GitHub.
License
This project is licensed under the MIT License. See the LICENSE file for details.
This documentation provides a comprehensive overview of the nanoweb-auth
project, including installation instructions, usage examples, API reference, and testing guidelines.