feat: монорепо миграция, Discover/SearxNG улучшения
- Миграция на монорепозиторий (apps/frontend, apps/chat-service, etc.) - Discover: проверка SearxNG, понятное empty state при ненастроенном поиске - searxng.ts: валидация URL, проверка JSON-ответа, авто-добавление http:// - docker/searxng-config: настройки для JSON API SearxNG Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
22
apps/auth-mcs/.env.example
Normal file
22
apps/auth-mcs/.env.example
Normal file
@@ -0,0 +1,22 @@
|
||||
# Обязательные
|
||||
BETTER_AUTH_SECRET= # openssl rand -base64 32
|
||||
BETTER_AUTH_URL=http://localhost:3001
|
||||
|
||||
# База данных (опционально, по умолчанию data/auth.db)
|
||||
# DATABASE_URL=file:./data/auth.db
|
||||
|
||||
# LDAP (опционально — без этих переменных LDAP отключён)
|
||||
# LDAP_URL=ldap://ldap.example.com:389
|
||||
# LDAP_BIND_DN=cn=admin,dc=example,dc=com
|
||||
# LDAP_PASSWORD=admin_password
|
||||
# LDAP_BASE_DN=ou=users,dc=example,dc=com
|
||||
# LDAP_USERNAME_ATTR=uid
|
||||
|
||||
# Показать вкладку LDAP на форме входа
|
||||
# NEXT_PUBLIC_LDAP_ENABLED=true
|
||||
|
||||
# Trusted OAuth clients (JSON, опционально)
|
||||
# TRUSTED_CLIENTS=[{"clientId":"app1","clientSecret":"secret","name":"My App","type":"web","redirectUrls":["http://localhost:3000/callback"],"skipConsent":true}]
|
||||
|
||||
# Trusted origins для CORS
|
||||
# TRUSTED_ORIGINS=http://app1.local,http://app2.local
|
||||
6
apps/auth-mcs/.gitignore
vendored
Normal file
6
apps/auth-mcs/.gitignore
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
node_modules
|
||||
.next
|
||||
data/
|
||||
.env
|
||||
.env.local
|
||||
*.log
|
||||
34
apps/auth-mcs/Dockerfile
Normal file
34
apps/auth-mcs/Dockerfile
Normal file
@@ -0,0 +1,34 @@
|
||||
FROM node:20-alpine AS base
|
||||
|
||||
FROM base AS deps
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json* ./
|
||||
RUN npm ci
|
||||
|
||||
FROM base AS builder
|
||||
WORKDIR /app
|
||||
COPY --from=deps /app/node_modules ./node_modules
|
||||
COPY . .
|
||||
|
||||
# Сборка без env check для статики
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
RUN npm run build
|
||||
|
||||
FROM base AS runner
|
||||
WORKDIR /app
|
||||
ENV NODE_ENV=production
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
|
||||
RUN addgroup --system --gid 1001 nodejs
|
||||
RUN adduser --system --uid 1001 nextjs
|
||||
|
||||
COPY --from=builder /app/public ./public
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
|
||||
|
||||
USER nextjs
|
||||
EXPOSE 3001
|
||||
ENV PORT=3001
|
||||
ENV HOSTNAME="0.0.0.0"
|
||||
|
||||
CMD ["node", "server.js"]
|
||||
135
apps/auth-mcs/README.md
Normal file
135
apps/auth-mcs/README.md
Normal file
@@ -0,0 +1,135 @@
|
||||
# Auth Microservice — Identity Provider
|
||||
|
||||
Отдельный микросервис аутентификации с поддержкой **SSO**, **LDAP** и **OIDC**. Выступает как единый Identity Provider для регистрации и входа во все приложения вашего ландшафта.
|
||||
|
||||
## Возможности
|
||||
|
||||
- **Email/пароль** — регистрация и вход
|
||||
- **LDAP / Active Directory** — вход через корпоративный каталог
|
||||
- **SSO** — вход через внешние IdP (Okta, Google, Azure AD, Keycloak и др.)
|
||||
- **OIDC Provider** — этот сервис выступает как IdP для других приложений (Perplexica и др.)
|
||||
|
||||
## Быстрый старт
|
||||
|
||||
### Локально
|
||||
|
||||
```bash
|
||||
cd auth-microservice
|
||||
cp .env.example .env
|
||||
# Отредактируйте .env: BETTER_AUTH_SECRET, BETTER_AUTH_URL
|
||||
npm install
|
||||
npm run db:migrate # Создание таблиц БД
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Сервис доступен по адресу: **http://localhost:3001**
|
||||
|
||||
### Docker
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
## Конфигурация
|
||||
|
||||
### Обязательные переменные
|
||||
|
||||
| Переменная | Описание |
|
||||
|------------|----------|
|
||||
| `BETTER_AUTH_SECRET` | Секрет для шифрования (минимум 32 символа). Сгенерируйте: `openssl rand -base64 32` |
|
||||
| `BETTER_AUTH_URL` | Публичный URL сервиса (например `https://auth.example.com`) |
|
||||
|
||||
### LDAP (опционально)
|
||||
|
||||
Если заданы переменные LDAP, включается вход через Active Directory / OpenLDAP:
|
||||
|
||||
| Переменная | Описание |
|
||||
|------------|----------|
|
||||
| `LDAP_URL` | URL LDAP-сервера (`ldap://` или `ldaps://`) |
|
||||
| `LDAP_BIND_DN` | DN для bind (admin) |
|
||||
| `LDAP_PASSWORD` | Пароль для bind |
|
||||
| `LDAP_BASE_DN` | Базовый DN для поиска пользователей |
|
||||
| `LDAP_USERNAME_ATTR` | Атрибут логина (по умолчанию `uid`) |
|
||||
| `NEXT_PUBLIC_LDAP_ENABLED` | `true` — показать вкладку LDAP на форме входа |
|
||||
|
||||
### Trusted OAuth Clients
|
||||
|
||||
Приложения, которые могут использовать этот IdP. Задаётся через `TRUSTED_CLIENTS` (JSON-массив) или `DEFAULT_CLIENT_ID` / `DEFAULT_CLIENT_SECRET`.
|
||||
|
||||
## Интеграция приложений
|
||||
|
||||
### OIDC Endpoints
|
||||
|
||||
```
|
||||
Authorization: {BETTER_AUTH_URL}/api/auth/oauth2/authorize
|
||||
Token: {BETTER_AUTH_URL}/api/auth/oauth2/token
|
||||
UserInfo: {BETTER_AUTH_URL}/api/auth/oauth2/userinfo
|
||||
Discovery: {BETTER_AUTH_URL}/api/auth/.well-known/openid-configuration
|
||||
```
|
||||
|
||||
### Регистрация клиента
|
||||
|
||||
Через API (требуется сессия администратора):
|
||||
|
||||
```
|
||||
POST /api/auth/oauth2/register
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"redirect_uris": ["https://myapp.com/callback"],
|
||||
"client_name": "My Application",
|
||||
"scope": "openid profile email"
|
||||
}
|
||||
```
|
||||
|
||||
### Подключение Perplexica
|
||||
|
||||
В Perplexica настройте Better Auth как OIDC провайдер:
|
||||
|
||||
```ts
|
||||
// В Perplexica
|
||||
baseURL: "http://localhost:3001"
|
||||
// или URL вашего auth-microservice
|
||||
```
|
||||
|
||||
И укажите redirect URL Perplexica в `TRUSTED_CLIENTS` auth-сервиса.
|
||||
|
||||
## SSO (вход через внешние IdP)
|
||||
|
||||
Чтобы пользователи могли входить через Okta, Google и т.п., зарегистрируйте SSO провайдера:
|
||||
|
||||
```ts
|
||||
await authClient.sso.register({
|
||||
providerId: "okta",
|
||||
issuer: "https://your-tenant.okta.com",
|
||||
domain: "company.com",
|
||||
oidcConfig: {
|
||||
clientId: "...",
|
||||
clientSecret: "...",
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## Структура проекта
|
||||
|
||||
```
|
||||
auth-microservice/
|
||||
├── src/
|
||||
│ ├── lib/
|
||||
│ │ ├── auth.ts # Конфигурация Better Auth
|
||||
│ │ ├── auth-client.ts # Клиент для React
|
||||
│ │ └── db.ts # SQLite
|
||||
│ └── app/
|
||||
│ ├── api/auth/ # API Better Auth
|
||||
│ ├── sign-in/ # Страница входа
|
||||
│ ├── sign-up/ # Регистрация
|
||||
│ └── dashboard/ # Личный кабинет
|
||||
├── data/ # SQLite (создаётся автоматически)
|
||||
├── .env.example
|
||||
├── Dockerfile
|
||||
└── docker-compose.yaml
|
||||
```
|
||||
|
||||
## Лицензия
|
||||
|
||||
MIT
|
||||
5
apps/auth-mcs/auth.config.ts
Normal file
5
apps/auth-mcs/auth.config.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
/**
|
||||
* Re-export для Better Auth CLI (db:migrate, db:generate)
|
||||
*/
|
||||
export { auth } from './src/lib/auth';
|
||||
export { db } from './src/lib/db';
|
||||
15
apps/auth-mcs/docker-compose.yaml
Normal file
15
apps/auth-mcs/docker-compose.yaml
Normal file
@@ -0,0 +1,15 @@
|
||||
services:
|
||||
auth:
|
||||
build: .
|
||||
ports:
|
||||
- "3001:3001"
|
||||
environment:
|
||||
BETTER_AUTH_SECRET: "${BETTER_AUTH_SECRET:-change-me-generate-with-openssl-rand-base64-32}"
|
||||
BETTER_AUTH_URL: "${BETTER_AUTH_URL:-http://localhost:3001}"
|
||||
DATABASE_PATH: /app/data/auth.db
|
||||
volumes:
|
||||
- auth-data:/app/data
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
auth-data:
|
||||
6
apps/auth-mcs/next-env.d.ts
vendored
Normal file
6
apps/auth-mcs/next-env.d.ts
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
/// <reference types="next" />
|
||||
/// <reference types="next/image-types/global" />
|
||||
/// <reference path="./.next/types/routes.d.ts" />
|
||||
|
||||
// NOTE: This file should not be edited
|
||||
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
|
||||
7
apps/auth-mcs/next.config.js
Normal file
7
apps/auth-mcs/next.config.js
Normal file
@@ -0,0 +1,7 @@
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
reactStrictMode: true,
|
||||
output: 'standalone',
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
2057
apps/auth-mcs/package-lock.json
generated
Normal file
2057
apps/auth-mcs/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
33
apps/auth-mcs/package.json
Normal file
33
apps/auth-mcs/package.json
Normal file
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"name": "auth-microservice",
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"description": "Standalone Identity Provider microservice with SSO, LDAP, and OIDC",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"dev": "next dev -p 3001",
|
||||
"build": "next build",
|
||||
"start": "next start -p 3001",
|
||||
"lint": "next lint",
|
||||
"db:generate": "npx @better-auth/cli generate",
|
||||
"db:migrate": "npx @better-auth/cli migrate --yes"
|
||||
},
|
||||
"dependencies": {
|
||||
"better-auth": "^1.4.0",
|
||||
"@better-auth/sso": "^1.3.0",
|
||||
"better-auth-credentials-plugin": "^0.4.0",
|
||||
"ldap-authentication": "^3.3.6",
|
||||
"better-sqlite3": "^11.9.1",
|
||||
"next": "^15.0.0",
|
||||
"react": "^18",
|
||||
"react-dom": "^18",
|
||||
"zod": "^3.23.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/better-sqlite3": "^7.6.12",
|
||||
"@types/node": "^20",
|
||||
"@types/react": "^18",
|
||||
"@types/react-dom": "^18",
|
||||
"typescript": "^5.0.0"
|
||||
}
|
||||
}
|
||||
4
apps/auth-mcs/src/app/api/auth/[...all]/route.ts
Normal file
4
apps/auth-mcs/src/app/api/auth/[...all]/route.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
import { auth } from '@/lib/auth';
|
||||
import { toNextJsHandler } from 'better-auth/next-js';
|
||||
|
||||
export const { GET, POST } = toNextJsHandler(auth);
|
||||
31
apps/auth-mcs/src/app/dashboard/SignOutButton.tsx
Normal file
31
apps/auth-mcs/src/app/dashboard/SignOutButton.tsx
Normal file
@@ -0,0 +1,31 @@
|
||||
'use client';
|
||||
|
||||
import { authClient } from '@/lib/auth-client';
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
export function SignOutButton() {
|
||||
const router = useRouter();
|
||||
|
||||
const handleSignOut = async () => {
|
||||
await authClient.signOut();
|
||||
router.push('/sign-in');
|
||||
router.refresh();
|
||||
};
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={handleSignOut}
|
||||
type="button"
|
||||
style={{
|
||||
padding: '8px 16px',
|
||||
background: '#f1f5f9',
|
||||
border: '1px solid #e2e8f0',
|
||||
borderRadius: 8,
|
||||
cursor: 'pointer',
|
||||
fontWeight: 500,
|
||||
}}
|
||||
>
|
||||
Выйти
|
||||
</button>
|
||||
);
|
||||
}
|
||||
101
apps/auth-mcs/src/app/dashboard/page.tsx
Normal file
101
apps/auth-mcs/src/app/dashboard/page.tsx
Normal file
@@ -0,0 +1,101 @@
|
||||
import { redirect } from 'next/navigation';
|
||||
import { headers } from 'next/headers';
|
||||
import { auth } from '@/lib/auth';
|
||||
import { SignOutButton } from './SignOutButton';
|
||||
|
||||
export default async function DashboardPage() {
|
||||
const session = await auth.api.getSession({
|
||||
headers: await headers(),
|
||||
});
|
||||
|
||||
if (!session) {
|
||||
redirect('/sign-in');
|
||||
}
|
||||
|
||||
const discoveryUrl = `${process.env.BETTER_AUTH_URL || 'http://localhost:3001'}/api/auth/.well-known/openid-configuration`;
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
minHeight: '100vh',
|
||||
padding: 32,
|
||||
background: '#f8fafc',
|
||||
}}
|
||||
>
|
||||
<div style={{ maxWidth: 800, margin: '0 auto' }}>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
marginBottom: 32,
|
||||
}}
|
||||
>
|
||||
<h1 style={{ margin: 0, fontSize: 28, fontWeight: 700 }}>
|
||||
Auth Service — Identity Provider
|
||||
</h1>
|
||||
<SignOutButton />
|
||||
</div>
|
||||
|
||||
<div
|
||||
style={{
|
||||
background: '#fff',
|
||||
padding: 24,
|
||||
borderRadius: 12,
|
||||
boxShadow: '0 1px 3px rgba(0,0,0,0.1)',
|
||||
marginBottom: 24,
|
||||
}}
|
||||
>
|
||||
<h2 style={{ margin: '0 0 16px', fontSize: 18 }}>Ваш профиль</h2>
|
||||
<p style={{ margin: 0, color: '#64748b' }}>
|
||||
<strong>Email:</strong> {session.user.email}
|
||||
</p>
|
||||
<p style={{ margin: '8px 0 0', color: '#64748b' }}>
|
||||
<strong>Имя:</strong> {session.user.name || '—'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div
|
||||
style={{
|
||||
background: '#fff',
|
||||
padding: 24,
|
||||
borderRadius: 12,
|
||||
boxShadow: '0 1px 3px rgba(0,0,0,0.1)',
|
||||
}}
|
||||
>
|
||||
<h2 style={{ margin: '0 0 16px', fontSize: 18 }}>
|
||||
Интеграция с приложениями
|
||||
</h2>
|
||||
<p style={{ margin: '0 0 16px', color: '#64748b', fontSize: 14 }}>
|
||||
Этот сервис выступает как OIDC Identity Provider. Подключите ваши
|
||||
приложения, указав следующие параметры:
|
||||
</p>
|
||||
<pre
|
||||
style={{
|
||||
padding: 16,
|
||||
background: '#1e293b',
|
||||
color: '#e2e8f0',
|
||||
borderRadius: 8,
|
||||
overflow: 'auto',
|
||||
fontSize: 13,
|
||||
}}
|
||||
>
|
||||
{`Authorization URL: ${process.env.BETTER_AUTH_URL || 'http://localhost:3001'}/api/auth/oauth2/authorize
|
||||
Token URL: ${process.env.BETTER_AUTH_URL || 'http://localhost:3001'}/api/auth/oauth2/token
|
||||
UserInfo URL: ${process.env.BETTER_AUTH_URL || 'http://localhost:3001'}/api/auth/oauth2/userinfo
|
||||
Discovery: ${discoveryUrl}
|
||||
|
||||
Scopes: openid profile email`}
|
||||
</pre>
|
||||
<p style={{ margin: '16px 0 0', color: '#64748b', fontSize: 14 }}>
|
||||
Зарегистрируйте клиента через API{' '}
|
||||
<code style={{ background: '#f1f5f9', padding: '2px 6px', borderRadius: 4 }}>
|
||||
POST /api/auth/oauth2/register
|
||||
</code>{' '}
|
||||
или настройте trusted clients в конфигурации сервиса.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
18
apps/auth-mcs/src/app/layout.tsx
Normal file
18
apps/auth-mcs/src/app/layout.tsx
Normal file
@@ -0,0 +1,18 @@
|
||||
import type { Metadata } from 'next';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'Auth Service — Identity Provider',
|
||||
description: 'Централизованный сервис аутентификации с SSO, LDAP и OIDC',
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<html lang="ru">
|
||||
<body style={{ margin: 0, fontFamily: 'system-ui, sans-serif' }}>{children}</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
13
apps/auth-mcs/src/app/page.tsx
Normal file
13
apps/auth-mcs/src/app/page.tsx
Normal file
@@ -0,0 +1,13 @@
|
||||
import { redirect } from 'next/navigation';
|
||||
import { headers } from 'next/headers';
|
||||
import { auth } from '@/lib/auth';
|
||||
|
||||
export default async function HomePage() {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
|
||||
if (session) {
|
||||
redirect('/dashboard');
|
||||
}
|
||||
|
||||
redirect('/sign-in');
|
||||
}
|
||||
244
apps/auth-mcs/src/app/sign-in/page.tsx
Normal file
244
apps/auth-mcs/src/app/sign-in/page.tsx
Normal file
@@ -0,0 +1,244 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { authClient } from '@/lib/auth-client';
|
||||
import Link from 'next/link';
|
||||
|
||||
type Tab = 'password' | 'ldap';
|
||||
|
||||
export default function SignInPage() {
|
||||
const router = useRouter();
|
||||
const [tab, setTab] = useState<Tab>('password');
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [credential, setCredential] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const ldapEnabled = process.env.NEXT_PUBLIC_LDAP_ENABLED === 'true';
|
||||
|
||||
const handleEmailSignIn = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setLoading(true);
|
||||
try {
|
||||
const { error } = await authClient.signIn.email({ email, password });
|
||||
if (error) throw new Error(error.message);
|
||||
router.push('/dashboard');
|
||||
router.refresh();
|
||||
} catch (err: unknown) {
|
||||
setError(err instanceof Error ? err.message : 'Ошибка входа');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleLdapSignIn = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await fetch('/api/auth/sign-in/ldap', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ credential, password, callbackURL: '/dashboard' }),
|
||||
credentials: 'include',
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok || data?.error) throw new Error(data?.message || data?.error?.message || 'Ошибка входа');
|
||||
router.push('/dashboard');
|
||||
router.refresh();
|
||||
} catch (err: unknown) {
|
||||
setError(err instanceof Error ? err.message : 'Ошибка LDAP входа');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
minHeight: '100vh',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
background: 'linear-gradient(135deg, #1a1a2e 0%, #16213e 100%)',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
width: '100%',
|
||||
maxWidth: 400,
|
||||
padding: 32,
|
||||
background: '#fff',
|
||||
borderRadius: 12,
|
||||
boxShadow: '0 8px 32px rgba(0,0,0,0.2)',
|
||||
}}
|
||||
>
|
||||
<h1 style={{ margin: '0 0 24px', fontSize: 24, fontWeight: 600 }}>
|
||||
Вход в систему
|
||||
</h1>
|
||||
|
||||
{ldapEnabled && (
|
||||
<div style={{ marginBottom: 16, display: 'flex', gap: 8 }}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setTab('password')}
|
||||
style={{
|
||||
flex: 1,
|
||||
padding: '10px 16px',
|
||||
border: tab === 'password' ? '2px solid #6366f1' : '1px solid #ddd',
|
||||
borderRadius: 8,
|
||||
background: tab === 'password' ? '#eef2ff' : '#fff',
|
||||
cursor: 'pointer',
|
||||
fontWeight: 500,
|
||||
}}
|
||||
>
|
||||
Email
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setTab('ldap')}
|
||||
style={{
|
||||
flex: 1,
|
||||
padding: '10px 16px',
|
||||
border: tab === 'ldap' ? '2px solid #6366f1' : '1px solid #ddd',
|
||||
borderRadius: 8,
|
||||
background: tab === 'ldap' ? '#eef2ff' : '#fff',
|
||||
cursor: 'pointer',
|
||||
fontWeight: 500,
|
||||
}}
|
||||
>
|
||||
LDAP / AD
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div
|
||||
style={{
|
||||
padding: 12,
|
||||
marginBottom: 16,
|
||||
background: '#fef2f2',
|
||||
color: '#dc2626',
|
||||
borderRadius: 8,
|
||||
fontSize: 14,
|
||||
}}
|
||||
>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{tab === 'password' ? (
|
||||
<form onSubmit={handleEmailSignIn}>
|
||||
<input
|
||||
type="email"
|
||||
placeholder="Email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: 12,
|
||||
marginBottom: 12,
|
||||
border: '1px solid #ddd',
|
||||
borderRadius: 8,
|
||||
boxSizing: 'border-box',
|
||||
}}
|
||||
/>
|
||||
<input
|
||||
type="password"
|
||||
placeholder="Пароль"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: 12,
|
||||
marginBottom: 16,
|
||||
border: '1px solid #ddd',
|
||||
borderRadius: 8,
|
||||
boxSizing: 'border-box',
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: 12,
|
||||
background: '#6366f1',
|
||||
color: '#fff',
|
||||
border: 'none',
|
||||
borderRadius: 8,
|
||||
fontSize: 16,
|
||||
fontWeight: 600,
|
||||
cursor: loading ? 'not-allowed' : 'pointer',
|
||||
}}
|
||||
>
|
||||
{loading ? 'Вход...' : 'Войти'}
|
||||
</button>
|
||||
</form>
|
||||
) : (
|
||||
<form onSubmit={handleLdapSignIn}>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Логин или DN"
|
||||
value={credential}
|
||||
onChange={(e) => setCredential(e.target.value)}
|
||||
required
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: 12,
|
||||
marginBottom: 12,
|
||||
border: '1px solid #ddd',
|
||||
borderRadius: 8,
|
||||
boxSizing: 'border-box',
|
||||
}}
|
||||
/>
|
||||
<input
|
||||
type="password"
|
||||
placeholder="Пароль"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: 12,
|
||||
marginBottom: 16,
|
||||
border: '1px solid #ddd',
|
||||
borderRadius: 8,
|
||||
boxSizing: 'border-box',
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: 12,
|
||||
background: '#6366f1',
|
||||
color: '#fff',
|
||||
border: 'none',
|
||||
borderRadius: 8,
|
||||
fontSize: 16,
|
||||
fontWeight: 600,
|
||||
cursor: loading ? 'not-allowed' : 'pointer',
|
||||
}}
|
||||
>
|
||||
{loading ? 'Вход...' : 'Войти через LDAP'}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
|
||||
<p style={{ marginTop: 24, textAlign: 'center', fontSize: 14, color: '#666' }}>
|
||||
Нет аккаунта?{' '}
|
||||
<Link href="/sign-up" style={{ color: '#6366f1', textDecoration: 'none' }}>
|
||||
Регистрация
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
150
apps/auth-mcs/src/app/sign-up/page.tsx
Normal file
150
apps/auth-mcs/src/app/sign-up/page.tsx
Normal file
@@ -0,0 +1,150 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { authClient } from '@/lib/auth-client';
|
||||
import Link from 'next/link';
|
||||
|
||||
export default function SignUpPage() {
|
||||
const router = useRouter();
|
||||
const [name, setName] = useState('');
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const handleSignUp = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setLoading(true);
|
||||
try {
|
||||
const { error } = await authClient.signUp.email({
|
||||
name,
|
||||
email,
|
||||
password,
|
||||
});
|
||||
if (error) throw new Error(error.message);
|
||||
router.push('/dashboard');
|
||||
router.refresh();
|
||||
} catch (err: unknown) {
|
||||
setError(err instanceof Error ? err.message : 'Ошибка регистрации');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
minHeight: '100vh',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
background: 'linear-gradient(135deg, #1a1a2e 0%, #16213e 100%)',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
width: '100%',
|
||||
maxWidth: 400,
|
||||
padding: 32,
|
||||
background: '#fff',
|
||||
borderRadius: 12,
|
||||
boxShadow: '0 8px 32px rgba(0,0,0,0.2)',
|
||||
}}
|
||||
>
|
||||
<h1 style={{ margin: '0 0 24px', fontSize: 24, fontWeight: 600 }}>
|
||||
Регистрация
|
||||
</h1>
|
||||
|
||||
{error && (
|
||||
<div
|
||||
style={{
|
||||
padding: 12,
|
||||
marginBottom: 16,
|
||||
background: '#fef2f2',
|
||||
color: '#dc2626',
|
||||
borderRadius: 8,
|
||||
fontSize: 14,
|
||||
}}
|
||||
>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSignUp}>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Имя"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
required
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: 12,
|
||||
marginBottom: 12,
|
||||
border: '1px solid #ddd',
|
||||
borderRadius: 8,
|
||||
boxSizing: 'border-box',
|
||||
}}
|
||||
/>
|
||||
<input
|
||||
type="email"
|
||||
placeholder="Email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: 12,
|
||||
marginBottom: 12,
|
||||
border: '1px solid #ddd',
|
||||
borderRadius: 8,
|
||||
boxSizing: 'border-box',
|
||||
}}
|
||||
/>
|
||||
<input
|
||||
type="password"
|
||||
placeholder="Пароль"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
minLength={8}
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: 12,
|
||||
marginBottom: 16,
|
||||
border: '1px solid #ddd',
|
||||
borderRadius: 8,
|
||||
boxSizing: 'border-box',
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: 12,
|
||||
background: '#6366f1',
|
||||
color: '#fff',
|
||||
border: 'none',
|
||||
borderRadius: 8,
|
||||
fontSize: 16,
|
||||
fontWeight: 600,
|
||||
cursor: loading ? 'not-allowed' : 'pointer',
|
||||
}}
|
||||
>
|
||||
{loading ? 'Регистрация...' : 'Зарегистрироваться'}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<p style={{ marginTop: 24, textAlign: 'center', fontSize: 14, color: '#666' }}>
|
||||
Уже есть аккаунт?{' '}
|
||||
<Link href="/sign-in" style={{ color: '#6366f1', textDecoration: 'none' }}>
|
||||
Войти
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
11
apps/auth-mcs/src/lib/auth-client.ts
Normal file
11
apps/auth-mcs/src/lib/auth-client.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
'use client';
|
||||
|
||||
import { createAuthClient } from 'better-auth/react';
|
||||
import { ssoClient } from '@better-auth/sso/client';
|
||||
import { oidcClient } from 'better-auth/client/plugins';
|
||||
|
||||
export const authClient = createAuthClient({
|
||||
baseURL:
|
||||
typeof window !== 'undefined' ? window.location.origin : process.env.NEXT_PUBLIC_AUTH_URL,
|
||||
plugins: [ssoClient(), oidcClient()],
|
||||
});
|
||||
97
apps/auth-mcs/src/lib/auth.ts
Normal file
97
apps/auth-mcs/src/lib/auth.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
import { betterAuth } from 'better-auth';
|
||||
import { sso } from '@better-auth/sso';
|
||||
import { oidcProvider } from 'better-auth/plugins';
|
||||
import { credentials } from 'better-auth-credentials-plugin';
|
||||
import { authenticate } from 'ldap-authentication';
|
||||
import { z } from 'zod';
|
||||
import { db } from './db';
|
||||
|
||||
const baseUrl = process.env.BETTER_AUTH_URL || 'http://localhost:3001';
|
||||
|
||||
export const auth = betterAuth({
|
||||
database: db,
|
||||
basePath: '/api/auth',
|
||||
baseURL: baseUrl,
|
||||
trustedOrigins: [
|
||||
baseUrl,
|
||||
'http://localhost:3000',
|
||||
'http://localhost:3001',
|
||||
...(process.env.TRUSTED_ORIGINS || '').split(',').filter(Boolean),
|
||||
],
|
||||
emailAndPassword: {
|
||||
enabled: true,
|
||||
},
|
||||
plugins: [
|
||||
// SSO — вход через внешние IdP (Okta, Google, Azure AD)
|
||||
sso(),
|
||||
|
||||
// OIDC Provider — этот сервис выступает как IdP для других приложений
|
||||
oidcProvider({
|
||||
loginPage: '/sign-in',
|
||||
allowDynamicClientRegistration: true,
|
||||
trustedClients: (() => {
|
||||
try {
|
||||
if (process.env.TRUSTED_CLIENTS) {
|
||||
return JSON.parse(process.env.TRUSTED_CLIENTS);
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
return [
|
||||
{
|
||||
clientId: process.env.DEFAULT_CLIENT_ID || 'perplexica',
|
||||
clientSecret: process.env.DEFAULT_CLIENT_SECRET || 'perplexica-secret-change-me',
|
||||
name: 'Perplexica',
|
||||
type: 'web',
|
||||
redirectUrls: ['http://localhost:3000/api/auth/callback/better-auth'],
|
||||
disabled: false,
|
||||
skipConsent: true,
|
||||
},
|
||||
];
|
||||
})(),
|
||||
}),
|
||||
|
||||
// LDAP — вход через Active Directory / OpenLDAP
|
||||
...(process.env.LDAP_URL
|
||||
? [
|
||||
credentials({
|
||||
autoSignUp: true,
|
||||
linkAccountIfExisting: true,
|
||||
providerId: 'ldap',
|
||||
path: '/sign-in/ldap',
|
||||
inputSchema: z.object({
|
||||
credential: z.string().min(1, 'Username or DN required'),
|
||||
password: z.string().min(1, 'Password required'),
|
||||
}),
|
||||
async callback(_ctx, parsed) {
|
||||
const ldapResult = await authenticate({
|
||||
ldapOpts: {
|
||||
url: process.env.LDAP_URL!,
|
||||
connectTimeout: 5000,
|
||||
...(process.env.LDAP_URL!.startsWith('ldaps://')
|
||||
? { tlsOptions: { minVersion: 'TLSv1.2' } }
|
||||
: {}),
|
||||
},
|
||||
adminDn: process.env.LDAP_BIND_DN || '',
|
||||
adminPassword: process.env.LDAP_PASSWORD || '',
|
||||
userSearchBase: process.env.LDAP_BASE_DN || '',
|
||||
usernameAttribute: process.env.LDAP_USERNAME_ATTR || 'uid',
|
||||
username: parsed.credential,
|
||||
userPassword: parsed.password,
|
||||
});
|
||||
|
||||
const uid = ldapResult[process.env.LDAP_USERNAME_ATTR || 'uid'];
|
||||
const email =
|
||||
(Array.isArray(ldapResult.mail) ? ldapResult.mail[0] : ldapResult.mail) ||
|
||||
`${uid}@local`;
|
||||
|
||||
return {
|
||||
email,
|
||||
name: ldapResult.displayName || ldapResult.cn || String(uid),
|
||||
};
|
||||
},
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
],
|
||||
});
|
||||
15
apps/auth-mcs/src/lib/db.ts
Normal file
15
apps/auth-mcs/src/lib/db.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import Database from 'better-sqlite3';
|
||||
import path from 'node:path';
|
||||
import fs from 'node:fs';
|
||||
|
||||
const defaultPath = path.join(process.cwd(), 'data', 'auth.db');
|
||||
const dbPath = process.env.DATABASE_URL?.startsWith('file:')
|
||||
? process.env.DATABASE_URL.replace(/^file:/, '')
|
||||
: process.env.DATABASE_PATH || defaultPath;
|
||||
|
||||
const dir = path.dirname(dbPath);
|
||||
if (!fs.existsSync(dir)) {
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
|
||||
export const db = new Database(dbPath);
|
||||
21
apps/auth-mcs/tsconfig.json
Normal file
21
apps/auth-mcs/tsconfig.json
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2017",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "preserve",
|
||||
"incremental": true,
|
||||
"plugins": [{ "name": "next" }],
|
||||
"paths": { "@/*": ["./src/*"] }
|
||||
},
|
||||
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
Reference in New Issue
Block a user