📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
redesigned the logic of google oauth sso
Blue Mouse8987fdb7d859
diff --git a/.env.example b/.env.exampleindex fcada8216..96b340cf9 100644--- a/.env.example+++ b/.env.example@@ -2,8 +2,5 @@ REACT_APP_API_URL=https://api.swetrix.com/REACT_APP_CDN_URL=https://cdn.swetrix.com/REACT_APP_BLOG_URL=https://blog.swetrix.com/REACT_APP_AIAPI_URL=https://aiapi.swetrix.com/--REACT_APP_GOOGLE_CLIENT_ID=-CHOKIDAR_USEPOLLING=trueGENERATE_SOURCEMAP=falsediff --git a/public/locales/en.json b/public/locales/en.jsonindex 32b0e7d09..fa72eb5c7 100644--- a/public/locales/en.json+++ b/public/locales/en.json@@ -25,7 +25,8 @@"forecastNumberCantBeBigger": "The forecast number cannot be bigger than {{max}} for the selected frequency","invalidToken": "Invalid token","transferRequestSent": "Transfer request sent",- "transferProjectReject": "The project transfer request has been cancelled"+ "transferProjectReject": "The project transfer request has been cancelled",+ "socialisationGenericError": "Error occurred while linking Swetrix account with a 3rd party service"},"common": {"features": "Features",@@ -277,6 +278,9 @@"verification": {"success": "Your email has been successfully verified!"},+ "socialisation": {+ "success": "Socialisation successful"+ },"common": {"signinInstead": "Sign in instead","signupInstead": "Sign up instead",@@ -756,7 +760,8 @@"contact": "Contact","changelog": "Changelog","main": "Ultimate open-source analytics to satisfy all your needs",- "press": "Media & Press"+ "press": "Media & Press",+ "socialisation": "Socialisation"},"header": {"switchTheme": "Switch theme",diff --git a/src/App.tsx b/src/App.tsxindex e1737ec8d..e5824fa8e 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -60,6 +60,7 @@ const ConfirmReportsShare = lazy(() => import('pages/Project/Settings/Emails/Conconst MediaAndPress = lazy(() => import('pages/Press'))const TransferProjectConfirm = lazy(() => import('pages/Project/Settings/TransferProject/TransferProjectConfirm'))const TransferProjectReject = lazy(() => import('pages/Project/Settings/TransferProject/TransferProjectReject'))+const Socialised = lazy(() => import('pages/Auth/Socialised'))const minimalFooterPages = ['/projects', '/dashboard', '/settings', '/contact',@@ -231,6 +232,7 @@ const App = () => {<Route path={routes.press} component={MediaAndPress} exact /><Route path={routes.transfer_confirm} component={TransferProjectConfirm} exact /><Route path={routes.transfer_reject} component={TransferProjectReject} exact />+ <Route path={routes.socialised} component={Socialised} exact /><Route path='*' component={NotFound} /></Switch></Suspense>diff --git a/src/api/index.ts b/src/api/index.tsindex 9148b7be9..0231f7691 100644--- a/src/api/index.ts+++ b/src/api/index.ts@@ -809,9 +809,42 @@ export const confirmTransferProject = (uuid: string) =>: error.response.data.message})-export const googleAuth = (data: any) =>+export const generateGoogleAuthURL = () =>api- .post('v1/auth/google', data)+ .post('v1/auth/google/generate')+ .then((response): unknown => response.data)+ .catch((error) => {+ debug('%s', error)+ throw _isEmpty(error.response.data?.message)+ ? error.response.data+ : error.response.data.message+ })++export const getJWTByGoogleHash = (hash: string) =>+ api+ .post('v1/auth/google/hash', { hash })+ .then((response): unknown => response.data)+ .catch((error) => {+ debug('%s', error)+ throw _isEmpty(error.response.data?.message)+ ? error.response.data+ : error.response.data.message+ })++export const linkByGoogleHash = (hash: string) =>+ api+ .post('v1/auth/google/link_by_hash', { hash })+ .then((response): unknown => response.data)+ .catch((error) => {+ debug('%s', error)+ throw _isEmpty(error.response.data?.message)+ ? error.response.data+ : error.response.data.message+ })++export const processGoogleToken = (token: string, hash: string) =>+ api+ .post('v1/auth/google/process-token', { token, hash }).then((response): unknown => response.data).catch((error) => {debug('%s', error)diff --git a/src/components/GoogleAuth.tsx b/src/components/GoogleAuth.tsxindex 301bcac4b..5355282cd 100644--- a/src/components/GoogleAuth.tsx+++ b/src/components/GoogleAuth.tsx@@ -1,110 +1,38 @@-import React, { useRef } from 'react'+import React from 'react'import { useTranslation } from 'react-i18next'-import { googleAuth } from 'api'import Button from 'ui/Button'import GoogleGSVG from 'ui/icons/GoogleG'-const googleScriptSrc = 'https://accounts.google.com/gsi/client'-const clientId = process.env.REACT_APP_GOOGLE_CLIENT_ID--const checkIfScriptIsLoaded = (src: string): boolean => {- return Boolean(document.querySelector(`script[src='${src}']`))-}--const loadScript = (src: string): Promise<any> => new Promise((resolve, reject) => {- if (checkIfScriptIsLoaded(src)) {- resolve(null)- return- }-- const script = document.createElement('script')- script.src = src- script.onload = resolve- script.onerror = reject- document.body.appendChild(script)-})interface IGoogleAuth {setIsLoading: (isLoading: boolean) => void,+ authSSO: any, // TODO add types+ dontRemember?: boolean,}-const GoogleAuth: React.FC<IGoogleAuth> = ({ setIsLoading }) => {+const GoogleAuth: React.FC<IGoogleAuth> = ({ setIsLoading, authSSO, dontRemember }) => {const { t } = useTranslation()- const actualGoogleButton = useRef<HTMLDivElement>(null)-- const handleCredentialResponse = async (response: any) => {- const result = await googleAuth({ token: response.credential })- console.log(result) // should be { user, access_token, refresh_token }-- setIsLoading(false)- }-- const renderGoogleLoginButton = async () => {- try {- await loadScript(googleScriptSrc)-- // @ts-ignore- window.google.accounts.id.initialize({- client_id: clientId,- callback: handleCredentialResponse,- })-- // @ts-ignore- window.google.accounts.id.renderButton(- actualGoogleButton.current,- { theme: 'outline', size: 'large' },- )- } catch (error) {- // todo: display error notification- console.error(error)- }- }-- const clickGoogleLoginButton = () => {- if (actualGoogleButton.current) {- // @ts-ignore- const iframe = actualGoogleButton.current.querySelector('iframe') as HTMLIFrameElement- // Emulating the click on an actial 'Sign in with Google' button-- // Works for Firefox- if (iframe.nextElementSibling) {- // @ts-ignore- iframe.nextElementSibling.click()- }-- // Works for Chrome- if (iframe.previousElementSibling) {- // idk how to make it work for Chrome yet so just displaying the google button itself- actualGoogleButton.current.className = ''- }- }- }const googleLogin = async () => {setIsLoading(true)- await renderGoogleLoginButton()- clickGoogleLoginButton()+ authSSO(dontRemember, t, () => {+ setIsLoading(false)+ })}return (- <div>- <Button- className='mr-2 border-indigo-100 dark:text-gray-50 dark:border-gray-700 dark:bg-gray-700 dark:hover:bg-gray-600'- onClick={googleLogin}- secondary- regular- >- <>- <GoogleGSVG className='w-5 h-5 mr-2' />- {t('auth.common.continueWithGoogle')}- </>- </Button>- <div- className='hidden'- ref={actualGoogleButton}- />- </div>+ <Button+ className='mr-2 border-indigo-100 dark:text-gray-50 dark:border-gray-700 dark:bg-gray-700 dark:hover:bg-gray-600'+ onClick={googleLogin}+ secondary+ regular+ >+ <>+ <GoogleGSVG className='w-5 h-5 mr-2' />+ {t('auth.common.continueWithGoogle')}+ </>+ </Button>)}diff --git a/src/pages/Auth/Signup/Signup.container.tsx b/src/pages/Auth/Signup/Signup.container.tsxindex 836427595..20879c1b3 100644--- a/src/pages/Auth/Signup/Signup.container.tsx+++ b/src/pages/Auth/Signup/Signup.container.tsx@@ -15,6 +15,10 @@ const mapDispatchToProps = (dispatch: AppDispatch) => ({}) => string, callback: (res: any) => void) => {dispatch(sagaActions.signupAsync(data, t, callback))},+ authSSO: (dontRemember: boolean, t: (key: string) => string, callback: (res: any) => void) => {+ console.log('dispatching authSSO')+ dispatch(sagaActions.authSSO(dontRemember, t, callback))+ }})export default connect(null, mapDispatchToProps)(Signup)diff --git a/src/pages/Auth/Signup/Signup.tsx b/src/pages/Auth/Signup/Signup.tsxindex cd00b13c6..80d731bcf 100644--- a/src/pages/Auth/Signup/Signup.tsx+++ b/src/pages/Auth/Signup/Signup.tsx@@ -21,7 +21,7 @@ import { HAVE_I_BEEN_PWNED_URL, TRIAL_DAYS } from 'redux/constants'import { trackCustom } from 'utils/analytics'import _omit from 'lodash/omit'-const Signup = ({ signup }: {+const Signup = ({ signup, authSSO }: {signup: (data: {email: string,password: string,@@ -31,6 +31,7 @@ const Signup = ({ signup }: {}, t: (key: string, optinions?: {[key: string]: string | number,}) => string, callback: (res: any) => void) => void,+ authSSO: any, // TODO add types}): JSX.Element => {const { t }: {t: (key: string, optinions?: {@@ -250,7 +251,7 @@ const Signup = ({ signup }: {{t('auth.signup.button')}</Button></div>- <GoogleAuth setIsLoading={setIsLoading} />+ <GoogleAuth setIsLoading={setIsLoading} authSSO={authSSO} dontRemember={form.dontRemember} /></form></div></Title>@@ -259,6 +260,7 @@ const Signup = ({ signup }: {Signup.propTypes = {signup: PropTypes.func.isRequired,+ authSSO: PropTypes.func.isRequired,}export default memo(withAuthentication(Signup, auth.notAuthenticated))diff --git a/src/pages/Auth/Socialised/index.tsx b/src/pages/Auth/Socialised/index.tsxnew file mode 100644index 000000000..0c96aca2d--- /dev/null+++ b/src/pages/Auth/Socialised/index.tsx@@ -0,0 +1,112 @@+import React, {+ useEffect, useState, memo,+} from 'react'+import { Link } from 'react-router-dom'+import { useTranslation } from 'react-i18next'+import { CheckCircleIcon, XCircleIcon } from '@heroicons/react/24/solid'+import _replace from 'lodash/replace'++import { processGoogleToken } from 'api'+import Title from 'components/Title'+import Loader from 'ui/Loader'+import routes from 'routes'++const Socialised = (): JSX.Element => {+ const { t }: {+ t: (key: string, optinions?: {+ [key: string]: string | number,+ }) => string,+ } = useTranslation('common')+ const [loading, setLoading] = useState<boolean>(true)+ const [isError, setIsError] = useState<boolean>(false)++ // For some reason, Google redirects to a hash URL, let's fix it+ const _location = _replace(window.location.href, `${routes.socialised}#`, `${routes.socialised}?`)++ const { searchParams } = new URL(_location)+ const state = searchParams.get('state')+ const token = searchParams.get('access_token')++ console.log(state, token)++ useEffect(() => {+ const processCode = async () => {+ if (!token || !state) {+ setIsError(true)+ return+ }++ try {+ await processGoogleToken(token, state)+ } catch (reason) {+ setIsError(true)+ console.error(`[ERROR] Error while processing Google code: ${reason}`)+ } finally {+ setLoading(false)+ }+ }++ setLoading(true)+ processCode()+ }, []) // eslint-disable-line++ if (loading) {+ return (+ <Title title={t('titles.socialisation')}>+ <div className='min-h-page bg-gray-50 dark:bg-gray-800'>+ <Loader />+ </div>+ </Title>+ )+ }++ if (isError) {+ return (+ <Title title={t('titles.socialisation')}>+ <div className='bg-gray-50 dark:bg-gray-800 min-h-page px-4 py-16 sm:px-6 sm:py-24 md:grid md:place-items-center lg:px-8'>+ <div className='max-w-max mx-auto'>+ <main className='sm:flex'>+ <XCircleIcon className='h-12 w-12 text-red-400' aria-hidden='true' />+ <div className='sm:ml-6'>+ <div className='sm:border-l max-w-prose sm:border-gray-200 sm:pl-6'>+ <h1 className='text-4xl font-extrabold text-gray-900 dark:text-gray-50 tracking-tight sm:text-5xl'>+ {t('apiNotifications.socialisationGenericError')}+ </h1>+ </div>+ <div className='mt-8 flex space-x-3 sm:border-l sm:border-transparent sm:pl-6'>+ <Link+ to={routes.contact}+ className='inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-indigo-700 bg-indigo-100 hover:bg-indigo-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:text-gray-50 dark:bg-gray-700 dark:hover:bg-gray-600 dark:focus:ring-gray-50'+ >+ {t('notFoundPage.support')}+ </Link>+ </div>+ </div>+ </main>+ </div>+ </div>+ </Title>+ )+ }++ return (+ <Title title={t('titles.socialisation')}>+ <div className='bg-gray-50 dark:bg-gray-800 min-h-page px-4 py-16 sm:px-6 sm:py-24 md:grid md:place-items-center lg:px-8'>+ <div className='max-w-max mx-auto'>+ <main className='sm:flex'>+ <CheckCircleIcon className='h-12 w-12 text-green-500 dark:text-green-400' aria-hidden='true' />+ <div className='sm:ml-6'>+ <div className='sm:border-l max-w-prose sm:border-gray-200 sm:pl-6'>+ <h1 className='text-4xl font-extrabold text-gray-900 dark:text-gray-50 tracking-tight sm:text-5xl'>+ {t('auth.socialisation.success')}+ </h1>+ </div>+ </div>+ </main>+ </div>+ </div>+ </Title>+ )+}++export default memo(Socialised)diff --git a/src/redux/constants/index.ts b/src/redux/constants/index.tsindex addd4eb4c..e892bc3c7 100644--- a/src/redux/constants/index.ts+++ b/src/redux/constants/index.ts@@ -405,9 +405,12 @@ export const PLAN_LIMITS: {export const TRIAL_DAYS: number = 14-export const chartTypes: {- [key: string]: string-} = {+export const chartTypes = Object.freeze({line: 'line',bar: 'bar',-}+})++export const SSO_ACTIONS = Object.freeze({+ LINK: 'link',+ AUTH: 'auth',+})diff --git a/src/redux/sagas/actions/index.ts b/src/redux/sagas/actions/index.tsindex ef2798fad..3d39c6213 100644--- a/src/redux/sagas/actions/index.ts+++ b/src/redux/sagas/actions/index.ts@@ -34,6 +34,7 @@ const loadProjectAlerts = (take?: number, skip?: number) => ({const loginAsync = (credentials: {email: string,password: string,+ dontRemember: boolean,}, callback = () => { }) => ({type: types.LOGIN_ASYNC,payload: {@@ -41,6 +42,14 @@ const loginAsync = (credentials: {},})+// currently only google is supported, in future we should provide a variable specifying the provider+const authSSO = (dontRemember: boolean, t: (key: string) => string = () => '', callback: (res: any) => void = () => { }) => ({+ type: types.AUTH_SSO,+ payload: {+ dontRemember, callback, t,+ },+})+const signupAsync = (data: {email: string,password: string,@@ -103,6 +112,7 @@ const sagaActions = {loadExtensions,loadProjectAlerts,loginAsync,+ authSSO,signupAsync,emailVerifyAsync,updateUserProfileAsync,diff --git a/src/redux/sagas/actions/types.ts b/src/redux/sagas/actions/types.tsindex cffd946b1..c62f04e35 100644--- a/src/redux/sagas/actions/types.ts+++ b/src/redux/sagas/actions/types.ts@@ -1,4 +1,4 @@-const sagaTypes: { [key: string]: string } = {+const sagaTypes = Object.freeze({LOAD_EXTENSIONS: 'LOAD_EXTENSIONS',LOAD_PROJECTS: 'LOAD_PROJECTS',LOAD_SHARED_PROJECTS: 'LOAD_SHARED_PROJECTS',@@ -10,6 +10,7 @@ const sagaTypes: { [key: string]: string } = {DELETE_ACCOUNT_ASYNC: 'DELETE_ACCOUNT_ASYNC',SHARE_VERIFY_ASYNC: 'SHARE_VERIFY_ASYNC',LOGOUT: 'LOGOUT',-}+ AUTH_SSO: 'AUTH_SSO',+})export default sagaTypesdiff --git a/src/redux/sagas/auth/watchers/index.ts b/src/redux/sagas/auth/watchers/index.tsindex ea83de867..e5a4ef8f6 100644--- a/src/redux/sagas/auth/watchers/index.ts+++ b/src/redux/sagas/auth/watchers/index.ts@@ -5,6 +5,7 @@ import logout from 'redux/sagas/auth/workers/logout'import verifyEmail from 'redux/sagas/auth/workers/verifyEmail'import updateUserProfile from 'redux/sagas/auth/workers/updateUserProfile'import deleteUserAccount from 'redux/sagas/auth/workers/deleteUserAccount'+import ssoAuth from 'redux/sagas/auth/workers/sso_auth'import sagaTypes from '../../actions/types'function* watchLogin() {@@ -37,10 +38,15 @@ function* watchDeleteUserProfile() {yield takeLatest(sagaTypes.DELETE_ACCOUNT_ASYNC, deleteUserAccount)}+function* watchAuthSSO() {+ // @ts-ignore+ yield takeLatest(sagaTypes.AUTH_SSO, ssoAuth)+}+export default function* watchAuth() {yield all([call(watchLogin), call(watchSignup), call(watchVerifyEmail),call(watchUpdateUserProfile), call(watchDeleteUserProfile),- call(watchLogout),+ call(watchLogout), call(watchAuthSSO),])}diff --git a/src/redux/sagas/auth/workers/sso_auth.ts b/src/redux/sagas/auth/workers/sso_auth.tsnew file mode 100644index 000000000..a9ba9417f--- /dev/null+++ b/src/redux/sagas/auth/workers/sso_auth.ts@@ -0,0 +1,85 @@+import { call, put, delay } from 'redux-saga/effects'+import _isObject from 'lodash/isPlainObject'+import _omit from 'lodash/omit'++import UIActions from 'redux/reducers/ui'+import { authActions } from 'redux/reducers/auth'+import { errorsActions } from 'redux/reducers/errors'+import { setAccessToken } from 'utils/accessToken'+import {+ getJWTByGoogleHash, generateGoogleAuthURL,+} from 'api'+import { setRefreshToken } from 'utils/refreshToken'+import sagaActions from '../../actions/index'+import { openBrowserWindow } from 'utils/generic'++const AUTH_WINDOW_WIDTH = 600+const AUTH_WINDOW_HEIGHT = 800++const HASH_CHECK_FREQUENCY = 1000 // 1 second++// TODO: Add types+export default function* ssoAuth({ payload: { callback, dontRemember } }: any) {+ console.log('ssoAuth worker')+ const authWindow = openBrowserWindow('', AUTH_WINDOW_WIDTH, AUTH_WINDOW_HEIGHT)++ if (!authWindow) {+ // TODO: Check the issue later+ // @ts-ignore+ yield put(errorsActions.loginFailed('SOMETHING WENT WRONG (THIS MESSAGE SHOULD BE SENT VIA I18N)'))+ // callback(false, false)+ return+ }++ try {+ const { uuid, auth_url: authUrl } = yield call(generateGoogleAuthURL)++ console.log(uuid, authUrl)++ // Set the URL of the authentification browser window+ authWindow.location = authUrl++ // Close the authWindow after 5 minutes+ // TODO: THIS VALUE SHOULD BE RETURNED FROM THE API+ setTimeout(() => {+ authWindow.close()+ }, 5 * 60 * 1000)++ while (true) {+ yield delay(HASH_CHECK_FREQUENCY)++ try {+ const {+ accessToken, refreshToken, user,+ } = yield call(getJWTByGoogleHash, uuid)++ yield put(authActions.setDontRemember(dontRemember))++ if (user.isTwoFactorAuthenticationEnabled) {+ yield call(setAccessToken, accessToken, true)+ yield call(setRefreshToken, refreshToken)+ yield put(authActions.updateUserData(user))+ callback(false, true)+ return+ }++ yield put(authActions.loginSuccessful(user))+ yield call(setAccessToken, accessToken, dontRemember)+ yield call(setRefreshToken, refreshToken)+ yield put(UIActions.setThemeType(user.theme))+ yield put(sagaActions.loadProjects())+ yield put(sagaActions.loadSharedProjects())+ yield put(sagaActions.loadProjectAlerts())+ callback(true, false)+ } catch (reason) {+ // Authentication is not finished yet+ }+ if (authWindow.closed) {+ // callback(false, false)+ return+ }+ }+ } catch (reason) {+ // TODO: Display notification. Something went wrong while generating auth URL+ }+}diff --git a/src/redux/sagas/auth/workers/sso_link.ts b/src/redux/sagas/auth/workers/sso_link.tsnew file mode 100644index 000000000..70b786d12--- /dev/null+++ b/src/redux/sagas/auth/workers/sso_link.ts@@ -0,0 +1 @@+// TODOdiff --git a/src/routes.ts b/src/routes.tsindex 4ee82a931..6bb9bab82 100644--- a/src/routes.ts+++ b/src/routes.ts@@ -29,6 +29,7 @@ const routes = Object.freeze({press: '/press',transfer_confirm: '/project/transfer/confirm',transfer_reject: '/project/transfer/cancel',+ socialised: '/socialised',})export default routesdiff --git a/src/utils/generic.ts b/src/utils/generic.tsindex f47cd544b..1353cff4f 100644--- a/src/utils/generic.ts+++ b/src/utils/generic.ts@@ -74,3 +74,7 @@ export const sumArrays = (...arrays: any): number[] => {return _reduce(arrays, (sum, array) => sum + array[index], 0)})}++export const openBrowserWindow = (url: string, width: number, height: number) => {+ return window.open(url, '', `width=${width},height=${height},top=${(window.innerHeight - height) / 2},left=${(window.innerWidth - width) / 2}`)+}