Authentication Quick Reference
Token Expiry Configurationβ
Current Settingsβ
// attunelogic-api/constants/index.js
TOKEN_EXPIRE: "4h"; // Access tokens last 4 hours
REFRESH_TOKEN_EXPIRES_WEB: "8h"; // Web refresh tokens last 8 hours
REFRESH_TOKEN_EXPIRES_MOBILE: "10d"; // Mobile refresh tokens last 10 days
To Change Token Expiryβ
- Edit
attunelogic-api/constants/index.js - Update both JWT expiry (
TOKEN_EXPIRE) and cookie TTL (TOKEN_EXPIRE_TTL) - Restart API server
- All existing tokens remain valid until their current expiry
Key Filesβ
Backendβ
constants/index.js- Token configurationmodels/User.js- Token generation methodsmodels/Token.js- Token storage schemacontrollers/account/login.js- Login flowcontrollers/account/tokens.js- Refresh logicmiddlewares/verifyToken.js- Token validation
Frontendβ
redux/api.ts- Automatic refresh logichooks/useAuth.jsx- Auth context & statepages/Login/index.jsx- Login UI
Common Tasksβ
Debug Token Issuesβ
// Check if refresh token exists in database
db.tokens.findOne({
userId: ObjectId("..."),
type: "refresh",
isRevoked: false,
});
// Clean up expired tokens
db.tokens.deleteMany({ expiresAt: { $lt: new Date() } });
// Revoke all tokens for a user
db.tokens.updateMany({ userId: ObjectId("...") }, { isRevoked: true });
Add Logging to Track Refreshβ
// In controllers/account/tokens.js refresh function
console.log("Token refresh:", {
userId: decoded.id,
userEmail: decoded.email,
oldJti: decoded.jti,
newJti: jwt.decode(newRefreshToken).jti,
timestamp: new Date().toISOString(),
});
Test Authentication Flowβ
# Login
curl -X POST http://localhost:3001/api/v1/account/login \
-H "Content-Type: application/json" \
-d '{"user":{"email":"test@example.com","password":"password"}}' \
-c cookies.txt -v
# Make authenticated request
curl -X GET http://localhost:3001/api/v1/account/current \
-b cookies.txt -v
# Check cookies
cat cookies.txt
Error Code Referenceβ
| Code | Trigger | Frontend Action |
|---|---|---|
TOKEN_EXPIRED | No access token, has refresh token | Auto refresh |
TOKEN_INVALID_WITH_REFRESH | Invalid access token, has refresh token | Auto refresh |
NO_TOKEN | No access token, no refresh token | Redirect to login |
AUTHENTICATION_FAILED | Invalid access token, no refresh token | Redirect to login |
Security Checklistβ
- β Tokens are HTTP-only cookies
- β Secure flag enabled in production
- β SameSite protection against CSRF
- β Refresh tokens rotated on each use
- β Old refresh tokens immediately revoked
- β Database cleanup of expired tokens
- β Multi-tenant isolation via parentCompany
Performance Notesβ
- Access token verification is stateless (no DB lookup)
- Refresh token requires DB lookup for validation
- Token cleanup should run daily via cron job
- Consider token indices for large user bases:
db.tokens.createIndex({ userId: 1, type: 1 });
db.tokens.createIndex({ jti: 1 }, { unique: true });
db.tokens.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 });