hightjs 0.1.1 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/http.js +5 -3
- package/dist/auth/client.d.ts +11 -1
- package/dist/auth/client.js +78 -0
- package/dist/auth/core.d.ts +21 -4
- package/dist/auth/core.js +66 -17
- package/dist/auth/example.d.ts +40 -0
- package/dist/auth/example.js +104 -0
- package/dist/auth/index.d.ts +1 -1
- package/dist/auth/index.js +2 -1
- package/dist/auth/providers/credentials.d.ts +68 -0
- package/dist/auth/providers/credentials.js +132 -0
- package/dist/auth/providers/discord.d.ts +67 -0
- package/dist/auth/providers/discord.js +198 -0
- package/dist/auth/providers/index.d.ts +2 -0
- package/dist/auth/providers/index.js +19 -0
- package/dist/auth/providers.d.ts +2 -5
- package/dist/auth/providers.js +6 -12
- package/dist/auth/react.js +20 -13
- package/dist/auth/routes.d.ts +2 -2
- package/dist/auth/routes.js +45 -13
- package/dist/auth/types.d.ts +36 -21
- package/dist/router.js +9 -1
- package/package.json +1 -1
- package/src/api/http.ts +6 -2
- package/src/auth/client.ts +84 -3
- package/src/auth/core.ts +75 -19
- package/src/auth/example.ts +115 -0
- package/src/auth/index.ts +2 -1
- package/src/auth/providers/credentials.ts +158 -0
- package/src/auth/providers/discord.ts +231 -0
- package/src/auth/providers/index.ts +4 -0
- package/src/auth/providers.ts +3 -12
- package/src/auth/react.tsx +21 -13
- package/src/auth/routes.ts +51 -18
- package/src/auth/types.ts +49 -26
- package/src/router.ts +9 -1
package/dist/api/http.js
CHANGED
|
@@ -362,14 +362,16 @@ class HightJSResponse {
|
|
|
362
362
|
res.cookie(name, value, options);
|
|
363
363
|
}
|
|
364
364
|
});
|
|
365
|
+
// Handle redirects specifically
|
|
366
|
+
if (this._headers['Location']) {
|
|
367
|
+
res.redirect(this._headers['Location']);
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
365
370
|
// Envia o corpo se foi definido
|
|
366
371
|
if (this._sent && this._body !== null) {
|
|
367
372
|
if (this._headers['Content-Type']?.includes('application/json')) {
|
|
368
373
|
res.json(JSON.parse(this._body));
|
|
369
374
|
}
|
|
370
|
-
else if (this._headers['Location']) {
|
|
371
|
-
res.redirect(this._headers['Location']);
|
|
372
|
-
}
|
|
373
375
|
else {
|
|
374
376
|
res.send(this._body);
|
|
375
377
|
}
|
package/dist/auth/client.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Session } from './types';
|
|
1
|
+
import type { SignInOptions, SignInResult, Session } from './types';
|
|
2
2
|
export declare function setBasePath(path: string): void;
|
|
3
3
|
/**
|
|
4
4
|
* Função para obter a sessão atual (similar ao NextAuth getSession)
|
|
@@ -12,3 +12,13 @@ export declare function getCsrfToken(): Promise<string | null>;
|
|
|
12
12
|
* Função para obter providers disponíveis
|
|
13
13
|
*/
|
|
14
14
|
export declare function getProviders(): Promise<any[] | null>;
|
|
15
|
+
/**
|
|
16
|
+
* Função para fazer login (similar ao NextAuth signIn)
|
|
17
|
+
*/
|
|
18
|
+
export declare function signIn(provider?: string, options?: SignInOptions): Promise<SignInResult | undefined>;
|
|
19
|
+
/**
|
|
20
|
+
* Função para fazer logout (similar ao NextAuth signOut)
|
|
21
|
+
*/
|
|
22
|
+
export declare function signOut(options?: {
|
|
23
|
+
callbackUrl?: string;
|
|
24
|
+
}): Promise<void>;
|
package/dist/auth/client.js
CHANGED
|
@@ -4,6 +4,8 @@ exports.setBasePath = setBasePath;
|
|
|
4
4
|
exports.getSession = getSession;
|
|
5
5
|
exports.getCsrfToken = getCsrfToken;
|
|
6
6
|
exports.getProviders = getProviders;
|
|
7
|
+
exports.signIn = signIn;
|
|
8
|
+
exports.signOut = signOut;
|
|
7
9
|
// Configuração global do client
|
|
8
10
|
let basePath = '/api/auth';
|
|
9
11
|
function setBasePath(path) {
|
|
@@ -66,3 +68,79 @@ async function getProviders() {
|
|
|
66
68
|
return null;
|
|
67
69
|
}
|
|
68
70
|
}
|
|
71
|
+
/**
|
|
72
|
+
* Função para fazer login (similar ao NextAuth signIn)
|
|
73
|
+
*/
|
|
74
|
+
async function signIn(provider = 'credentials', options = {}) {
|
|
75
|
+
try {
|
|
76
|
+
const { redirect = true, callbackUrl, ...credentials } = options;
|
|
77
|
+
const response = await fetch(`${basePath}/signin`, {
|
|
78
|
+
method: 'POST',
|
|
79
|
+
headers: {
|
|
80
|
+
'Content-Type': 'application/json',
|
|
81
|
+
},
|
|
82
|
+
credentials: 'include',
|
|
83
|
+
body: JSON.stringify({
|
|
84
|
+
provider,
|
|
85
|
+
...credentials
|
|
86
|
+
})
|
|
87
|
+
});
|
|
88
|
+
const data = await response.json();
|
|
89
|
+
if (response.ok && data.success) {
|
|
90
|
+
// Se é OAuth, redireciona para URL fornecida
|
|
91
|
+
if (data.type === 'oauth' && data.redirectUrl) {
|
|
92
|
+
if (redirect && typeof window !== 'undefined') {
|
|
93
|
+
window.location.href = data.redirectUrl;
|
|
94
|
+
}
|
|
95
|
+
return {
|
|
96
|
+
ok: true,
|
|
97
|
+
status: 200,
|
|
98
|
+
url: data.redirectUrl
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
// Se é sessão (credentials), redireciona para callbackUrl
|
|
102
|
+
if (data.type === 'session') {
|
|
103
|
+
if (redirect && typeof window !== 'undefined') {
|
|
104
|
+
window.location.href = callbackUrl || '/';
|
|
105
|
+
}
|
|
106
|
+
return {
|
|
107
|
+
ok: true,
|
|
108
|
+
status: 200,
|
|
109
|
+
url: callbackUrl || '/'
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
else {
|
|
114
|
+
return {
|
|
115
|
+
error: data.error || 'Authentication failed',
|
|
116
|
+
status: response.status,
|
|
117
|
+
ok: false
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
catch (error) {
|
|
122
|
+
console.error('[hweb-auth] Erro no signIn:', error);
|
|
123
|
+
return {
|
|
124
|
+
error: 'Network error',
|
|
125
|
+
status: 500,
|
|
126
|
+
ok: false
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Função para fazer logout (similar ao NextAuth signOut)
|
|
132
|
+
*/
|
|
133
|
+
async function signOut(options = {}) {
|
|
134
|
+
try {
|
|
135
|
+
await fetch(`${basePath}/signout`, {
|
|
136
|
+
method: 'POST',
|
|
137
|
+
credentials: 'include'
|
|
138
|
+
});
|
|
139
|
+
if (typeof window !== 'undefined') {
|
|
140
|
+
window.location.href = options.callbackUrl || '/';
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
catch (error) {
|
|
144
|
+
console.error('[hweb-auth] Erro no signOut:', error);
|
|
145
|
+
}
|
|
146
|
+
}
|
package/dist/auth/core.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { HightJSRequest, HightJSResponse } from '../api/http';
|
|
2
|
-
import type { AuthConfig, Session } from './types';
|
|
2
|
+
import type { AuthConfig, AuthProviderClass, Session } from './types';
|
|
3
3
|
export declare class HWebAuth {
|
|
4
4
|
private config;
|
|
5
5
|
private sessionManager;
|
|
@@ -9,16 +9,18 @@ export declare class HWebAuth {
|
|
|
9
9
|
*/
|
|
10
10
|
private middleware;
|
|
11
11
|
/**
|
|
12
|
-
* Autentica um usuário
|
|
12
|
+
* Autentica um usuário usando um provider específico
|
|
13
13
|
*/
|
|
14
|
-
signIn(
|
|
14
|
+
signIn(providerId: string, credentials: Record<string, string>): Promise<{
|
|
15
15
|
session: Session;
|
|
16
16
|
token: string;
|
|
17
|
+
} | {
|
|
18
|
+
redirectUrl: string;
|
|
17
19
|
} | null>;
|
|
18
20
|
/**
|
|
19
21
|
* Faz logout do usuário
|
|
20
22
|
*/
|
|
21
|
-
signOut(): HightJSResponse
|
|
23
|
+
signOut(req: HightJSRequest): Promise<HightJSResponse>;
|
|
22
24
|
/**
|
|
23
25
|
* Obtém a sessão atual
|
|
24
26
|
*/
|
|
@@ -27,6 +29,21 @@ export declare class HWebAuth {
|
|
|
27
29
|
* Verifica se o usuário está autenticado
|
|
28
30
|
*/
|
|
29
31
|
isAuthenticated(req: HightJSRequest): Promise<boolean>;
|
|
32
|
+
/**
|
|
33
|
+
* Retorna todos os providers disponíveis (dados públicos)
|
|
34
|
+
*/
|
|
35
|
+
getProviders(): any[];
|
|
36
|
+
/**
|
|
37
|
+
* Busca um provider específico
|
|
38
|
+
*/
|
|
39
|
+
getProvider(id: string): AuthProviderClass | null;
|
|
40
|
+
/**
|
|
41
|
+
* Retorna todas as rotas adicionais dos providers
|
|
42
|
+
*/
|
|
43
|
+
getAllAdditionalRoutes(): Array<{
|
|
44
|
+
provider: string;
|
|
45
|
+
route: any;
|
|
46
|
+
}>;
|
|
30
47
|
/**
|
|
31
48
|
* Cria resposta com cookie de autenticação - Secure implementation
|
|
32
49
|
*/
|
package/dist/auth/core.js
CHANGED
|
@@ -27,49 +27,67 @@ class HWebAuth {
|
|
|
27
27
|
};
|
|
28
28
|
}
|
|
29
29
|
/**
|
|
30
|
-
* Autentica um usuário
|
|
30
|
+
* Autentica um usuário usando um provider específico
|
|
31
31
|
*/
|
|
32
|
-
async signIn(
|
|
33
|
-
const
|
|
34
|
-
if (!
|
|
35
|
-
|
|
36
|
-
}
|
|
37
|
-
if (!authProvider.authorize) {
|
|
32
|
+
async signIn(providerId, credentials) {
|
|
33
|
+
const provider = this.config.providers.find(p => p.id === providerId);
|
|
34
|
+
if (!provider) {
|
|
35
|
+
console.error(`[hweb-auth] Provider not found: ${providerId}`);
|
|
38
36
|
return null;
|
|
39
37
|
}
|
|
40
38
|
try {
|
|
41
|
-
|
|
42
|
-
|
|
39
|
+
// Usa o método handleSignIn do provider
|
|
40
|
+
const result = await provider.handleSignIn(credentials);
|
|
41
|
+
if (!result)
|
|
43
42
|
return null;
|
|
43
|
+
// Se resultado é string, é URL de redirecionamento OAuth
|
|
44
|
+
if (typeof result === 'string') {
|
|
45
|
+
return { redirectUrl: result };
|
|
46
|
+
}
|
|
47
|
+
// Se resultado é User, cria sessão
|
|
48
|
+
const user = result;
|
|
44
49
|
// Callback de signIn se definido
|
|
45
50
|
if (this.config.callbacks?.signIn) {
|
|
46
|
-
const allowed = await this.config.callbacks.signIn(user, { provider }, {});
|
|
51
|
+
const allowed = await this.config.callbacks.signIn(user, { provider: providerId }, {});
|
|
47
52
|
if (!allowed)
|
|
48
53
|
return null;
|
|
49
54
|
}
|
|
50
|
-
const
|
|
55
|
+
const sessionResult = this.sessionManager.createSession(user);
|
|
51
56
|
// Callback de sessão se definido
|
|
52
57
|
if (this.config.callbacks?.session) {
|
|
53
|
-
|
|
58
|
+
sessionResult.session = await this.config.callbacks.session(sessionResult.session, user);
|
|
54
59
|
}
|
|
55
|
-
return
|
|
60
|
+
return sessionResult;
|
|
56
61
|
}
|
|
57
62
|
catch (error) {
|
|
58
|
-
console.error(
|
|
63
|
+
console.error(`[hweb-auth] Erro no signIn com provider ${providerId}:`, error);
|
|
59
64
|
return null;
|
|
60
65
|
}
|
|
61
66
|
}
|
|
62
67
|
/**
|
|
63
68
|
* Faz logout do usuário
|
|
64
69
|
*/
|
|
65
|
-
signOut() {
|
|
70
|
+
async signOut(req) {
|
|
71
|
+
// Busca a sessão atual para saber qual provider usar
|
|
72
|
+
const { session } = await this.middleware(req);
|
|
73
|
+
if (session?.user?.provider) {
|
|
74
|
+
const provider = this.config.providers.find(p => p.id === session.user.provider);
|
|
75
|
+
if (provider && provider.handleSignOut) {
|
|
76
|
+
try {
|
|
77
|
+
await provider.handleSignOut();
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
console.error(`[hweb-auth] Erro no signOut do provider ${provider.id}:`, error);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
66
84
|
return http_1.HightJSResponse
|
|
67
85
|
.json({ success: true })
|
|
68
86
|
.clearCookie('hweb-auth-token', {
|
|
69
87
|
path: '/',
|
|
70
88
|
httpOnly: true,
|
|
71
|
-
secure: true,
|
|
72
|
-
sameSite: 'strict'
|
|
89
|
+
secure: true,
|
|
90
|
+
sameSite: 'strict'
|
|
73
91
|
});
|
|
74
92
|
}
|
|
75
93
|
/**
|
|
@@ -86,6 +104,37 @@ class HWebAuth {
|
|
|
86
104
|
const session = await this.getSession(req);
|
|
87
105
|
return session !== null;
|
|
88
106
|
}
|
|
107
|
+
/**
|
|
108
|
+
* Retorna todos os providers disponíveis (dados públicos)
|
|
109
|
+
*/
|
|
110
|
+
getProviders() {
|
|
111
|
+
return this.config.providers.map(provider => ({
|
|
112
|
+
id: provider.id,
|
|
113
|
+
name: provider.name,
|
|
114
|
+
type: provider.type,
|
|
115
|
+
config: provider.getConfig ? provider.getConfig() : {}
|
|
116
|
+
}));
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Busca um provider específico
|
|
120
|
+
*/
|
|
121
|
+
getProvider(id) {
|
|
122
|
+
return this.config.providers.find(p => p.id === id) || null;
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Retorna todas as rotas adicionais dos providers
|
|
126
|
+
*/
|
|
127
|
+
getAllAdditionalRoutes() {
|
|
128
|
+
const routes = [];
|
|
129
|
+
for (const provider of this.config.providers) {
|
|
130
|
+
if (provider.additionalRoutes) {
|
|
131
|
+
for (const route of provider.additionalRoutes) {
|
|
132
|
+
routes.push({ provider: provider.id, route });
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return routes;
|
|
137
|
+
}
|
|
89
138
|
/**
|
|
90
139
|
* Cria resposta com cookie de autenticação - Secure implementation
|
|
91
140
|
*/
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Exemplo de como usar os novos providers baseados em classes
|
|
3
|
+
*/
|
|
4
|
+
export declare const authRoutes: {
|
|
5
|
+
pattern: string;
|
|
6
|
+
GET(req: import("..").HightJSRequest, params: {
|
|
7
|
+
[key: string]: string;
|
|
8
|
+
}): Promise<any>;
|
|
9
|
+
POST(req: import("..").HightJSRequest, params: {
|
|
10
|
+
[key: string]: string;
|
|
11
|
+
}): Promise<any>;
|
|
12
|
+
auth: import("./core").HWebAuth;
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Como usar em suas rotas API:
|
|
16
|
+
*
|
|
17
|
+
* // arquivo: /api/auth/[...value].ts
|
|
18
|
+
* import { authRoutes } from '../../../src/auth/example';
|
|
19
|
+
*
|
|
20
|
+
* export const GET = authRoutes.GET;
|
|
21
|
+
* export const POST = authRoutes.POST;
|
|
22
|
+
*/
|
|
23
|
+
/**
|
|
24
|
+
* Rotas disponíveis automaticamente:
|
|
25
|
+
*
|
|
26
|
+
* Core routes:
|
|
27
|
+
* - GET /api/auth/session - Obter sessão atual
|
|
28
|
+
* - GET /api/auth/providers - Listar providers
|
|
29
|
+
* - GET /api/auth/csrf - Obter token CSRF
|
|
30
|
+
* - POST /api/auth/signin - Login
|
|
31
|
+
* - POST /api/auth/signout - Logout
|
|
32
|
+
*
|
|
33
|
+
* Provider específico (CredentialsProvider):
|
|
34
|
+
* - GET /api/auth/credentials/config - Config do provider
|
|
35
|
+
*
|
|
36
|
+
* Provider específico (DiscordProvider):
|
|
37
|
+
* - GET /api/auth/signin/discord - Iniciar OAuth Discord
|
|
38
|
+
* - GET /api/auth/callback/discord - Callback OAuth Discord
|
|
39
|
+
* - GET /api/auth/discord/config - Config do provider Discord
|
|
40
|
+
*/
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Exemplo de como usar os novos providers baseados em classes
|
|
4
|
+
*/
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.authRoutes = void 0;
|
|
7
|
+
const routes_1 = require("./routes");
|
|
8
|
+
const providers_1 = require("./providers");
|
|
9
|
+
// Exemplo de configuração com os novos providers
|
|
10
|
+
const authConfig = {
|
|
11
|
+
providers: [
|
|
12
|
+
// Provider de credenciais customizado
|
|
13
|
+
new providers_1.CredentialsProvider({
|
|
14
|
+
name: "Login com Email",
|
|
15
|
+
credentials: {
|
|
16
|
+
email: {
|
|
17
|
+
label: "Email",
|
|
18
|
+
type: "email",
|
|
19
|
+
placeholder: "seu@email.com"
|
|
20
|
+
},
|
|
21
|
+
password: {
|
|
22
|
+
label: "Senha",
|
|
23
|
+
type: "password"
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
async authorize(credentials) {
|
|
27
|
+
// Aqui você faz a validação com seu banco de dados
|
|
28
|
+
const { email, password } = credentials;
|
|
29
|
+
// Exemplo de validação (substitua pela sua lógica)
|
|
30
|
+
if (email === "admin@example.com" && password === "123456") {
|
|
31
|
+
return {
|
|
32
|
+
id: "1",
|
|
33
|
+
name: "Admin User",
|
|
34
|
+
email: email,
|
|
35
|
+
role: "admin"
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
// Retorna null se credenciais inválidas
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
}),
|
|
42
|
+
// Provider do Discord
|
|
43
|
+
new providers_1.DiscordProvider({
|
|
44
|
+
clientId: process.env.DISCORD_CLIENT_ID,
|
|
45
|
+
clientSecret: process.env.DISCORD_CLIENT_SECRET,
|
|
46
|
+
callbackUrl: "http://localhost:3000/api/auth/callback/discord"
|
|
47
|
+
})
|
|
48
|
+
],
|
|
49
|
+
secret: process.env.HWEB_AUTH_SECRET || "seu-super-secret-aqui-32-chars-min",
|
|
50
|
+
session: {
|
|
51
|
+
strategy: 'jwt',
|
|
52
|
+
maxAge: 86400 // 24 horas
|
|
53
|
+
},
|
|
54
|
+
pages: {
|
|
55
|
+
signIn: '/auth/signin',
|
|
56
|
+
signOut: '/auth/signout'
|
|
57
|
+
},
|
|
58
|
+
callbacks: {
|
|
59
|
+
async signIn(user, account, profile) {
|
|
60
|
+
// Lógica customizada antes do login
|
|
61
|
+
console.log(`Usuário ${user.email} fazendo login via ${account.provider}`);
|
|
62
|
+
return true; // permitir login
|
|
63
|
+
},
|
|
64
|
+
async session(session, user) {
|
|
65
|
+
// Adicionar dados customizados à sessão
|
|
66
|
+
return {
|
|
67
|
+
...session,
|
|
68
|
+
user: {
|
|
69
|
+
...session.user,
|
|
70
|
+
customData: "dados extras"
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
// Criar as rotas de autenticação
|
|
77
|
+
exports.authRoutes = (0, routes_1.createAuthRoutes)(authConfig);
|
|
78
|
+
/**
|
|
79
|
+
* Como usar em suas rotas API:
|
|
80
|
+
*
|
|
81
|
+
* // arquivo: /api/auth/[...value].ts
|
|
82
|
+
* import { authRoutes } from '../../../src/auth/example';
|
|
83
|
+
*
|
|
84
|
+
* export const GET = authRoutes.GET;
|
|
85
|
+
* export const POST = authRoutes.POST;
|
|
86
|
+
*/
|
|
87
|
+
/**
|
|
88
|
+
* Rotas disponíveis automaticamente:
|
|
89
|
+
*
|
|
90
|
+
* Core routes:
|
|
91
|
+
* - GET /api/auth/session - Obter sessão atual
|
|
92
|
+
* - GET /api/auth/providers - Listar providers
|
|
93
|
+
* - GET /api/auth/csrf - Obter token CSRF
|
|
94
|
+
* - POST /api/auth/signin - Login
|
|
95
|
+
* - POST /api/auth/signout - Logout
|
|
96
|
+
*
|
|
97
|
+
* Provider específico (CredentialsProvider):
|
|
98
|
+
* - GET /api/auth/credentials/config - Config do provider
|
|
99
|
+
*
|
|
100
|
+
* Provider específico (DiscordProvider):
|
|
101
|
+
* - GET /api/auth/signin/discord - Iniciar OAuth Discord
|
|
102
|
+
* - GET /api/auth/callback/discord - Callback OAuth Discord
|
|
103
|
+
* - GET /api/auth/discord/config - Config do provider Discord
|
|
104
|
+
*/
|
package/dist/auth/index.d.ts
CHANGED
|
@@ -3,5 +3,5 @@ export * from './providers';
|
|
|
3
3
|
export * from './core';
|
|
4
4
|
export * from './routes';
|
|
5
5
|
export * from './jwt';
|
|
6
|
-
export { CredentialsProvider } from './providers';
|
|
6
|
+
export { CredentialsProvider, DiscordProvider } from './providers';
|
|
7
7
|
export { createAuthRoutes } from './routes';
|
package/dist/auth/index.js
CHANGED
|
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
14
14
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
-
exports.createAuthRoutes = exports.CredentialsProvider = void 0;
|
|
17
|
+
exports.createAuthRoutes = exports.DiscordProvider = exports.CredentialsProvider = void 0;
|
|
18
18
|
// Exportações principais do sistema de autenticação
|
|
19
19
|
__exportStar(require("./types"), exports);
|
|
20
20
|
__exportStar(require("./providers"), exports);
|
|
@@ -23,5 +23,6 @@ __exportStar(require("./routes"), exports);
|
|
|
23
23
|
__exportStar(require("./jwt"), exports);
|
|
24
24
|
var providers_1 = require("./providers");
|
|
25
25
|
Object.defineProperty(exports, "CredentialsProvider", { enumerable: true, get: function () { return providers_1.CredentialsProvider; } });
|
|
26
|
+
Object.defineProperty(exports, "DiscordProvider", { enumerable: true, get: function () { return providers_1.DiscordProvider; } });
|
|
26
27
|
var routes_1 = require("./routes");
|
|
27
28
|
Object.defineProperty(exports, "createAuthRoutes", { enumerable: true, get: function () { return routes_1.createAuthRoutes; } });
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import type { AuthProviderClass, User, AuthRoute } from '../types';
|
|
2
|
+
export interface CredentialsConfig {
|
|
3
|
+
id?: string;
|
|
4
|
+
name?: string;
|
|
5
|
+
credentials: Record<string, {
|
|
6
|
+
label: string;
|
|
7
|
+
type: string;
|
|
8
|
+
placeholder?: string;
|
|
9
|
+
}>;
|
|
10
|
+
authorize: (credentials: Record<string, string>) => Promise<User | null> | User | null;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Provider para autenticação com credenciais (email/senha)
|
|
14
|
+
*
|
|
15
|
+
* Este provider permite autenticação usando email/senha ou qualquer outro
|
|
16
|
+
* sistema de credenciais customizado. Você define a função authorize
|
|
17
|
+
* que será chamada para validar as credenciais.
|
|
18
|
+
*
|
|
19
|
+
* Exemplo de uso:
|
|
20
|
+
* ```typescript
|
|
21
|
+
* new CredentialsProvider({
|
|
22
|
+
* name: "Credentials",
|
|
23
|
+
* credentials: {
|
|
24
|
+
* email: { label: "Email", type: "email" },
|
|
25
|
+
* password: { label: "Password", type: "password" }
|
|
26
|
+
* },
|
|
27
|
+
* async authorize(credentials) {
|
|
28
|
+
* // Aqui você faz a validação com seu banco de dados
|
|
29
|
+
* const user = await validateUser(credentials.email, credentials.password);
|
|
30
|
+
* if (user) {
|
|
31
|
+
* return { id: user.id, name: user.name, email: user.email };
|
|
32
|
+
* }
|
|
33
|
+
* return null;
|
|
34
|
+
* }
|
|
35
|
+
* })
|
|
36
|
+
* ```
|
|
37
|
+
*/
|
|
38
|
+
export declare class CredentialsProvider implements AuthProviderClass {
|
|
39
|
+
readonly id: string;
|
|
40
|
+
readonly name: string;
|
|
41
|
+
readonly type: string;
|
|
42
|
+
private config;
|
|
43
|
+
constructor(config: CredentialsConfig);
|
|
44
|
+
/**
|
|
45
|
+
* Método principal para autenticar usuário com credenciais
|
|
46
|
+
*/
|
|
47
|
+
handleSignIn(credentials: Record<string, string>): Promise<User | null>;
|
|
48
|
+
/**
|
|
49
|
+
* Método opcional para logout (pode ser sobrescrito se necessário)
|
|
50
|
+
*/
|
|
51
|
+
handleSignOut?(): Promise<void>;
|
|
52
|
+
/**
|
|
53
|
+
* Rotas adicionais específicas do provider (opcional)
|
|
54
|
+
*/
|
|
55
|
+
additionalRoutes?: AuthRoute[];
|
|
56
|
+
/**
|
|
57
|
+
* Retorna configuração pública do provider
|
|
58
|
+
*/
|
|
59
|
+
getConfig(): any;
|
|
60
|
+
/**
|
|
61
|
+
* Valida se as credenciais fornecidas são válidas
|
|
62
|
+
*/
|
|
63
|
+
validateCredentials(credentials: Record<string, string>): boolean;
|
|
64
|
+
/**
|
|
65
|
+
* Validação simples de email
|
|
66
|
+
*/
|
|
67
|
+
private isValidEmail;
|
|
68
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.CredentialsProvider = void 0;
|
|
4
|
+
const http_1 = require("../../api/http");
|
|
5
|
+
/**
|
|
6
|
+
* Provider para autenticação com credenciais (email/senha)
|
|
7
|
+
*
|
|
8
|
+
* Este provider permite autenticação usando email/senha ou qualquer outro
|
|
9
|
+
* sistema de credenciais customizado. Você define a função authorize
|
|
10
|
+
* que será chamada para validar as credenciais.
|
|
11
|
+
*
|
|
12
|
+
* Exemplo de uso:
|
|
13
|
+
* ```typescript
|
|
14
|
+
* new CredentialsProvider({
|
|
15
|
+
* name: "Credentials",
|
|
16
|
+
* credentials: {
|
|
17
|
+
* email: { label: "Email", type: "email" },
|
|
18
|
+
* password: { label: "Password", type: "password" }
|
|
19
|
+
* },
|
|
20
|
+
* async authorize(credentials) {
|
|
21
|
+
* // Aqui você faz a validação com seu banco de dados
|
|
22
|
+
* const user = await validateUser(credentials.email, credentials.password);
|
|
23
|
+
* if (user) {
|
|
24
|
+
* return { id: user.id, name: user.name, email: user.email };
|
|
25
|
+
* }
|
|
26
|
+
* return null;
|
|
27
|
+
* }
|
|
28
|
+
* })
|
|
29
|
+
* ```
|
|
30
|
+
*/
|
|
31
|
+
class CredentialsProvider {
|
|
32
|
+
constructor(config) {
|
|
33
|
+
this.type = 'credentials';
|
|
34
|
+
/**
|
|
35
|
+
* Rotas adicionais específicas do provider (opcional)
|
|
36
|
+
*/
|
|
37
|
+
this.additionalRoutes = [
|
|
38
|
+
{
|
|
39
|
+
method: 'GET',
|
|
40
|
+
path: '/api/auth/credentials/config',
|
|
41
|
+
handler: async (req, params) => {
|
|
42
|
+
// Retorna configuração das credenciais (sem dados sensíveis)
|
|
43
|
+
const safeConfig = {
|
|
44
|
+
id: this.id,
|
|
45
|
+
name: this.name,
|
|
46
|
+
type: this.type,
|
|
47
|
+
credentials: Object.entries(this.config.credentials).reduce((acc, [key, field]) => {
|
|
48
|
+
acc[key] = {
|
|
49
|
+
label: field.label,
|
|
50
|
+
type: field.type,
|
|
51
|
+
placeholder: field.placeholder
|
|
52
|
+
};
|
|
53
|
+
return acc;
|
|
54
|
+
}, {})
|
|
55
|
+
};
|
|
56
|
+
return http_1.HightJSResponse.json({ config: safeConfig });
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
];
|
|
60
|
+
this.config = config;
|
|
61
|
+
this.id = config.id || 'credentials';
|
|
62
|
+
this.name = config.name || 'Credentials';
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Método principal para autenticar usuário com credenciais
|
|
66
|
+
*/
|
|
67
|
+
async handleSignIn(credentials) {
|
|
68
|
+
try {
|
|
69
|
+
if (!this.config.authorize) {
|
|
70
|
+
throw new Error('Authorize function not provided');
|
|
71
|
+
}
|
|
72
|
+
const user = await this.config.authorize(credentials);
|
|
73
|
+
if (!user) {
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
// Adiciona informações do provider ao usuário
|
|
77
|
+
return {
|
|
78
|
+
...user,
|
|
79
|
+
provider: this.id,
|
|
80
|
+
providerId: user.id || user.email || 'unknown'
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
console.error(`[${this.id} Provider] Error during sign in:`, error);
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Método opcional para logout (pode ser sobrescrito se necessário)
|
|
90
|
+
*/
|
|
91
|
+
async handleSignOut() {
|
|
92
|
+
// Credentials provider não precisa fazer nada específico no logout
|
|
93
|
+
// O core já cuida de limpar cookies e tokens
|
|
94
|
+
console.log(`[${this.id} Provider] User signed out`);
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Retorna configuração pública do provider
|
|
98
|
+
*/
|
|
99
|
+
getConfig() {
|
|
100
|
+
return {
|
|
101
|
+
id: this.id,
|
|
102
|
+
name: this.name,
|
|
103
|
+
type: this.type,
|
|
104
|
+
credentials: this.config.credentials
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Valida se as credenciais fornecidas são válidas
|
|
109
|
+
*/
|
|
110
|
+
validateCredentials(credentials) {
|
|
111
|
+
for (const [key, field] of Object.entries(this.config.credentials)) {
|
|
112
|
+
if (!credentials[key]) {
|
|
113
|
+
console.warn(`[${this.id} Provider] Missing required credential: ${key}`);
|
|
114
|
+
return false;
|
|
115
|
+
}
|
|
116
|
+
// Validações básicas por tipo
|
|
117
|
+
if (field.type === 'email' && !this.isValidEmail(credentials[key])) {
|
|
118
|
+
console.warn(`[${this.id} Provider] Invalid email format: ${credentials[key]}`);
|
|
119
|
+
return false;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return true;
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Validação simples de email
|
|
126
|
+
*/
|
|
127
|
+
isValidEmail(email) {
|
|
128
|
+
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
129
|
+
return emailRegex.test(email);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
exports.CredentialsProvider = CredentialsProvider;
|