hono-auth
v0.1.0
Published
Authentication middleware for Hono. Inspired by NextAuth.js.
Readme
hono-auth
Authentication middleware for Hono. Inspired by NextAuth.js.
[!WARNING]
This project is currently in beta. Production use is not recommended.
Install
bun add hono hono-auth
# or
npm install hono hono-authUsage
import { Hono } from 'hono'
import { createAuthMiddleware } from 'hono-auth'
import type {
DefaultToken, DefaultSession, DefaultUser, AuthContext, AuthOptions
} from 'hono-auth'
const app = new Hono()
interface MyToken extends DefaultToken {
name: string
something: string
}
interface MySession extends DefaultSession {
userName: string
something: string
}
interface MyUser extends DefaultUser {
something: string
}
type MyContext = AuthContext<MyToken, MySession, MyUser>
const tokenMaxAge = 60 * 60 * 24 // 1 day
const authOpts: AuthOptions<MyContext> = {
tokenSecret: 'some-super-secret-key-that-is-long-and-secure',
tokenMaxAge,
async tokenCallback(c, ref) {
if (ref == 'login') {
if (!c.var.user) return null
const token: typeof c['var']['token'] = {
sub: c.var.user.id,
exp: Date.now()/1000 + tokenMaxAge,
iat: Date.now()/1000,
jti: 'some-session-id',
name: c.var.user.name,
something: c.var.user.something
}
return token
}
if (ref === 'logout') return null
return c.var.token
},
async sessionCallback(c) {
if (!c.var.token) return null
const session: typeof c['var']['session'] = {
sessionId: c.var.token.jti,
userId: c.var.token.sub,
userName: c.var.token.name,
something: c.var.token.something
}
return session
},
providers: {
async login(c) {
try {
// Login logic here...
return { user }
} catch {
return null
}
},
async logout(c) {
// Logout logic here...
return { res: c.redirect('/', 302) }
}
}
}
const { authMiddleware, authRequired } = createAuthMiddleware(authOpts)
app.use('*', authMiddleware)
app.get('/me', (c: MyContext) => {
if (!c.var.session) return authRequired(c)
return c.json({
message: `Hello @${c.var.session.userName}!`
}, 200)
})Refer to source code for implementation and usage details.
TODO
- Proper documentations.
- Built-in authentication providers.
License
This project is licensed under the MIT License. Refer to LICENSE for details.
