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