Stop Duplicating Auth Logic in ODAC.JS
Every Node.js codebase eventually hits the same quiet security bug. You add a user.suspended check and a last_login_at update to your email and password controller, ship it, and move on. Three months later you add magic links, social callbacks, or auto-login after registration, and half your sign-in paths silently bypass the rules you wrote in the first controller.
ODAC.JS v1.6.0 eliminates that drift with a dedicated hook/ convention directory, starting with hook/auth.js. Instead of wrapping every controller or chasing middleware chains, you declare beforeLogin, login, and loginFailed once and let ODAC.JS enforce them across every authentication path in your application.
Show Me The Code
Create hook/auth.js at the root of your ODAC.JS project and export only the lifecycle hooks you need:
// hook/auth.js
module.exports = {
// Runs after credentials pass, before any session or cookie is issued.
async beforeLogin(Odac, { user, method }) {
if (user.suspended) return false
},
// Runs after the session token is stored and cookies are set.
async login(Odac, { user, method }) {
await Odac.DB.users.where('id', user.id).update({
last_login_at: new Date(),
last_login_ip: Odac.Request.ip
})
},
// Runs when any sign-in attempt fails to produce a session.
async loginFailed(Odac, { identity, method, reason }) {
await Odac.DB.login_audit.insert({
email: identity.email,
ip: Odac.Request.ip,
method,
reason,
created_at: new Date()
})
}
}
Every handler receives the request-scoped Odac instance as its first argument, matching controllers and service classes. You have immediate access to Odac.DB, Odac.Request, and your own services in class/, and saving hook/auth.js hot-reloads in development just like middleware.
Why Controllers Are the Wrong Layer for Auth Side Effects
In traditional Node.js frameworks like Express or Fastify, login side effects live wherever a developer remembered to put them. A team starts with one POST /login route, drops an audit insert inside the handler, and feels productive. Then the application grows:
- A zero-config
<odac:login>component handles form submissions without a custom controller. - A passwordless
<odac:magic-login>form verifies one-time tokens through/_odac/magic-verify. - A signup flow calls
Odac.Auth.register()withautoLogin: true. - An onboarding or impersonation controller calls
Odac.Auth.login({ id })directly.
Route middleware cannot solve this cleanly either. Middleware executes before authentication runs, long before you know which user record matched or why an attempt was rejected. Pushing beforeLogin or audit logging into individual routes forces you to either duplicate logic across four entry points or give up built-in declarative components altogether.
ODAC.JS treats sign-in as a single lifecycle boundary rather than a collection of unrelated routes. Whether a user enters through a <odac:login> form, clicks a magic link, completes registration, or signs in programmatically via Odac.Auth.login(), every path funnels through the exact same hooks in hook/auth.js.

The Three Lifecycle Hooks in Practice
Each export in hook/auth.js maps to a distinct moment in the authentication lifecycle, with a strict payload tailored to that stage.
beforeLogin(Odac, { user, method }): Runs after credentials or tokens are verified, before any session record or cookie is created. Returnfalseto refuse the sign-in.login(Odac, { user, method }): Runs immediately after the session token is stored and auth cookies are written. Use it forlast_login_at,last_login_ip, or security alerts.loginFailed(Odac, { identity, method, reason }): Runs whenever a sign-in attempt fails to issue a session, giving you a single audit sink across all entry points.
The method string tells your hooks which path triggered the attempt:
password: Standard credential checks throughOdac.Auth.login()or<odac:login>.magic: Verified magic links through<odac:magic-login>orOdac.Auth.verifyMagicLink(), covering both existing users and new accounts created via the link.register: Automatic sign-in triggered byOdac.Auth.register().direct: Identity-only programmatic calls such asOdac.Auth.login({ id }).
For failed attempts, loginFailed also provides a structured reason code:
invalid: Wrong password, unknown account, or a malformed or already used magic link.expired: A valid magic link token whose 15-minute window has elapsed.throttled: Blocked by built-in brute-force protection before credentials were even checked.denied: Valid credentials or link rejected by yourbeforeLoginhook.
Handling Refusals Gracefully Across Flows
When beforeLogin returns false, ODAC.JS stops the sign-in cleanly without leaking internal state, and each flow reacts predictably. Odac.Auth.login() returns false just like a bad password, so <odac:login> displays "Invalid credentials" without revealing account status to an attacker. Odac.Auth.register() still creates the user record and returns { success: true, autoLogin: false }, letting you gate new accounts until an admin approves them.
Magic links route failures back to a page you control. If a user clicks a magic link for a suspended account, Odac.Auth.verifyMagicLink() returns { success: false, code: 'denied', error: 'Login failed' }, and the built-in verification handler redirects back to your configured error page where Odac.Auth.magicError() exposes { code, message }:
// controller/page/link-error.js
module.exports = async function (Odac) {
const error = Odac.Auth.magicError()
if (!error) return Odac.direct('/login')
if (error.code === 'denied') {
Odac.set('message', 'Your account is currently suspended.')
} else {
Odac.set('message', error.message)
}
Odac.View.set({ skeleton: 'main', content: 'auth.link-error' })
}
If you want a custom password-form message such as "Your account is suspended" instead of "Invalid credentials", check that condition in your own login controller before calling Odac.Auth.login(), while keeping beforeLogin in hook/auth.js as your unbypassable backstop.
// controller/Auth.js
class Auth {
async login(Odac) {
const email = await Odac.request('email')
const password = await Odac.request('password')
const existing = await Odac.DB.users.select('id', 'suspended').where('email', email).first()
if (existing && existing.suspended) {
return { error: 'Your account is suspended. Contact support.' }
}
const ok = await Odac.Auth.login({ email, password })
if (!ok) return { error: 'Invalid email or password.' }
return Odac.direct('/dashboard')
}
}
module.exports = Auth
Architectural Guarantees We Refused to Compromise
When designing hook/auth.js, we made five deliberate engineering choices so you do not have to discover edge cases in production.

1. beforeLogin Fails Closed
Returning false explicitly blocks the login, while any other return value (including undefined) lets the user proceed. If beforeLogin throws an exception, ODAC.JS logs the error and refuses the sign-in anyway. A security check that opens the door when a database query times out is a liability, not a safeguard.
2. login and loginFailed Never Break Authentication
Once a session token is written in login, or an attempt is rejected in loginFailed, errors inside your telemetry code are logged without altering the outcome. A temporary analytics outage should never lock users out of your application. Because ODAC.JS awaits hook handlers, keep database writes fast and fire slow external webhooks or emails without await.
3. Refusals Do Not Burn Brute-Force Budgets
ODAC.JS throttles wrong passwords automatically (defaulting to 5 failures per account and IP, or 50 per IP within 15 minutes). When beforeLogin denies a user who entered the correct password, that refusal records reason: 'denied' in loginFailed without counting against password throttling. Legitimate users waiting on account verification will not lock out their own office IP.
4. Zero Credential Exposure in Payloads
Inside beforeLogin and login, ODAC.JS strips every column configured in auth.passwordField from the user object before your code ever sees it. Likewise, identity in loginFailed only carries lookup fields such as email or username, never the submitted password. Use the user argument passed to the hook rather than calling Odac.Auth.user(), which is not populated during beforeLogin.
5. Cookie Resumption Stays Quiet
Authenticated requests verified through rotating auth cookies do not trigger hook/auth.js. Firing database updates on every page navigation or API call would hammer your primary database on every request. Session activity timestamps are already tracked by the framework on the token record, readable anytime via Odac.Auth.token('active').
A Closed Contract, Not an Open Event Bus
Many frameworks implement lifecycle hooks as untyped string event emitters. You call on('auth:afterLogin', fn), mistype a single character six months later, and spend an afternoon wondering why audit rows stopped appearing.
In ODAC.JS, the hook/ directory is a strict, closed contract. Only auth.js and its three documented exports (beforeLogin, login, loginFailed) are recognized. Drop an unknown file into hook/ or misspell an export name, and ODAC.JS reports it in the logs at load time so mistakes fail visibly instead of silently.
Centralizing sign-in policies in hook/auth.js gives every ODAC.JS application one verifiable place for account gates, login telemetry, and security auditing across forms, magic links, registrations, and custom controllers. Drop in hook/auth.js, keep your controllers focused on HTTP flow, and let ODAC.JS enforce your auth contract on every sign-in path.