Skip to content

Commit

Permalink
Merge pull request #1 from Zakaria9375/develop
Browse files Browse the repository at this point in the history
refactor useAuth
  • Loading branch information
Zakaria9375 authored Jul 2, 2024
2 parents 2c4e002 + 712cdfc commit 70a9dd6
Show file tree
Hide file tree
Showing 8 changed files with 88 additions and 87 deletions.
3 changes: 2 additions & 1 deletion .env
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
VITE_AUTH0_DOMAIN=dev-zqi0aizss6zf41fe.us.auth0.com
VITE_AUTH0_CLIENT_ID=jEAg3tFkMJzWra1EYR7WHHeVIxPhMLGB
VITE_AUTH0_AUDIENCE=https://naked-vivien-zaportfolio-345d21c7.koyeb.app/api
VITE_AUTH0_AUDIENCE1=https://naked-vivien-zaportfolio-345d21c7.koyeb.app/api
VITE_AUTH0_AUDIENCE=http://localhost:8050/api
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,4 @@ dist-ssr
*.njsproj
*.sln
*.sw?
.env
55 changes: 34 additions & 21 deletions src/components/base/AppHeader.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import { useAuth0 } from "@auth0/auth0-react";
import { NavLink } from "react-router-dom";
import useAuth from "../../hooks/useAuth";
import { useSelector } from "react-redux";
import { RootState } from "../../stores/store";
import useAppAuth from "../../hooks/useAppAuth";

function AppHeader() {
useAuth();
const { loginWithRedirect, logout } = useAuth0();
useAppAuth();
const { loginWithRedirect, logout, isLoading } = useAuth0();
const logoutWithRedirect = () =>
logout({
logoutParams: {
returnTo: window.location.origin,
returnTo: `${window.location.origin}/redirect`,
},
});
const { isAuthenticated, user } = useSelector(
Expand All @@ -31,26 +31,39 @@ function AppHeader() {
<NavLink to="/search">Search</NavLink>
</nav>
<div>
{isAuthenticated ? (
<div className="flex gap-3 items-center">
<div className="flex gap-2 items-center">
<img
src={user?.photo || "/public/user.png"}
alt="Profile photo"
className="size-8 rounded-full"
/>
<span className="text-base tracking-tight">
{user?.name || "Welcome"}
</span>
{!isLoading ? (
isAuthenticated ? (
<div className="flex gap-3 items-center">
<div className="flex gap-2 items-center">
<img
src={user?.photo || "/public/user.png"}
alt="Profile photo"
className="size-8 rounded-full"
/>
<span className="text-base tracking-tight">
{user?.name || "Welcome"}
</span>
</div>
<button onClick={() => logoutWithRedirect()} className="log-btn">
Log out
</button>
</div>
<button onClick={() => logoutWithRedirect()} className="log-btn">
Log out
) : (
<button
onClick={() =>
loginWithRedirect({
authorizationParams: {
redirect_uri: `${window.location.origin}/redirect`,
},
})
}
className="log-btn"
>
Log in
</button>
</div>
)
) : (
<button onClick={() => loginWithRedirect()} className="log-btn">
Log in
</button>
<div className="name-spin"></div>
)}
</div>
</header>
Expand Down
1 change: 1 addition & 0 deletions src/hooks/Auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

41 changes: 41 additions & 0 deletions src/hooks/useAppAuth.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { useAuth0 } from "@auth0/auth0-react";
import { login, logout } from "../stores/reducers/authReducer";
import axios from "axios";
import { baseUrl, DBUser } from "../types/types";
import { useEffect } from "react";
import { useDispatch } from "react-redux";

const useAppAuth = () => {
const { user: authUser, isAuthenticated } = useAuth0();
const dispatch = useDispatch();
useEffect(() => {
const authenticate = async () => {
if (isAuthenticated && authUser) {
let user: DBUser;
try {
const response = await axios.get(
`${baseUrl}/users/search/findByEmail?email=${authUser.email}`
);
user = response.data;
} catch (error) {
console.log("User does not exist in database", error);
const newUser = {
name: authUser.name,
email: authUser.email,
photo: authUser.picture || null,
};
const response = await axios.post(`${baseUrl}/users`, newUser);
user = response.data;
}
dispatch(login({ user }));
} else {
dispatch(logout());
}
};
authenticate();
}, [isAuthenticated, authUser, dispatch]);

return { isAuthenticated, authUser };
};

export default useAppAuth;
54 changes: 0 additions & 54 deletions src/hooks/useAuth.tsx

This file was deleted.

12 changes: 8 additions & 4 deletions src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,20 @@ import { Auth0Provider } from "@auth0/auth0-react";
import { getConfig } from "./authConfig.ts";
import { Provider } from "react-redux";
import { store } from "./stores/store.ts";

const { domain, clientId } = getConfig();
function onRedirect() {
window.history.replaceState(
{},
document.title,
window.location.origin + "/redirect"
);
}
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<Auth0Provider
domain={domain}
clientId={clientId}
authorizationParams={{
redirect_uri: window.location.origin,
}}
onRedirectCallback={onRedirect}
>
<Provider store={store}>
<App />
Expand Down
8 changes: 1 addition & 7 deletions src/stores/reducers/authReducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,39 +4,33 @@ import { DBUser } from "../../types/types";
export interface MyAuthState {
isAuthenticated: boolean;
user: DBUser | null;
token: string | null;
}

const initialState: MyAuthState = {
isAuthenticated: JSON.parse(
localStorage.getItem("isAuthenticated") || "false"
),
user: JSON.parse(localStorage.getItem("user") || "null"),
token: localStorage.getItem("token") || null,
};

const authSlice = createSlice({
name: "auth",
initialState,
reducers: {
login: (state, action: PayloadAction<{ user: DBUser; token: string }>) => {
login: (state, action: PayloadAction<{ user: DBUser }>) => {
state.isAuthenticated = true;
state.user = action.payload.user;
state.token = action.payload.token;
localStorage.setItem(
"isAuthenticated",
JSON.stringify(state.isAuthenticated)
);
localStorage.setItem("user", JSON.stringify(state.user));
localStorage.setItem("token", state.token);
},
logout: (state) => {
state.isAuthenticated = false;
state.user = null;
state.token = null;
localStorage.removeItem("isAuthenticated");
localStorage.removeItem("user");
localStorage.removeItem("token");
},
},
});
Expand Down

0 comments on commit 70a9dd6

Please sign in to comment.