hightjs 0.4.0 → 0.5.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/README.md +42 -126
- package/dist/bin/hightjs.js +51 -23
- package/dist/builder.js +139 -4
- package/dist/client/DefaultNotFound.d.ts +1 -1
- package/dist/client/DefaultNotFound.js +72 -46
- package/dist/client/client.d.ts +3 -0
- package/dist/{client.js → client/client.js} +4 -4
- package/dist/client/entry.client.js +39 -29
- package/dist/global/global.d.ts +117 -0
- package/dist/{auth/types.js → global/global.js} +0 -1
- package/dist/helpers.js +80 -2
- package/dist/hotReload.js +2 -2
- package/dist/index.js +16 -16
- package/dist/loaders.d.ts +1 -0
- package/dist/loaders.js +46 -0
- package/dist/renderer.js +158 -4
- package/dist/types.d.ts +44 -0
- package/package.json +37 -31
- package/src/bin/hightjs.js +59 -29
- package/src/builder.js +163 -4
- package/src/client/DefaultNotFound.tsx +88 -53
- package/src/{client.ts → client/client.ts} +4 -3
- package/src/client/entry.client.tsx +44 -29
- package/src/global/global.ts +171 -0
- package/src/helpers.ts +91 -2
- package/src/hotReload.ts +2 -2
- package/src/index.ts +2 -0
- package/src/loaders.js +53 -0
- package/src/renderer.tsx +162 -4
- package/src/types.ts +51 -0
- package/.idea/HightJS.iml +0 -9
- package/.idea/copilot.data.migration.agent.xml +0 -6
- package/.idea/copilot.data.migration.ask.xml +0 -6
- package/.idea/copilot.data.migration.ask2agent.xml +0 -6
- package/.idea/copilot.data.migration.edit.xml +0 -6
- package/.idea/copilotDiffState.xml +0 -67
- package/.idea/inspectionProfiles/Project_Default.xml +0 -13
- package/.idea/libraries/test_package.xml +0 -9
- package/.idea/libraries/ts_commonjs_default_export.xml +0 -9
- package/.idea/misc.xml +0 -7
- package/.idea/modules.xml +0 -8
- package/.idea/vcs.xml +0 -6
- package/dist/auth/client.d.ts +0 -24
- package/dist/auth/client.js +0 -146
- package/dist/auth/components.d.ts +0 -29
- package/dist/auth/components.js +0 -100
- package/dist/auth/core.d.ts +0 -55
- package/dist/auth/core.js +0 -189
- package/dist/auth/index.d.ts +0 -7
- package/dist/auth/index.js +0 -45
- package/dist/auth/jwt.d.ts +0 -41
- package/dist/auth/jwt.js +0 -185
- package/dist/auth/providers/credentials.d.ts +0 -60
- package/dist/auth/providers/credentials.js +0 -97
- package/dist/auth/providers/discord.d.ts +0 -63
- package/dist/auth/providers/discord.js +0 -190
- package/dist/auth/providers/google.d.ts +0 -63
- package/dist/auth/providers/google.js +0 -186
- package/dist/auth/providers/index.d.ts +0 -2
- package/dist/auth/providers/index.js +0 -35
- package/dist/auth/providers.d.ts +0 -3
- package/dist/auth/providers.js +0 -26
- package/dist/auth/react/index.d.ts +0 -6
- package/dist/auth/react/index.js +0 -48
- package/dist/auth/react.d.ts +0 -22
- package/dist/auth/react.js +0 -199
- package/dist/auth/routes.d.ts +0 -16
- package/dist/auth/routes.js +0 -152
- package/dist/auth/types.d.ts +0 -76
- package/dist/client.d.ts +0 -3
- package/docs/README.md +0 -58
- package/docs/arquivos-especiais.md +0 -10
- package/docs/autenticacao.md +0 -212
- package/docs/checklist.md +0 -9
- package/docs/cli.md +0 -72
- package/docs/config.md +0 -216
- package/docs/estrutura.md +0 -20
- package/docs/faq.md +0 -10
- package/docs/hot-reload.md +0 -5
- package/docs/integracoes.md +0 -240
- package/docs/middlewares.md +0 -73
- package/docs/rotas-backend.md +0 -45
- package/docs/rotas-frontend.md +0 -66
- package/docs/seguranca.md +0 -8
- package/docs/websocket.md +0 -45
- package/example/certs/cert.pem +0 -20
- package/example/certs/key.pem +0 -27
- package/example/hightjs.config.ts +0 -87
- package/example/package-lock.json +0 -1174
- package/example/package.json +0 -26
- package/example/postcss.config.js +0 -8
- package/example/src/backend/auth.ts +0 -42
- package/example/src/backend/routes/auth.ts +0 -3
- package/example/src/backend/routes/version.ts +0 -13
- package/example/src/web/components/Home.tsx +0 -140
- package/example/src/web/components/LoginPage.tsx +0 -149
- package/example/src/web/globals.css +0 -5
- package/example/src/web/layout.tsx +0 -100
- package/example/src/web/routes/index.tsx +0 -13
- package/example/src/web/routes/login.tsx +0 -30
- package/example/tailwind.config.js +0 -12
- package/example/tsconfig.json +0 -15
- package/src/auth/client.ts +0 -171
- package/src/auth/components.tsx +0 -125
- package/src/auth/core.ts +0 -215
- package/src/auth/index.ts +0 -25
- package/src/auth/jwt.ts +0 -210
- package/src/auth/providers/credentials.ts +0 -139
- package/src/auth/providers/discord.ts +0 -239
- package/src/auth/providers/google.ts +0 -234
- package/src/auth/providers/index.ts +0 -20
- package/src/auth/providers.ts +0 -20
- package/src/auth/react/index.ts +0 -25
- package/src/auth/react.tsx +0 -234
- package/src/auth/routes.ts +0 -183
- package/src/auth/types.ts +0 -108
- package/tsconfig.json +0 -17
|
@@ -1,234 +0,0 @@
|
|
|
1
|
-
/*
|
|
2
|
-
* This file is part of the HightJS Project.
|
|
3
|
-
* Copyright (c) 2025 itsmuzin
|
|
4
|
-
*
|
|
5
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
-
* you may not use this file except in compliance with the License.
|
|
7
|
-
* You may obtain a copy of the License at
|
|
8
|
-
*
|
|
9
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
-
*
|
|
11
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
-
* See the License for the specific language governing permissions and
|
|
15
|
-
* limitations under the License.
|
|
16
|
-
*/
|
|
17
|
-
import type {AuthProviderClass, AuthRoute, User} from '../types';
|
|
18
|
-
import {HightJSRequest, HightJSResponse} from '../../api/http';
|
|
19
|
-
|
|
20
|
-
export interface GoogleConfig {
|
|
21
|
-
id?: string;
|
|
22
|
-
name?: string;
|
|
23
|
-
clientId: string;
|
|
24
|
-
clientSecret: string;
|
|
25
|
-
callbackUrl?: string;
|
|
26
|
-
successUrl?: string;
|
|
27
|
-
// Escopos OAuth do Google, padrão: ['openid', 'email', 'profile']
|
|
28
|
-
scope?: string[];
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
* Provider para autenticação com Google OAuth2
|
|
33
|
-
*
|
|
34
|
-
* Este provider permite autenticação usando Google OAuth2.
|
|
35
|
-
* Automaticamente gerencia o fluxo OAuth completo e rotas necessárias.
|
|
36
|
-
*
|
|
37
|
-
* Exemplo de uso:
|
|
38
|
-
* ```typescript
|
|
39
|
-
* new GoogleProvider({
|
|
40
|
-
* clientId: process.env.GOOGLE_CLIENT_ID!,
|
|
41
|
-
* clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
|
|
42
|
-
* callbackUrl: "http://localhost:3000/api/auth/callback/google"
|
|
43
|
-
* })
|
|
44
|
-
* ```
|
|
45
|
-
*
|
|
46
|
-
* Fluxo de autenticação:
|
|
47
|
-
* 1. GET /api/auth/signin/google - Gera URL e redireciona para Google
|
|
48
|
-
* 2. Google redireciona para /api/auth/callback/google com código
|
|
49
|
-
* 3. Provider troca código por token e busca dados do usuário
|
|
50
|
-
* 4. Retorna objeto User com dados do Google
|
|
51
|
-
*/
|
|
52
|
-
export class GoogleProvider implements AuthProviderClass {
|
|
53
|
-
public readonly id: string;
|
|
54
|
-
public readonly name: string;
|
|
55
|
-
public readonly type: string = 'google';
|
|
56
|
-
|
|
57
|
-
private config: GoogleConfig;
|
|
58
|
-
private readonly defaultScope = [
|
|
59
|
-
'openid',
|
|
60
|
-
'https://www.googleapis.com/auth/userinfo.email',
|
|
61
|
-
'https://www.googleapis.com/auth/userinfo.profile'
|
|
62
|
-
];
|
|
63
|
-
|
|
64
|
-
constructor(config: GoogleConfig) {
|
|
65
|
-
this.config = config;
|
|
66
|
-
this.id = config.id || 'google';
|
|
67
|
-
this.name = config.name || 'Google';
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
/**
|
|
71
|
-
* Método para gerar URL OAuth (usado pelo handleSignIn)
|
|
72
|
-
*/
|
|
73
|
-
handleOauth(credentials: Record<string, string> = {}): string {
|
|
74
|
-
return this.getAuthorizationUrl();
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
/**
|
|
78
|
-
* Método principal - redireciona para OAuth ou processa o callback
|
|
79
|
-
*/
|
|
80
|
-
async handleSignIn(credentials: Record<string, string>): Promise<User | string | null> {
|
|
81
|
-
// Se tem código, é o callback - processa a autenticação
|
|
82
|
-
if (credentials.code) {
|
|
83
|
-
return await this.processOAuthCallback(credentials);
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
// Se não tem código, é o início do OAuth - retorna a URL
|
|
87
|
-
return this.handleOauth(credentials);
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
/**
|
|
91
|
-
* Processa o callback do OAuth (troca o código pelo usuário)
|
|
92
|
-
*/
|
|
93
|
-
private async processOAuthCallback(credentials: Record<string, string>): Promise<User | null> {
|
|
94
|
-
try {
|
|
95
|
-
const { code } = credentials;
|
|
96
|
-
if (!code) {
|
|
97
|
-
throw new Error('Authorization code not provided');
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
// Troca o código por um access token
|
|
101
|
-
const tokenResponse = await fetch('https://oauth2.googleapis.com/token', {
|
|
102
|
-
method: 'POST',
|
|
103
|
-
headers: {
|
|
104
|
-
'Content-Type': 'application/x-www-form-urlencoded',
|
|
105
|
-
},
|
|
106
|
-
body: new URLSearchParams({
|
|
107
|
-
client_id: this.config.clientId,
|
|
108
|
-
client_secret: this.config.clientSecret,
|
|
109
|
-
grant_type: 'authorization_code',
|
|
110
|
-
code,
|
|
111
|
-
redirect_uri: this.config.callbackUrl || '',
|
|
112
|
-
}),
|
|
113
|
-
});
|
|
114
|
-
|
|
115
|
-
if (!tokenResponse.ok) {
|
|
116
|
-
const error = await tokenResponse.text();
|
|
117
|
-
throw new Error(`Failed to exchange code for token: ${error}`);
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
const tokens = await tokenResponse.json();
|
|
121
|
-
|
|
122
|
-
// Busca os dados do usuário com o access token
|
|
123
|
-
const userResponse = await fetch('https://www.googleapis.com/oauth2/v2/userinfo', {
|
|
124
|
-
headers: {
|
|
125
|
-
'Authorization': `Bearer ${tokens.access_token}`,
|
|
126
|
-
},
|
|
127
|
-
});
|
|
128
|
-
|
|
129
|
-
if (!userResponse.ok) {
|
|
130
|
-
throw new Error('Failed to fetch user data');
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
const googleUser = await userResponse.json();
|
|
134
|
-
|
|
135
|
-
// Retorna o objeto User padronizado
|
|
136
|
-
return {
|
|
137
|
-
id: googleUser.id,
|
|
138
|
-
name: googleUser.name,
|
|
139
|
-
email: googleUser.email,
|
|
140
|
-
image: googleUser.picture || null,
|
|
141
|
-
provider: this.id,
|
|
142
|
-
providerId: googleUser.id,
|
|
143
|
-
accessToken: tokens.access_token,
|
|
144
|
-
refreshToken: tokens.refresh_token
|
|
145
|
-
};
|
|
146
|
-
|
|
147
|
-
} catch (error) {
|
|
148
|
-
console.error(`[${this.id} Provider] Error during OAuth callback:`, error);
|
|
149
|
-
return null;
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
/**
|
|
154
|
-
* Rotas adicionais específicas do Google OAuth
|
|
155
|
-
*/
|
|
156
|
-
public additionalRoutes: AuthRoute[] = [
|
|
157
|
-
// Rota de callback do Google
|
|
158
|
-
{
|
|
159
|
-
method: 'GET',
|
|
160
|
-
path: '/api/auth/callback/google',
|
|
161
|
-
handler: async (req: HightJSRequest, params: any) => {
|
|
162
|
-
const url = new URL(req.url || '', 'http://localhost');
|
|
163
|
-
const code = url.searchParams.get('code');
|
|
164
|
-
|
|
165
|
-
if (!code) {
|
|
166
|
-
return HightJSResponse.json({ error: 'Authorization code not provided' }, { status: 400 });
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
try {
|
|
170
|
-
// Delega o 'code' para o endpoint de signin principal
|
|
171
|
-
const authResponse = await fetch(`${req.headers.origin || 'http://localhost:3000'}/api/auth/signin`, {
|
|
172
|
-
method: 'POST',
|
|
173
|
-
headers: {
|
|
174
|
-
'Content-Type': 'application/json',
|
|
175
|
-
},
|
|
176
|
-
body: JSON.stringify({
|
|
177
|
-
provider: this.id,
|
|
178
|
-
code,
|
|
179
|
-
})
|
|
180
|
-
});
|
|
181
|
-
|
|
182
|
-
if (authResponse.ok) {
|
|
183
|
-
// Propaga o cookie de sessão e redireciona para a URL de sucesso
|
|
184
|
-
const setCookieHeader = authResponse.headers.get('set-cookie');
|
|
185
|
-
|
|
186
|
-
if(this.config.successUrl) {
|
|
187
|
-
return HightJSResponse
|
|
188
|
-
.redirect(this.config.successUrl)
|
|
189
|
-
.header('Set-Cookie', setCookieHeader || '');
|
|
190
|
-
}
|
|
191
|
-
return HightJSResponse.json({ success: true })
|
|
192
|
-
.header('Set-Cookie', setCookieHeader || '');
|
|
193
|
-
} else {
|
|
194
|
-
const errorText = await authResponse.text();
|
|
195
|
-
console.error(`[${this.id} Provider] Session creation failed during callback. Status: ${authResponse.status}, Body: ${errorText}`);
|
|
196
|
-
return HightJSResponse.json({ error: 'Session creation failed' }, { status: 500 });
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
} catch (error) {
|
|
200
|
-
console.error(`[${this.id} Provider] Callback handler fetch error:`, error);
|
|
201
|
-
return HightJSResponse.json({ error: 'Internal server error' }, { status: 500 });
|
|
202
|
-
}
|
|
203
|
-
}
|
|
204
|
-
}
|
|
205
|
-
];
|
|
206
|
-
|
|
207
|
-
/**
|
|
208
|
-
* Gera a URL de autorização do Google
|
|
209
|
-
*/
|
|
210
|
-
getAuthorizationUrl(): string {
|
|
211
|
-
const params = new URLSearchParams({
|
|
212
|
-
client_id: this.config.clientId,
|
|
213
|
-
redirect_uri: this.config.callbackUrl || '',
|
|
214
|
-
response_type: 'code',
|
|
215
|
-
scope: (this.config.scope || this.defaultScope).join(' ')
|
|
216
|
-
});
|
|
217
|
-
|
|
218
|
-
return `https://accounts.google.com/o/oauth2/v2/auth?${params.toString()}`;
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
/**
|
|
222
|
-
* Retorna a configuração pública do provider
|
|
223
|
-
*/
|
|
224
|
-
getConfig(): any {
|
|
225
|
-
return {
|
|
226
|
-
id: this.id,
|
|
227
|
-
name: this.name,
|
|
228
|
-
type: this.type,
|
|
229
|
-
clientId: this.config.clientId, // Público
|
|
230
|
-
scope: this.config.scope || this.defaultScope,
|
|
231
|
-
callbackUrl: this.config.callbackUrl
|
|
232
|
-
};
|
|
233
|
-
}
|
|
234
|
-
}
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
/*
|
|
2
|
-
* This file is part of the HightJS Project.
|
|
3
|
-
* Copyright (c) 2025 itsmuzin
|
|
4
|
-
*
|
|
5
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
-
* you may not use this file except in compliance with the License.
|
|
7
|
-
* You may obtain a copy of the License at
|
|
8
|
-
*
|
|
9
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
-
*
|
|
11
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
-
* See the License for the specific language governing permissions and
|
|
15
|
-
* limitations under the License.
|
|
16
|
-
*/
|
|
17
|
-
// Exportações dos providers
|
|
18
|
-
export * from './credentials';
|
|
19
|
-
export * from './discord';
|
|
20
|
-
|
package/src/auth/providers.ts
DELETED
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
/*
|
|
2
|
-
* This file is part of the HightJS Project.
|
|
3
|
-
* Copyright (c) 2025 itsmuzin
|
|
4
|
-
*
|
|
5
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
-
* you may not use this file except in compliance with the License.
|
|
7
|
-
* You may obtain a copy of the License at
|
|
8
|
-
*
|
|
9
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
-
*
|
|
11
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
-
* See the License for the specific language governing permissions and
|
|
15
|
-
* limitations under the License.
|
|
16
|
-
*/
|
|
17
|
-
// Exportações dos providers
|
|
18
|
-
export { CredentialsProvider } from './providers/credentials';
|
|
19
|
-
export { DiscordProvider } from './providers/discord';
|
|
20
|
-
export { GoogleProvider } from './providers/google';
|
package/src/auth/react/index.ts
DELETED
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
/*
|
|
2
|
-
* This file is part of the HightJS Project.
|
|
3
|
-
* Copyright (c) 2025 itsmuzin
|
|
4
|
-
*
|
|
5
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
-
* you may not use this file except in compliance with the License.
|
|
7
|
-
* You may obtain a copy of the License at
|
|
8
|
-
*
|
|
9
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
-
*
|
|
11
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
-
* See the License for the specific language governing permissions and
|
|
15
|
-
* limitations under the License.
|
|
16
|
-
*/
|
|
17
|
-
// Exportações do frontend
|
|
18
|
-
export * from '../react';
|
|
19
|
-
export * from '../client';
|
|
20
|
-
export * from '../components';
|
|
21
|
-
|
|
22
|
-
// Re-exports das funções mais usadas para conveniência
|
|
23
|
-
export { getSession } from '../client';
|
|
24
|
-
export { useSession, useAuth, SessionProvider } from '../react';
|
|
25
|
-
export { ProtectedRoute, AuthGuard, GuestOnly } from '../components';
|
package/src/auth/react.tsx
DELETED
|
@@ -1,234 +0,0 @@
|
|
|
1
|
-
/*
|
|
2
|
-
* This file is part of the HightJS Project.
|
|
3
|
-
* Copyright (c) 2025 itsmuzin
|
|
4
|
-
*
|
|
5
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
-
* you may not use this file except in compliance with the License.
|
|
7
|
-
* You may obtain a copy of the License at
|
|
8
|
-
*
|
|
9
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
-
*
|
|
11
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
-
* See the License for the specific language governing permissions and
|
|
15
|
-
* limitations under the License.
|
|
16
|
-
*/
|
|
17
|
-
import React, { createContext, useContext, useEffect, useState, useCallback, ReactNode } from 'react';
|
|
18
|
-
import type { Session, SessionContextType, SignInOptions, SignInResult, User } from './types';
|
|
19
|
-
import { router } from "../client/clientRouter";
|
|
20
|
-
|
|
21
|
-
const SessionContext = createContext<SessionContextType | undefined>(undefined);
|
|
22
|
-
|
|
23
|
-
interface SessionProviderProps {
|
|
24
|
-
children: ReactNode;
|
|
25
|
-
basePath?: string;
|
|
26
|
-
refetchInterval?: number;
|
|
27
|
-
refetchOnWindowFocus?: boolean;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
export function SessionProvider({
|
|
31
|
-
children,
|
|
32
|
-
basePath = '/api/auth',
|
|
33
|
-
refetchInterval = 0,
|
|
34
|
-
refetchOnWindowFocus = true
|
|
35
|
-
}: SessionProviderProps) {
|
|
36
|
-
const [session, setSession] = useState<Session | null>(null);
|
|
37
|
-
const [status, setStatus] = useState<'loading' | 'authenticated' | 'unauthenticated'>('loading');
|
|
38
|
-
|
|
39
|
-
// Fetch da sessão atual
|
|
40
|
-
const fetchSession = useCallback(async (): Promise<Session | null> => {
|
|
41
|
-
try {
|
|
42
|
-
const response = await fetch(`${basePath}/session`, {
|
|
43
|
-
credentials: 'include'
|
|
44
|
-
});
|
|
45
|
-
|
|
46
|
-
if (!response.ok) {
|
|
47
|
-
setStatus('unauthenticated');
|
|
48
|
-
return null;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
const data = await response.json();
|
|
52
|
-
const sessionData = data.session;
|
|
53
|
-
|
|
54
|
-
if (sessionData) {
|
|
55
|
-
setSession(sessionData);
|
|
56
|
-
setStatus('authenticated');
|
|
57
|
-
return sessionData;
|
|
58
|
-
} else {
|
|
59
|
-
setSession(null);
|
|
60
|
-
setStatus('unauthenticated');
|
|
61
|
-
return null;
|
|
62
|
-
}
|
|
63
|
-
} catch (error) {
|
|
64
|
-
console.error('[hweb-auth] Error fetching session:', error);
|
|
65
|
-
setSession(null);
|
|
66
|
-
setStatus('unauthenticated');
|
|
67
|
-
return null;
|
|
68
|
-
}
|
|
69
|
-
}, [basePath]);
|
|
70
|
-
|
|
71
|
-
// SignIn function
|
|
72
|
-
const signIn = useCallback(async (
|
|
73
|
-
provider: string = 'credentials',
|
|
74
|
-
options: SignInOptions = {}
|
|
75
|
-
): Promise<SignInResult | undefined> => {
|
|
76
|
-
try {
|
|
77
|
-
const { redirect = true, callbackUrl, ...credentials } = options;
|
|
78
|
-
|
|
79
|
-
const response = await fetch(`${basePath}/signin`, {
|
|
80
|
-
method: 'POST',
|
|
81
|
-
headers: {
|
|
82
|
-
'Content-Type': 'application/json',
|
|
83
|
-
},
|
|
84
|
-
credentials: 'include',
|
|
85
|
-
body: JSON.stringify({
|
|
86
|
-
provider,
|
|
87
|
-
...credentials
|
|
88
|
-
})
|
|
89
|
-
});
|
|
90
|
-
|
|
91
|
-
const data = await response.json();
|
|
92
|
-
|
|
93
|
-
if (response.ok && data.success) {
|
|
94
|
-
await fetchSession();
|
|
95
|
-
// Se é OAuth, redireciona para URL fornecida
|
|
96
|
-
if (data.type === 'oauth' && data.redirectUrl) {
|
|
97
|
-
if (redirect && typeof window !== 'undefined') {
|
|
98
|
-
window.location.href = data.redirectUrl;
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
return {
|
|
102
|
-
ok: true,
|
|
103
|
-
status: 200,
|
|
104
|
-
url: data.redirectUrl
|
|
105
|
-
};
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
// Se é sessão (credentials), redireciona para callbackUrl
|
|
109
|
-
if (data.type === 'session') {
|
|
110
|
-
if (redirect && typeof window !== 'undefined') {
|
|
111
|
-
window.location.href = callbackUrl || '/';
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
return {
|
|
115
|
-
ok: true,
|
|
116
|
-
status: 200,
|
|
117
|
-
url: callbackUrl || '/'
|
|
118
|
-
};
|
|
119
|
-
}
|
|
120
|
-
} else {
|
|
121
|
-
return {
|
|
122
|
-
error: data.error || 'Authentication failed',
|
|
123
|
-
status: response.status,
|
|
124
|
-
ok: false
|
|
125
|
-
};
|
|
126
|
-
}
|
|
127
|
-
} catch (error) {
|
|
128
|
-
console.error('[hweb-auth] Error on signIn:', error);
|
|
129
|
-
return {
|
|
130
|
-
error: 'Network error',
|
|
131
|
-
status: 500,
|
|
132
|
-
ok: false
|
|
133
|
-
};
|
|
134
|
-
}
|
|
135
|
-
}, [basePath, fetchSession]);
|
|
136
|
-
|
|
137
|
-
// SignOut function
|
|
138
|
-
const signOut = useCallback(async (options: { callbackUrl?: string } = {}): Promise<void> => {
|
|
139
|
-
try {
|
|
140
|
-
await fetch(`${basePath}/signout`, {
|
|
141
|
-
method: 'POST',
|
|
142
|
-
credentials: 'include'
|
|
143
|
-
});
|
|
144
|
-
|
|
145
|
-
setSession(null);
|
|
146
|
-
setStatus('unauthenticated');
|
|
147
|
-
|
|
148
|
-
if (typeof window !== 'undefined') {
|
|
149
|
-
try {
|
|
150
|
-
router.push(options.callbackUrl || '/');
|
|
151
|
-
} catch (e) {
|
|
152
|
-
window.location.href = options.callbackUrl || '/';
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
} catch (error) {
|
|
156
|
-
console.error('[hweb-auth] Error on signOut:', error);
|
|
157
|
-
}
|
|
158
|
-
}, [basePath]);
|
|
159
|
-
|
|
160
|
-
// Update session
|
|
161
|
-
const update = useCallback(async (): Promise<Session | null> => {
|
|
162
|
-
return await fetchSession();
|
|
163
|
-
}, [fetchSession]);
|
|
164
|
-
|
|
165
|
-
// Initial session fetch
|
|
166
|
-
useEffect(() => {
|
|
167
|
-
fetchSession();
|
|
168
|
-
}, [fetchSession]);
|
|
169
|
-
|
|
170
|
-
// Refetch interval
|
|
171
|
-
useEffect(() => {
|
|
172
|
-
if (refetchInterval > 0) {
|
|
173
|
-
const interval = setInterval(() => {
|
|
174
|
-
if (status === 'authenticated') {
|
|
175
|
-
fetchSession();
|
|
176
|
-
}
|
|
177
|
-
}, refetchInterval * 1000);
|
|
178
|
-
|
|
179
|
-
return () => clearInterval(interval);
|
|
180
|
-
}
|
|
181
|
-
}, [refetchInterval, status, fetchSession]);
|
|
182
|
-
|
|
183
|
-
// Refetch on window focus
|
|
184
|
-
useEffect(() => {
|
|
185
|
-
if (refetchOnWindowFocus) {
|
|
186
|
-
const handleFocus = () => {
|
|
187
|
-
if (status === 'authenticated') {
|
|
188
|
-
fetchSession();
|
|
189
|
-
}
|
|
190
|
-
};
|
|
191
|
-
|
|
192
|
-
window.addEventListener('focus', handleFocus);
|
|
193
|
-
return () => window.removeEventListener('focus', handleFocus);
|
|
194
|
-
}
|
|
195
|
-
}, [refetchOnWindowFocus, status, fetchSession]);
|
|
196
|
-
|
|
197
|
-
const value: SessionContextType = {
|
|
198
|
-
data: session,
|
|
199
|
-
status,
|
|
200
|
-
signIn,
|
|
201
|
-
signOut,
|
|
202
|
-
update
|
|
203
|
-
};
|
|
204
|
-
|
|
205
|
-
return (
|
|
206
|
-
<SessionContext.Provider value={value}>
|
|
207
|
-
{children}
|
|
208
|
-
</SessionContext.Provider>
|
|
209
|
-
);
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
/**
|
|
213
|
-
* Hook para acessar a sessão atual
|
|
214
|
-
*/
|
|
215
|
-
export function useSession(): SessionContextType {
|
|
216
|
-
const context = useContext(SessionContext);
|
|
217
|
-
if (context === undefined) {
|
|
218
|
-
throw new Error('useSession must be used inside a SessionProvider');
|
|
219
|
-
}
|
|
220
|
-
return context;
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
/**
|
|
224
|
-
* Hook para verificar se o usuário está autenticado
|
|
225
|
-
*/
|
|
226
|
-
export function useAuth(): { user: User | null; isAuthenticated: boolean; isLoading: boolean } {
|
|
227
|
-
const { data: session, status } = useSession();
|
|
228
|
-
|
|
229
|
-
return {
|
|
230
|
-
user: session?.user || null,
|
|
231
|
-
isAuthenticated: status === 'authenticated',
|
|
232
|
-
isLoading: status === 'loading'
|
|
233
|
-
};
|
|
234
|
-
}
|