Authentication Examples
Explore code samples and implementation patterns for authentication integration in Nelgyfika projects.
OAuth2 Integration
Client Setup
import { OAuthClient } from 'nelgyfika/auth'
const client = new OAuthClient({
provider: 'github',
clientId: process.env.AUTH_GITHUB_ID,
clientSecret: process.env.AUTH_GITHUB_SECRET
})
Authentication Flow
// Initiate login redirect
export async function startLogin() {
const authUrl = client.getAuthorizationUrl({
scope: 'user:email',
redirectTo: '/auth/callback'
})
window.location.href = authUrl
}
// Handle redirect
export async function handleCallback(code: string) {
const tokens = await client.getTokenFromCode(code)
const user = await client.getUser(tokens)
return { user, tokens }
}
JWT Token Management
import jwt from 'jsonwebtoken'
// Generate token
function signToken(payload) {
return jwt.sign(
payload,
process.env.JWT_SECRET,
{ expiresIn: '24h' }
)
}
// Verify token
function verifyToken(token) {
try {
return jwt.verify(token, process.env.JWT_SECRET)
} catch (err) {
throw new Error('Invalid token')
}
}
Social Login Integration
provider: 'facebook'
provider: 'google'
provider: 'twitter'
const socialClient = new OAuthClient({
provider: 'google',
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
scope: ['email', 'profile']
})
Password Management
import bcrypt from 'bcryptjs'
// Hash password
async function hashPassword(password) {
return await bcrypt.hash(password, 10)
}
// Compare password
async function verifyPassword(password, hash) {
return await bcrypt.compare(password, hash)
}
Interactive Auth Playground
{
"status": "success",
"user": {
"id": "user_2DjGJ4x5Y6kZV5fR6X1v1Q7vz5",
"email": "demo@example.com",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCII6IkpXVCJ9..."
}
}
Security Best Practices
Token Storage
Use HttpOnly, Secure, SameSite=Strict cookies for session storage
Set-Cookie: auth_token=...; HttpOnly; Secure; SameSite=Strict
Throttling
Implement rate limiting for login attempts
maxAttempts:5 windowMs:15*60*1000