Created
October 26, 2024 15:17
-
-
Save aquapi/7814e7a7be4c002d1ab223c5a60c74b2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This is a proof of concept implementation since | |
// Mapl doesn't have built-in signer yet | |
import { jitc, router, staticException } from '@mapl/app'; | |
import jwt from 'jsonwebtoken'; | |
import Signer from '@bit-js/ncrypt/basic-signer'; | |
import ValueSigner from '@bit-js/ncrypt/value-signer'; | |
const SECRET = 'linux'; | |
const valueSigner = new ValueSigner(new Signer(SECRET)); | |
// Account routes | |
const logIn = router() | |
.get('/login', (c) => { | |
const token = jwt.sign({ id: 1, name: 'John Doe' }, SECRET, { expiresIn: '1h' }); | |
c.headers.push(['Set-Cookie', `accessToken=${token}; HttpOnly; Secure; SameSite=Lax`]); | |
return token; | |
}) | |
.post('/logout', (c) => { | |
c.headers.push(['Set-Cookie', 'accessToken=null']); | |
return 'Logged out'; | |
}); | |
const tokenException = staticException(); | |
const main = router() | |
// Manually parse the cookie since I don't have a parser yet | |
.parse('user', (c) => { | |
const cookie = c.req.headers.get('Cookie'); | |
if (cookie === null) return tokenException; | |
const startIdx = cookie.indexOf('accessToken=') + 12; | |
if (startIdx === 11) return tokenException; | |
const endIdx = cookie.indexOf('; ', startIdx); | |
const unverifiedToken = valueSigner.unsign( | |
endIdx === -1 | |
? cookie.slice(startIdx) | |
: cookie.substring(startIdx, endIdx) | |
); | |
if (unverifiedToken === null) return tokenException; | |
try { | |
return jwt.verify(unverifiedToken, SECRET); | |
} catch { | |
return tokenException; | |
} | |
}) | |
// Handle returned exception | |
.catch(tokenException, (c) => { | |
c.status = 401; | |
return 'You are not authorized!'; | |
}) | |
// Success path | |
.get('/', (c) => `Hi ${c.user}`); | |
// Mount all sub-routers | |
const app = router() | |
.route('/', main) | |
.route('/', logIn); | |
Bun.serve({ fetch: jitc(app) }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment