@hightjs/auth 0.5.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.
@@ -0,0 +1,234 @@
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 'hightjs';
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
+ }
@@ -0,0 +1,20 @@
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
+
@@ -0,0 +1,20 @@
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';
@@ -0,0 +1,25 @@
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 { AuthGuard, GuestOnly } from '../components';
package/src/react.tsx ADDED
@@ -0,0 +1,234 @@
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 "hightjs/react";
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
+ }