tokauthjs
v1.0.0
Published
File-based registration and token authentication helper.
Maintainers
Readme
tokauthjs
Lightweight file-backed registration and token authentication utilities for Node.js projects.
Features
- Email/password registration with PBKDF2 password hashing and per-user salts.
- Token-based authentication with configurable token lifetime.
- File storage automatically created for users and tokens.
- Helper methods to verify tokens, fetch user details, and revoke tokens.
Installation
npm install tokauthjsQuick Start
const path = require('path');
const { FileAuthManager } = require('tokauthjs');
async function main() {
const auth = new FileAuthManager({
usersFilePath: path.join(__dirname, 'storage', 'users.json'),
tokensFilePath: path.join(__dirname, 'storage', 'tokens.json'),
tokenTtlSeconds: 60 * 60, // optional, defaults to 24 hours
});
// Register a user
await auth.registerUser({
email: '[email protected]',
password: 'strongpassword',
username: 'ExampleUser', // optional
});
// Authenticate the user
const { token, user } = await auth.authenticate({
email: '[email protected]',
password: 'strongpassword',
});
console.log('Access token:', token);
console.log('User details:', user);
// Fetch user details later using the token
const userFromToken = await auth.getUserByToken(token);
console.log('User from token:', userFromToken);
}
main().catch(console.error);API
new FileAuthManager(options)
| Option | Type | Required | Description |
| ------ | ---- | -------- | ----------- |
| usersFilePath | string | Yes | Path to the JSON file storing user records. |
| tokensFilePath | string | Yes | Path to the JSON file storing issued tokens. |
| tokenTtlSeconds | number | No | Token time-to-live in seconds. Default is 24 hours. Use null/0 for no expiry. |
registerUser({ email, password, username })
Registers a new user. The email must be unique. Returns the public user profile.
authenticate({ email, password })
Validates credentials, issues a new token, and returns { token, user }.
getUserByToken(token)
Returns the public user profile associated with the token. Throws if the token is invalid or expired.
getUserIdFromToken(token)
Returns the user ID associated with the token.
revokeToken(token)
Deletes the token, preventing further use.
listActiveTokens(userId)
Lists non-expired tokens for the specified user ID.
Notes
- Passwords are hashed with PBKDF2 (
sha512, 100k iterations). Store the password securely and never log it. - JSON files are created automatically if missing. Ensure the running process has read/write access.
- For production scenarios, consider swapping the file storage out for a database. The class can serve as a reference implementation.
