Skip to content

Commit 7409f34

Browse files
authored
Merge pull request #1536 from w3bdesign/login
Login
2 parents 7f7c1b8 + 2c4b3b2 commit 7409f34

File tree

4 files changed

+85
-19
lines changed

4 files changed

+85
-19
lines changed

src/components/User/withAuth.component.tsx

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,42 @@
11
import { useRouter } from 'next/router';
2-
import { useEffect, ComponentType } from 'react';
3-
import { hasCredentials } from '../../utils/auth';
2+
import { useEffect, ComponentType, useState } from 'react';
3+
import { useQuery } from '@apollo/client';
4+
import { GET_CURRENT_USER } from '../../utils/gql/GQL_QUERIES';
5+
import LoadingSpinner from '../LoadingSpinner/LoadingSpinner.component';
46

57
const withAuth = <P extends object>(WrappedComponent: ComponentType<P>) => {
68
const Wrapper = (props: P) => {
79
const router = useRouter();
10+
const [isChecking, setIsChecking] = useState(true);
11+
12+
const { data, loading, error } = useQuery(GET_CURRENT_USER, {
13+
errorPolicy: 'all',
14+
fetchPolicy: 'cache-and-network',
15+
});
816

917
useEffect(() => {
10-
if (!hasCredentials()) {
11-
router.push('/logg-inn');
18+
if (!loading) {
19+
setIsChecking(false);
20+
21+
// If there's an error or no customer data, user is not authenticated
22+
if (error || !data?.customer) {
23+
router.push('/logg-inn');
24+
}
1225
}
13-
}, [router]);
26+
}, [data, loading, error, router]);
1427

15-
if (!hasCredentials()) {
16-
return null; // or a loading spinner
28+
// Show loading while checking authentication
29+
if (loading || isChecking) {
30+
return (
31+
<div className="flex justify-center items-center min-h-screen">
32+
<LoadingSpinner />
33+
</div>
34+
);
35+
}
36+
37+
// If no customer data, don't render the component
38+
if (!data?.customer) {
39+
return null;
1740
}
1841

1942
return <WrappedComponent {...props} />;

src/utils/apollo/ApolloClient.js

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ import {
66
createHttpLink,
77
ApolloLink,
88
} from '@apollo/client';
9-
import { getAuthToken } from '../auth';
109

1110
const SEVEN_DAYS = 7 * 24 * 60 * 60 * 1000; // 7 days in milliseconds
1211

@@ -39,12 +38,8 @@ export const middleware = new ApolloLink(async (operation, forward) => {
3938
}
4039
}
4140

42-
if (process.browser) {
43-
const authToken = await getAuthToken();
44-
if (authToken) {
45-
headers.Authorization = `Bearer ${authToken}`;
46-
}
47-
}
41+
// Cookie-based authentication - no JWT tokens needed
42+
// Cookies are automatically included with credentials: 'include'
4843

4944
operation.setContext({
5045
headers,
@@ -97,6 +92,7 @@ const client = new ApolloClient({
9792
createHttpLink({
9893
uri: process.env.NEXT_PUBLIC_GRAPHQL_URL,
9994
fetch,
95+
credentials: 'include', // Include cookies for authentication
10096
}),
10197
),
10298
),

src/utils/auth.ts

Lines changed: 41 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,44 @@ export async function getAuthToken() {
1717
return null;
1818
}
1919

20+
function getErrorMessage(error: any): string {
21+
// Check for GraphQL errors
22+
if (error.graphQLErrors && error.graphQLErrors.length > 0) {
23+
const graphQLError = error.graphQLErrors[0];
24+
const message = graphQLError.message;
25+
26+
// Map GraphQL error messages to user-friendly messages
27+
switch (message) {
28+
case 'invalid_username':
29+
return 'Ugyldig brukernavn eller e-postadresse. Vennligst sjekk og prøv igjen.';
30+
case 'incorrect_password':
31+
return 'Feil passord. Vennligst sjekk passordet ditt og prøv igjen.';
32+
case 'invalid_email':
33+
return 'Ugyldig e-postadresse. Vennligst skriv inn en gyldig e-postadresse.';
34+
case 'empty_username':
35+
return 'Vennligst skriv inn brukernavn eller e-postadresse.';
36+
case 'empty_password':
37+
return 'Vennligst skriv inn passord.';
38+
case 'too_many_retries':
39+
return 'For mange mislykkede forsøk. Vennligst vent litt før du prøver igjen.';
40+
default:
41+
return 'Innlogging mislyktes. Vennligst sjekk dine opplysninger og prøv igjen.';
42+
}
43+
}
44+
45+
// Check for network errors
46+
if (error.networkError) {
47+
return 'Nettverksfeil. Vennligst sjekk internetttilkoblingen din og prøv igjen.';
48+
}
49+
50+
// Fallback for other errors
51+
if (error.message) {
52+
return 'Det oppstod en feil under innlogging. Vennligst prøv igjen.';
53+
}
54+
55+
return 'En ukjent feil oppstod. Vennligst prøv igjen senere.';
56+
}
57+
2058
export async function login(username: string, password: string) {
2159
try {
2260
const client = new ApolloClient({
@@ -33,16 +71,14 @@ export async function login(username: string, password: string) {
3371
const loginResult = data.loginWithCookies;
3472

3573
if (loginResult.status !== 'SUCCESS') {
36-
throw new Error('Login failed');
74+
throw new Error('Innlogging mislyktes. Vennligst sjekk dine opplysninger og prøv igjen.');
3775
}
3876

3977
// On successful login, cookies are automatically set by the server
4078
return { success: true, status: loginResult.status };
4179
} catch (error: unknown) {
42-
if (error instanceof Error) {
43-
throw new Error(error.message);
44-
}
45-
throw new Error('An unknown error occurred during login.');
80+
const userFriendlyMessage = getErrorMessage(error);
81+
throw new Error(userFriendlyMessage);
4682
}
4783
}
4884

src/utils/gql/GQL_QUERIES.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -325,6 +325,17 @@ export const GET_CART = gql`
325325
}
326326
`;
327327

328+
export const GET_CURRENT_USER = gql`
329+
query GET_CURRENT_USER {
330+
customer {
331+
id
332+
firstName
333+
lastName
334+
email
335+
}
336+
}
337+
`;
338+
328339
export const GET_CUSTOMER_ORDERS = gql`
329340
query GET_CUSTOMER_ORDERS {
330341
customer {

0 commit comments

Comments
 (0)