Skip to content

Commit 245d2a1

Browse files
committed
Login
1 parent ca7630c commit 245d2a1

File tree

2 files changed

+26
-116
lines changed

2 files changed

+26
-116
lines changed

src/utils/auth.ts

Lines changed: 23 additions & 105 deletions
Original file line numberDiff line numberDiff line change
@@ -1,138 +1,56 @@
11
import { ApolloClient, InMemoryCache } from '@apollo/client';
2-
import { LOGIN_USER, REFRESH_AUTH_TOKEN } from './gql/GQL_MUTATIONS';
3-
4-
let tokenSetter: ReturnType<typeof setInterval>;
2+
import { LOGIN_USER } from './gql/GQL_MUTATIONS';
53

4+
// Cookie-based authentication - no token storage needed
65
export function hasCredentials() {
76
if (typeof window === 'undefined') {
87
return false; // Server-side, no credentials available
98
}
10-
11-
const authToken = sessionStorage.getItem(
12-
process.env.NEXT_PUBLIC_AUTH_TOKEN_SS_KEY as string
13-
);
14-
const refreshToken = localStorage.getItem(
15-
process.env.NEXT_PUBLIC_REFRESH_TOKEN_LS_KEY as string
16-
);
17-
18-
if (!!authToken && !!refreshToken) {
19-
return true;
20-
}
21-
9+
10+
// With cookie-based auth, we'll check if user is logged in through a query
11+
// For now, we'll return false and let components handle the check
2212
return false;
2313
}
2414

2515
export async function getAuthToken() {
26-
let authToken = sessionStorage.getItem(
27-
process.env.NEXT_PUBLIC_AUTH_TOKEN_SS_KEY as string,
28-
);
29-
if (!authToken || !tokenSetter) {
30-
authToken = await fetchAuthToken();
31-
}
32-
return authToken;
33-
}
34-
35-
async function fetchAuthToken() {
36-
const refreshToken = localStorage.getItem(
37-
process.env.NEXT_PUBLIC_REFRESH_TOKEN_LS_KEY as string,
38-
);
39-
if (!refreshToken) {
40-
// No refresh token means the user is not authenticated.
41-
return;
42-
}
43-
44-
try {
45-
const client = new ApolloClient({
46-
uri: process.env.NEXT_PUBLIC_GRAPHQL_URL,
47-
cache: new InMemoryCache(),
48-
});
49-
50-
const { data } = await client.mutate({
51-
mutation: REFRESH_AUTH_TOKEN,
52-
variables: { refreshToken },
53-
});
54-
55-
const authToken = data?.refreshJwtAuthToken?.authToken;
56-
if (!authToken) {
57-
throw new Error('Failed to retrieve a new auth token');
58-
}
59-
// Save token.
60-
sessionStorage.setItem(
61-
process.env.NEXT_PUBLIC_AUTH_TOKEN_SS_KEY as string,
62-
authToken,
63-
);
64-
if (tokenSetter) {
65-
clearInterval(tokenSetter);
66-
}
67-
tokenSetter = setInterval(
68-
async () => {
69-
if (!hasCredentials()) {
70-
clearInterval(tokenSetter);
71-
return;
72-
}
73-
fetchAuthToken();
74-
},
75-
Number(process.env.NEXT_PUBLIC_AUTH_KEY_TIMEOUT || 300000),
76-
);
77-
78-
return authToken;
79-
} catch (err) {
80-
console.error(err);
81-
}
82-
}
83-
84-
function saveCredentials(
85-
authToken: string,
86-
sessionToken: string,
87-
refreshToken: string | null = null,
88-
) {
89-
sessionStorage.setItem(
90-
process.env.NEXT_PUBLIC_AUTH_TOKEN_SS_KEY as string,
91-
authToken,
92-
);
93-
sessionStorage.setItem(
94-
process.env.NEXT_PUBLIC_SESSION_TOKEN_LS_KEY as string,
95-
sessionToken,
96-
);
97-
if (refreshToken) {
98-
localStorage.setItem(
99-
process.env.NEXT_PUBLIC_REFRESH_TOKEN_LS_KEY as string,
100-
refreshToken,
101-
);
102-
}
16+
// Cookie-based auth doesn't need JWT tokens
17+
return null;
10318
}
10419

10520
export async function login(username: string, password: string) {
106-
const headers: { [key: string]: string } = {};
107-
const sessionToken = sessionStorage.getItem(
108-
process.env.NEXT_PUBLIC_SESSION_TOKEN_LS_KEY as string,
109-
);
110-
if (sessionToken) {
111-
headers['woocommerce-session'] = `Session ${sessionToken}`;
112-
}
11321
try {
11422
const client = new ApolloClient({
11523
uri: process.env.NEXT_PUBLIC_GRAPHQL_URL,
11624
cache: new InMemoryCache(),
117-
headers,
25+
credentials: 'include', // Include cookies in requests
11826
});
11927

12028
const { data } = await client.mutate({
12129
mutation: LOGIN_USER,
12230
variables: { username, password },
12331
});
12432

125-
const { authToken, refreshToken, customer } = data.login;
33+
const loginResult = data.loginWithCookies;
12634

127-
if (!authToken || !refreshToken || !customer.sessionToken) {
128-
throw new Error('Failed to retrieve credentials.');
35+
if (loginResult.status !== 'SUCCESS') {
36+
throw new Error('Login failed');
12937
}
130-
saveCredentials(authToken, customer.sessionToken, refreshToken);
131-
return customer;
38+
39+
// On successful login, cookies are automatically set by the server
40+
return { success: true, status: loginResult.status };
13241
} catch (error: unknown) {
13342
if (error instanceof Error) {
13443
throw new Error(error.message);
13544
}
13645
throw new Error('An unknown error occurred during login.');
13746
}
13847
}
48+
49+
export async function logout() {
50+
// For cookie-based auth, we might need a logout mutation
51+
// For now, we can clear any client-side state
52+
if (typeof window !== 'undefined') {
53+
// Redirect to login or home page after logout
54+
window.location.href = '/';
55+
}
56+
}

src/utils/gql/GQL_MUTATIONS.ts

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -30,17 +30,9 @@ export const CREATE_USER = gql`
3030

3131
export const LOGIN_USER = gql`
3232
mutation Login($username: String!, $password: String!) {
33-
login(input: { username: $username, password: $password }) {
34-
authToken
35-
refreshToken
36-
customer {
37-
id
38-
email
39-
firstName
40-
lastName
41-
username
42-
sessionToken
43-
}
33+
loginWithCookies(input: { login: $username, password: $password }) {
34+
status
35+
clientMutationId
4436
}
4537
}
4638
`;

0 commit comments

Comments
 (0)