@developerwafi/auth
v1.1.0
Published
Modern authentication toolkit for Node.js, Express.js, Next.js and more
Maintainers
Readme
@developerwafi/auth
Modern authentication toolkit for Node.js, Express.js, Next.js and JavaScript applications.
A lightweight and developer-friendly authentication package with JWT, password hashing, authentication middleware, OTP system, password utilities and more.
Installation
npm install @developerwafi/authImport
ESM
// Import functions and utilities
import {
// Auth class
Auth,
// JWT
generateToken,
verifyToken,
decodeToken,
generateRefreshToken,
tokenExpired,
// Password
hashPassword,
comparePassword,
generateSalt,
validatePassword,
generatePassword,
checkPasswordStrength,
// Middleware
authenticated,
role
} from '@developerwafi/auth'CommonJS
// CommonJS support
const {
Auth,
generateToken,
verifyToken,
decodeToken,
generateRefreshToken,
tokenExpired,
hashPassword,
comparePassword,
generateSalt,
validatePassword,
generatePassword,
checkPasswordStrength,
authenticated,
role
} = require('@developerwafi/auth')Features
- JWT Token Generation
- JWT Token Verification
- JWT Decode
- Refresh Token Generation
- Token Expiry Checker
- Password Hashing
- Password Compare
- Salt Generator
- Password Validation
- Password Generator
- Password Strength Checker
- Authentication Middleware
- Role Middleware
- OTP Generator
- OTP Verification
- TypeScript Support
- ESM Support
- CommonJS Support
JWT
generateToken()
Generate JWT access token.
Parameters
| Parameter | Type | Description | | --------- | ------ | --------------------- | | payload | object | User data | | secret | string | JWT secret key | | expiresIn | string | Token expiration time |
Example
import {
generateToken
} from '@developerwafi/auth'
// payload -> user data
// secret -> jwt secret key
// expiresIn -> token expire time
const token = generateToken(
{
id: 1,
email: '[email protected]'
},
process.env.JWT_SECRET,
'7d'
)
console.log(token)verifyToken()
Verify JWT token and return decoded data.
Parameters
| Parameter | Type | Description | | --------- | ------ | -------------- | | token | string | JWT token | | secret | string | JWT secret key |
Example
import {
verifyToken
} from '@developerwafi/auth'
// token -> jwt token
// secret -> jwt secret key
const decoded = verifyToken(
token,
process.env.JWT_SECRET
)
console.log(decoded)decodeToken()
Decode JWT token without verification.
Parameters
| Parameter | Type | Description | | --------- | ------ | ----------- | | token | string | JWT token |
Example
import {
decodeToken
} from '@developerwafi/auth'
// token -> jwt token
const decoded =
decodeToken(token)
console.log(decoded)generateRefreshToken()
Generate refresh token.
Parameters
| Parameter | Type | Description | | --------- | ------ | ----------------- | | payload | object | User data | | secret | string | JWT secret key | | expiresIn | string | Token expire time |
Example
import {
generateRefreshToken
} from '@developerwafi/auth'
// payload -> user data
// secret -> jwt secret
// expiresIn -> token expire time
const refreshToken =
generateRefreshToken(
{
id: 1
},
process.env.JWT_SECRET,
'30d'
)
console.log(refreshToken)tokenExpired()
Check token expiration status.
Returns:
- true
- false
Parameters
| Parameter | Type | Description | | --------- | ------ | ----------- | | token | string | JWT token |
Example
import {
tokenExpired
} from '@developerwafi/auth'
// token -> jwt token
const expired =
tokenExpired(token)
console.log(expired)Password
hashPassword()
Hash password using bcrypt.
Parameters
| Parameter | Type | Description | | --------- | --------------- | -------------- | | password | string | Plain password | | salt | string | number | Salt or rounds |
Example
import {
hashPassword
} from '@developerwafi/auth'
// password -> plain password
// salt -> bcrypt salt or rounds
const hashedPassword =
await hashPassword(
'123456'
)
console.log(hashedPassword)comparePassword()
Compare plain password with hashed password.
Returns:
- true
- false
Parameters
| Parameter | Type | Description | | -------------- | ------ | --------------- | | password | string | Plain password | | hashedPassword | string | Hashed password |
Example
import {
comparePassword
} from '@developerwafi/auth'
// password -> plain password
// hashedPassword -> bcrypt hashed password
const isMatch =
await comparePassword(
'123456',
hashedPassword
)
console.log(isMatch)generateSalt()
Generate bcrypt salt.
Parameters
| Parameter | Type | Description | | --------- | ------ | ----------- | | rounds | number | Salt rounds |
Example
import {
generateSalt
} from '@developerwafi/auth'
// rounds -> bcrypt rounds
const salt =
await generateSalt(10)
console.log(salt)validatePassword()
Validate password strength.
Parameters
| Parameter | Type | Description | | --------- | ------ | ------------------ | | password | string | User password | | options | object | Validation options |
Validation Options
{
minLength: 8,
uppercase: true,
lowercase: true,
number: true,
specialChar: true
}Example
import {
validatePassword
} from '@developerwafi/auth'
// password -> user password
// options -> validation settings
const result =
validatePassword(
'Wafi@123'
)
console.log(result)Output
{
success: true,
message: 'Strong password'
}generatePassword()
Generate secure random password.
Parameters
| Parameter | Type | Description | | --------- | ------ | --------------------------- | | options | object | Password generation options |
Options
{
length: 12,
uppercase: true,
lowercase: true,
numbers: true,
symbols: true
}Example
import {
generatePassword
} from '@developerwafi/auth'
// options -> password settings
const password =
generatePassword({
length: 16,
symbols: true
})
console.log(password)checkPasswordStrength()
Check password strength level.
Parameters
| Parameter | Type | Description | | --------- | ------ | ------------- | | password | string | User password |
Example
import {
checkPasswordStrength
} from '@developerwafi/auth'
// password -> user password
const result =
checkPasswordStrength(
'Wafi@123'
)
console.log(result)Output
{
score: 5,
strength: 'Very Strong'
}Middleware
authenticated()
Authentication middleware for protecting routes.
Supports:
- Bearer token
- Raw token
- Custom headers
Parameters
| Parameter | Type | Description | | ---------- | ------ | ------------------- | | headerName | string | Request header name | | secret | string | JWT secret key |
Express.js Example
import express from 'express'
import {
authenticated
} from '@developerwafi/auth'
const app = express()
app.get(
'/profile',
// headerName -> authorization
// secret -> jwt secret
authenticated(
'authorization',
process.env.JWT_SECRET
),
(req, res) => {
res.json({
success: true,
user: req.user
})
}
)Bearer Token Example
Authorization: Bearer TOKENrole()
Role-based authorization middleware.
Parameters
| Parameter | Type | Description | | --------- | -------- | ------------- | | roles | string[] | Allowed roles |
Example
import {
authenticated,
role
} from '@developerwafi/auth'
app.get(
'/admin',
authenticated(),
// roles -> allowed roles
role([
'admin'
]),
(req, res) => {
res.json({
success: true
})
}
)OTP
Auth.generateOTP()
Generate numeric OTP.
Parameters
| Parameter | Type | Description | | --------- | ------ | ----------- | | length | number | OTP length |
Example
import {
Auth
} from '@developerwafi/auth'
// length -> otp length
const otp =
Auth.generateOTP(6)
console.log(otp)Auth.verifyOTP()
Verify OTP.
Returns:
- true
- false
Parameters
| Parameter | Type | Description | | --------- | ------ | ------------ | | otp | string | Original OTP | | userOTP | string | User OTP |
Example
import {
Auth
} from '@developerwafi/auth'
// otp -> original otp
// userOTP -> user entered otp
const verified =
Auth.verifyOTP(
'123456',
'123456'
)
console.log(verified)Auth Class
Auth.login()
Login helper utility.
Example
import {
Auth
} from '@developerwafi/auth'
const result =
await Auth.login({
body: {
email:
req.body.email,
password:
req.body.password
},
user: {
id: 1,
email:
'[email protected]',
password:
hashedPassword
},
authSecret:
process.env.JWT_SECRET
})
console.log(result)Auth.register()
Register helper utility.
Example
import {
Auth
} from '@developerwafi/auth'
const user =
await Auth.register({
body: {
name: 'Wafi',
email:
'[email protected]',
password:
'123456'
}
})
console.log(user)Auth.refreshToken()
Generate refresh token using Auth class.
Example
import {
Auth
} from '@developerwafi/auth'
const token =
Auth.refreshToken({
user: {
id: 1,
email:
'[email protected]'
},
authSecret:
process.env.JWT_SECRET
})
console.log(token)Raw Node.js Example
import http from 'http'
import {
authenticated
} from '@developerwafi/auth'
const server = http.createServer(
(req, res) => {
const middleware =
authenticated(
'authorization',
process.env.JWT_SECRET
)
middleware(
req,
res,
() => {
res.end(
JSON.stringify(req.user)
)
}
)
}
)
server.listen(3000)Next.js Example
import {
authenticated
} from '@developerwafi/auth'
export async function GET(req) {
const middleware =
authenticated(
'authorization',
process.env.JWT_SECRET
)
middleware(
req,
{
status: (code) => ({
json: (data) =>
Response.json(data, {
status: code
})
}),
end: () => {}
},
() => {}
)
return Response.json({
success: true
})
}TypeScript Support
Fully written in TypeScript.
Built-in typings included.
No additional typings required.
Framework Support
- Node.js
- Express.js
- Next.js
- Fastify
- Hono
- Bun
Package Structure
src/
│
├── auth/
├── jwt/
├── password/
├── middleware/
└── index.tsAuthor
Wafi Hasan
YouTube: Developer Wafi
GitHub: developerwafi
License
MIT License
