Skip to content

Commit

Permalink
added ability to log in with google
Browse files Browse the repository at this point in the history
  • Loading branch information
Macktireh committed Jul 25, 2024
1 parent a66759b commit f124925
Show file tree
Hide file tree
Showing 10 changed files with 6,732 additions and 32,625 deletions.
27,159 changes: 6,575 additions & 20,584 deletions package-lock.json

Large diffs are not rendered by default.

11,958 changes: 0 additions & 11,958 deletions pnpm-lock.yaml

This file was deleted.

36 changes: 36 additions & 0 deletions src/actions/auth/googleLogin.action.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { AnyAction, Dispatch } from "redux";

import Axios from "@/config/axios";
import * as Api from "@/config/apiEndPoint";
import * as Types from "@/actions/types";
import loginAction from "./login.action";

const googleLoginAction =
(code: any) =>
async (dispatch: Dispatch<AnyAction> | any) => {
const config = {
headers: {
"Content-Type": "application/json",
},
};

const body = JSON.stringify({ code });

console.log("googleLoginAction body", body);

try {
const res = await Axios.post(Api.googleLoginEndpoint, body, config);

localStorage.setItem("access", res.data.token.access);
localStorage.setItem("refresh", res.data.token.refresh);

dispatch(loginAction(true));

} catch (error: any) {
dispatch({
type: Types.LOGIN_FAIL,
});
}
};

export default googleLoginAction;
27 changes: 27 additions & 0 deletions src/components/auth/GoogleLoginButton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import ButtonCustom from "@/widgets/ButtonCustom";

interface propsTypes {
text: string;
nameClass?: string;
isDisabled?: boolean;
}

export const GoogleLoginButton: React.FC<propsTypes> = ({ text, nameClass, isDisabled }) => {
const handleReachGoogle = () => {
const GoogleClientID = process.env.REACT_APP_GOOGLE_CLIENT_ID;
const GoogleCallBackURI = process.env.REACT_APP_GOOGLE_CALLBACK_URL;
window.location.replace(
`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${GoogleCallBackURI}&prompt=consent&response_type=code&client_id=${GoogleClientID}&scope=openid%20email%20profile&access_type=offline`
);
};

return (
<ButtonCustom
nameClass={nameClass}
pic={"/static/svg/google.svg"}
text={text}
onClick={handleReachGoogle}
isDisabled={isDisabled}
/>
);
};
1 change: 1 addition & 0 deletions src/config/apiEndPoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export const resetPasswordEndpoint : string = "/api/auth/user/reset-password/"
export const verifyTokenEndpoint : string = "/api/auth/user/jwt/verify/"
export const refreshTokenEndpoint : string = "/api/auth/user/token/refresh/"
export const logoutEndpoint : string = "/api/auth/user/logout/"
export const googleLoginEndpoint : string = "/api/auth/user/login/google/"


/***
Expand Down
17 changes: 13 additions & 4 deletions src/helper/AuthProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,30 @@ import * as React from "react";
import { connect } from "react-redux";

import { IRootState } from "@/models";
import { Navigate } from "react-router-dom";
import { Navigate, useSearchParams } from "react-router-dom";
import { privateRoutes } from "@/routes/private.routes";
import SpinnersLoding from "@/widgets/SpinnersLoding";
import googleLoginAction from "@/actions/auth/googleLogin.action";

type TProps = {
isPublic: boolean;
isAuthenticated: boolean | null;
children: React.PropsWithChildren<any>;
googleLoginAction: (code: any) => void;
};

const AuthProvider: React.FC<TProps> = ({ isPublic, isAuthenticated, children }) => {
const AuthProvider: React.FC<TProps> = ({ isPublic, isAuthenticated, children, googleLoginAction }) => {
const [loading, setLoading] = React.useState(true);
let [searchParams, setSearchParams] = useSearchParams();

React.useEffect(() => {
if (isAuthenticated !== null) setLoading(false);
const code = searchParams.get("code")
if (code && isAuthenticated === false || isAuthenticated === null) {
(async () => {
await googleLoginAction( code );
setTimeout(() => setLoading(false), 800);
})();
} else if (isAuthenticated !== null) setLoading(false);
}, [loading, isAuthenticated]);

if (!isPublic) {
Expand All @@ -30,4 +39,4 @@ const mapStateToProps = (state: IRootState) => ({
isAuthenticated: state.authReducer.isAuthenticated,
});

export default connect(mapStateToProps, {})(AuthProvider);
export default connect(mapStateToProps, {googleLoginAction})(AuthProvider);
7 changes: 2 additions & 5 deletions src/pages/auth/Login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import useLogin from "@/hooks/UseLogin";
import loginAction from "@/actions/auth/login.action";
import { IAuthLogin } from "@/models";
import { authRoutes } from "@/routes/auth.routes";
import { GoogleLoginButton } from "@/components/auth/GoogleLoginButton";

type propsTypes = { loginAction: (isAuthenticated?: boolean) => Promise<void> };

Expand Down Expand Up @@ -39,11 +40,7 @@ const Login: React.FC<propsTypes> = ({ loginAction }) => {
return (
<ModalAuth title="Connectez-vous à Clone Twitter" loading={loading} disabled={disabled}>
<div className="box-social-auth">
<ButtonCustom
nameClass={"btn-signup-ext"}
pic={"/static/svg/google.svg"}
text={"Se connecter avec Google"}
/>
<GoogleLoginButton text={"Se connecter avec Google"} nameClass="btn-signup-ext btn-signup" />
<ButtonCustom
nameClass={"btn-signup-ext"}
pic={"/static/svg/apple.svg"}
Expand Down
7 changes: 2 additions & 5 deletions src/pages/public/HomePublic.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Link } from "react-router-dom";

import ButtonCustom from "@/widgets/ButtonCustom";
import { authRoutes } from "@/routes/auth.routes";
import { GoogleLoginButton } from "@/components/auth/GoogleLoginButton";

const HomePublic: React.FC = () => {
React.useEffect(() => {
Expand All @@ -21,11 +22,7 @@ const HomePublic: React.FC = () => {
</div>
<div className="frame-btn-connexion">
<div className="frame1">
<ButtonCustom
nameClass={"btn-signup-ext"}
pic={"/static/svg/google.svg"}
text={"S'inscrire avec Google"}
/>
<GoogleLoginButton text={"S'inscrire avec Google"} nameClass="btn-signup-ext btn-signup" />
<ButtonCustom
nameClass={"btn-signup-ext"}
pic={"/static/svg/apple.svg"}
Expand Down
137 changes: 69 additions & 68 deletions src/service-worker.ts
Original file line number Diff line number Diff line change
@@ -1,80 +1,81 @@
/// <reference lib="webworker" />
/* eslint-disable no-restricted-globals */
// /// <reference lib="webworker" />
// /* eslint-disable no-restricted-globals */

// This service worker can be customized!
// See https://developers.google.com/web/tools/workbox/modules
// for the list of available Workbox modules, or add any other
// code you'd like.
// You can also remove this file if you'd prefer not to use a
// service worker, and the Workbox build step will be skipped.
// // This service worker can be customized!
// // See https://developers.google.com/web/tools/workbox/modules
// // for the list of available Workbox modules, or add any other
// // code you'd like.
// // You can also remove this file if you'd prefer not to use a
// // service worker, and the Workbox build step will be skipped.

import { clientsClaim } from 'workbox-core';
import { ExpirationPlugin } from 'workbox-expiration';
import { precacheAndRoute, createHandlerBoundToURL } from 'workbox-precaching';
import { registerRoute } from 'workbox-routing';
import { StaleWhileRevalidate } from 'workbox-strategies';
// import { clientsClaim } from 'workbox-core';
// import { ExpirationPlugin } from 'workbox-expiration';
// import { precacheAndRoute, createHandlerBoundToURL } from 'workbox-precaching';
// import { registerRoute } from 'workbox-routing';
// import { StaleWhileRevalidate } from 'workbox-strategies';

declare const self: ServiceWorkerGlobalScope;
// declare const self: ServiceWorkerGlobalScope;

clientsClaim();
// clientsClaim();

// Precache all of the assets generated by your build process.
// Their URLs are injected into the manifest variable below.
// This variable must be present somewhere in your service worker file,
// even if you decide not to use precaching. See https://cra.link/PWA
precacheAndRoute(self.__WB_MANIFEST);
// // Precache all of the assets generated by your build process.
// // Their URLs are injected into the manifest variable below.
// // This variable must be present somewhere in your service worker file,
// // even if you decide not to use precaching. See https://cra.link/PWA
// precacheAndRoute(self.__WB_MANIFEST);

// Set up App Shell-style routing, so that all navigation requests
// are fulfilled with your index.html shell. Learn more at
// https://developers.google.com/web/fundamentals/architecture/app-shell
const fileExtensionRegexp = new RegExp('/[^/?]+\\.[^/]+$');
registerRoute(
// Return false to exempt requests from being fulfilled by index.html.
({ request, url }: { request: Request; url: URL }) => {
// If this isn't a navigation, skip.
if (request.mode !== 'navigate') {
return false;
}
// // Set up App Shell-style routing, so that all navigation requests
// // are fulfilled with your index.html shell. Learn more at
// // https://developers.google.com/web/fundamentals/architecture/app-shell
// const fileExtensionRegexp = new RegExp('/[^/?]+\\.[^/]+$');
// registerRoute(
// // Return false to exempt requests from being fulfilled by index.html.
// ({ request, url }: { request: Request; url: URL }) => {
// // If this isn't a navigation, skip.
// if (request.mode !== 'navigate') {
// return false;
// }

// If this is a URL that starts with /_, skip.
if (url.pathname.startsWith('/_')) {
return false;
}
// // If this is a URL that starts with /_, skip.
// if (url.pathname.startsWith('/_')) {
// return false;
// }

// If this looks like a URL for a resource, because it contains
// a file extension, skip.
if (url.pathname.match(fileExtensionRegexp)) {
return false;
}
// // If this looks like a URL for a resource, because it contains
// // a file extension, skip.
// if (url.pathname.match(fileExtensionRegexp)) {
// return false;
// }

// Return true to signal that we want to use the handler.
return true;
},
createHandlerBoundToURL(process.env.PUBLIC_URL + '/index.html')
);
// // Return true to signal that we want to use the handler.
// return true;
// },
// createHandlerBoundToURL(process.env.PUBLIC_URL + '/index.html')
// );

// An example runtime caching route for requests that aren't handled by the
// precache, in this case same-origin .png requests like those from in public/
registerRoute(
// Add in any other file extensions or routing criteria as needed.
({ url }) => url.origin === self.location.origin && url.pathname.endsWith('.png'),
// Customize this strategy as needed, e.g., by changing to CacheFirst.
new StaleWhileRevalidate({
cacheName: 'images',
plugins: [
// Ensure that once this runtime cache reaches a maximum size the
// least-recently used images are removed.
new ExpirationPlugin({ maxEntries: 50 }),
],
})
);
// // An example runtime caching route for requests that aren't handled by the
// // precache, in this case same-origin .png requests like those from in public/
// registerRoute(
// // Add in any other file extensions or routing criteria as needed.
// ({ url }) => url.origin === self.location.origin && url.pathname.endsWith('.png'),
// // Customize this strategy as needed, e.g., by changing to CacheFirst.
// new StaleWhileRevalidate({
// cacheName: 'images',
// plugins: [
// // Ensure that once this runtime cache reaches a maximum size the
// // least-recently used images are removed.
// new ExpirationPlugin({ maxEntries: 50 }),
// ],
// })
// );

// This allows the web app to trigger skipWaiting via
// registration.waiting.postMessage({type: 'SKIP_WAITING'})
self.addEventListener('message', (event) => {
if (event.data && event.data.type === 'SKIP_WAITING') {
self.skipWaiting();
}
});
// // This allows the web app to trigger skipWaiting via
// // registration.waiting.postMessage({type: 'SKIP_WAITING'})
// self.addEventListener('message', (event) => {
// if (event.data && event.data.type === 'SKIP_WAITING') {
// self.skipWaiting();
// }
// });

// Any other custom service worker logic can go here.
// // Any other custom service worker logic can go here.
export {}
8 changes: 7 additions & 1 deletion src/styles/pages/auth/_auth.scss
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,12 @@
width: 18px;
}
}
.btn-signup-ext[disabled] {
background-color: rgba($color2, 0.7) !important;
border-color: transparent;
color: $color1;
cursor: not-allowed;
}
}

.sep {
Expand Down Expand Up @@ -124,7 +130,7 @@
.btn-signup[disabled] {
background-color: rgba($color2, 0.7) !important;
color: $color1;
cursor: default;
cursor: not-allowed;
}

.info {
Expand Down

0 comments on commit f124925

Please sign in to comment.