Skip to content

Commit

Permalink
Add authenticated user to store
Browse files Browse the repository at this point in the history
  • Loading branch information
eelkevdbos committed Oct 10, 2023
1 parent 792d65e commit 7887e1a
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 1 deletion.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@eelkevdbos/elysia-basic-auth",
"version": "1.3.0",
"version": "1.4.0",
"description": "Basic auth for Elysia.js",
"repository": "https://github.com/eelkevdbos/elysia-basic-auth",
"author": {
Expand Down
12 changes: 12 additions & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ describe('basicAuth', () => {
})
)
.get('/private', () => 'private')
.get('/realm', ({ store }) => store.basicAuthRealm)
.get('/user', ({ store }) => store.basicAuthUser)
.options('/private', () => 'public for preflight requests')

it('sets WWW-Authenticate header on unauthorized requests', async () => {
Expand Down Expand Up @@ -52,6 +54,16 @@ describe('basicAuth', () => {
const bearerRequest = req('/private', bearerInit)
expect((await app.handle(bearerRequest)).status).toEqual(401)
})

it('stores authenticated realm', async () => {
const realmResponse = await app.handle(req('/realm', userInit))
expect(await realmResponse.text()).toEqual('Secure Area')
})

it('stores authenticated realm', async () => {
const userResponse = await app.handle(req('/user', userInit))
expect(await userResponse.text()).toEqual('admin')
})
})

describe('basicAuth skipCorsPreflight', () => {
Expand Down
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,7 @@ export function basicAuth(userOptions: Partial<BasicAuthOptions> = {}) {
return (app: Elysia) =>
app
.state('basicAuthRealm', null as string | null)
.state('basicAuthUser', null as string | null)
.addError({ BASIC_AUTH_ERROR: BasicAuthError })
.onError(({ code, error }) => {
if (code === 'BASIC_AUTH_ERROR' && error.realm === options.realm) {
Expand All @@ -208,6 +209,7 @@ export function basicAuth(userOptions: Partial<BasicAuthOptions> = {}) {
}

ctx.store.basicAuthRealm = options.realm
ctx.store.basicAuthUser = credentials.username
}
})
}

0 comments on commit 7887e1a

Please sign in to comment.