forked from lobehub/lobe-chat
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
💄 style: support webhooks for casdoor (lobehub#3942)
* ✨ feat: Support Casdoor provider * ✨ feat: + webhook for casdoor * 🐛 fix: skip test
- Loading branch information
Showing
6 changed files
with
206 additions
and
1 deletion.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
import { describe, expect, it } from 'vitest'; | ||
|
||
interface User { | ||
name: string; | ||
id: string; | ||
type: 'normal-user' | 'admin' | 'super-admin'; | ||
displayName: string; | ||
firstName: string; | ||
lastName: string; | ||
avatar: string; | ||
email: string; | ||
emailVerified: boolean; | ||
} | ||
|
||
interface UserDataUpdatedEvent { | ||
user: string; // 用户名 | ||
action: 'update-user'; | ||
extendedUser: User; // 扩展用户信息 | ||
} | ||
|
||
const userDataUpdatedEvent: UserDataUpdatedEvent = { | ||
user: 'admin', | ||
action: 'update-user', | ||
extendedUser: { | ||
name: 'admin', | ||
id: '35edace3-00c6-41e1-895e-97c519b1d8cc', | ||
type: 'normal-user', | ||
displayName: 'Admin', | ||
firstName: '', | ||
lastName: '', | ||
avatar: 'https://cdn.casbin.org/img/casbin.svg', | ||
email: 'admin@example.cn', | ||
emailVerified: false, | ||
}, | ||
}; | ||
|
||
const AUTH_CASDOOR_WEBHOOK_SECRET = 'casdoor-secret'; | ||
|
||
// Test Casdoor Webhooks in Local dev, here is some tips: | ||
// - Replace the var `AUTH_CASDOOR_WETHOOK_SECRET` with the actual value in your `.env` file | ||
// - Start web request: If you want to run the test, replace `describe.skip` with `describe` below | ||
// - Run this test with command: | ||
// pnpm vitest --run --testNamePattern='^ ?Test Casdoor Webhooks in Local dev' src/app/api/webhooks/casdoor/__tests__/route.test.ts | ||
|
||
describe.skip('Test Casdoor Webhooks in Local dev', () => { | ||
// describe('Test Casdoor Webhooks in Local dev', () => { | ||
it('should send a POST request with casdoor headers', async () => { | ||
const url = 'http://localhost:3010/api/webhooks/casdoor'; // 替换为目标URL | ||
const data = userDataUpdatedEvent; | ||
const response = await fetch(url, { | ||
method: 'POST', | ||
headers: { | ||
'Content-Type': 'application/json', | ||
'casdoor-secret': AUTH_CASDOOR_WEBHOOK_SECRET, | ||
}, | ||
body: JSON.stringify(data), | ||
}); | ||
expect(response.status).toBe(200); // 检查响应状态 | ||
}); | ||
}); |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
import { NextResponse } from 'next/server'; | ||
|
||
import { authEnv } from '@/config/auth'; | ||
import { pino } from '@/libs/logger'; | ||
import { NextAuthUserService } from '@/server/services/nextAuthUser'; | ||
|
||
import { validateRequest } from './validateRequest'; | ||
|
||
export const POST = async (req: Request): Promise<NextResponse> => { | ||
const payload = await validateRequest(req, authEnv.CASDOOR_WEBHOOK_SECRET); | ||
|
||
if (!payload) { | ||
return NextResponse.json( | ||
{ error: 'webhook verification failed or payload was malformed' }, | ||
{ status: 400 }, | ||
); | ||
} | ||
|
||
const { action, extendedUser } = payload; | ||
|
||
pino.trace(`casdoor webhook payload: ${{ action, extendedUser }}`); | ||
|
||
const nextAuthUserService = new NextAuthUserService(); | ||
switch (action) { | ||
case 'update-user': { | ||
return nextAuthUserService.safeUpdateUser(extendedUser.id, { | ||
avatar: extendedUser?.avatar, | ||
email: extendedUser?.email, | ||
fullName: extendedUser.displayName, | ||
}); | ||
} | ||
|
||
default: { | ||
pino.warn( | ||
`${req.url} received event type "${action}", but no handler is defined for this type`, | ||
); | ||
return NextResponse.json({ error: `unrecognised payload type: ${action}` }, { status: 400 }); | ||
} | ||
} | ||
}; |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
import { headers } from 'next/headers'; | ||
|
||
import { authEnv } from '@/config/auth'; | ||
|
||
export type CasdoorUserEntity = { | ||
avatar?: string; | ||
displayName: string; | ||
email?: string; | ||
id: string; | ||
}; | ||
|
||
interface CasdoorWebhookPayload { | ||
action: string; | ||
// Only support user event currently | ||
extendedUser: CasdoorUserEntity; | ||
} | ||
|
||
export const validateRequest = async (request: Request, secret?: string) => { | ||
const payloadString = await request.text(); | ||
const headerPayload = headers(); | ||
const casdoorSecret = headerPayload.get('casdoor-secret')!; | ||
try { | ||
if (casdoorSecret === secret) { | ||
return JSON.parse(payloadString) as CasdoorWebhookPayload; | ||
} else { | ||
console.warn( | ||
'[Casdoor]: secret verify failed, please check your secret in `CASDOOR_WEBHOOK_SECRET`', | ||
); | ||
return; | ||
} | ||
} catch (e) { | ||
if (!authEnv.CASDOOR_WEBHOOK_SECRET) { | ||
throw new Error('`CASDOOR_WEBHOOK_SECRET` environment variable is missing.'); | ||
} | ||
console.error('[Casdoor]: incoming webhook failed in verification.\n', e); | ||
return; | ||
} | ||
}; |
This file contains 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 file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
import { OIDCConfig, OIDCUserConfig } from '@auth/core/providers'; | ||
|
||
import { CommonProviderConfig } from './sso.config'; | ||
|
||
interface CasdoorProfile extends Record<string, any> { | ||
avatar: string; | ||
displayName: string; | ||
email: string; | ||
emailVerified: boolean; | ||
firstName: string; | ||
id: string; | ||
lastName: string; | ||
name: string; | ||
owner: string; | ||
permanentAvatar: string; | ||
} | ||
|
||
function LobeCasdoorProvider(config: OIDCUserConfig<CasdoorProfile>): OIDCConfig<CasdoorProfile> { | ||
return { | ||
...CommonProviderConfig, | ||
...config, | ||
id: 'casdoor', | ||
name: 'Casdoor', | ||
profile(profile) { | ||
return { | ||
email: profile.email, | ||
emailVerified: profile.emailVerified ? new Date() : null, | ||
image: profile.avatar, | ||
name: profile.displayName ?? profile.firstName ?? profile.lastName, | ||
providerAccountId: profile.id, | ||
}; | ||
}, | ||
type: 'oidc', | ||
}; | ||
} | ||
|
||
const provider = { | ||
id: 'casdoor', | ||
provider: LobeCasdoorProvider({ | ||
authorization: { | ||
params: { scope: 'openid profile email' }, | ||
}, | ||
clientId: process.env.AUTH_CASDOOR_ID, | ||
clientSecret: process.env.AUTH_CASDOOR_SECRET, | ||
issuer: process.env.AUTH_CASDOOR_ISSUER, | ||
}), | ||
}; | ||
|
||
export default provider; |
This file contains 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