📈 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
added ability to link/unlink social profiles
Blue Mouse8301920258e2
diff --git a/package.json b/package.jsonindex 58c4a5da8..24e52b725 100644--- a/package.json+++ b/package.json@@ -40,6 +40,7 @@"react-router-dom": "^5.3.4","react-router-hash-link": "^2.4.3","react-scripts": "5.0.1",+ "react-select": "^5.7.2","react-snowfall": "^1.2.1","react-timezone-select": "^2.1.0","react-type-animation": "^3.0.1",diff --git a/public/locales/en.json b/public/locales/en.jsonindex ff2213ef4..16119f725 100644--- a/public/locales/en.json+++ b/public/locales/en.json@@ -27,7 +27,10 @@"transferRequestSent": "Transfer request sent","transferProjectReject": "The project transfer request has been cancelled","socialisationGenericError": "Error occurred while linking Swetrix account with a 3rd party service",- "socialisationAuthGenericError": "Error occurred while authenticating with a 3rd party service"+ "socialisationUnlinkGenericError": "Error occurred while unlinking Swetrix account with the 3rd party service",+ "socialisationAuthGenericError": "Error occurred while authenticating with a 3rd party service",+ "socialAccountLinked": "The Swetrix account has been linked with your selected provider",+ "socialAccountUninked": "The Swetrix account has been unlinked from the selected provider"},"common": {"features": "Features",@@ -71,7 +74,9 @@"loading": "Loading..","edit": "Edit","account": "Account",- "transferring": "Transferring"+ "transferring": "Transferring",+ "link": "Link",+ "unlink": "Unlink"},"main": {"ukrSupport": "Support the Ukrainian army to fight Russian invasion.",@@ -425,6 +430,9 @@"telegram": "Receive notifications directly into a Telegram bot.","tgHint": "Write a message to <url>{{username}}</url> to get your chat ID. This bot will be used later to send you notifications or alerts."},+ "socialisations": "Socialisations",+ "socialisationsDesc": "Socialisation feature allows you to link 3rd party accounts (like Google or Twitter) to your Swetrix account and use them to sign in to Swetrix.",+ "cantUnlinkSocialisation": "You can't unlink this socialisation because is was used to register your account.","addIntegration": "Add integration","removeIntegration": "Remove integration","chatID": "Chat ID",diff --git a/src/api/index.ts b/src/api/index.tsindex 0231f7691..a989fe162 100644--- a/src/api/index.ts+++ b/src/api/index.ts@@ -842,6 +842,17 @@ export const linkByGoogleHash = (hash: string) =>: error.response.data.message})+export const unlinkGoogle = () =>+ api+ .delete('v1/auth/google/unlink')+ .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 })diff --git a/src/pages/UserSettings/UserSettings.container.tsx b/src/pages/UserSettings/UserSettings.container.tsxindex 53c5ae818..280d1fdc9 100644--- a/src/pages/UserSettings/UserSettings.container.tsx+++ b/src/pages/UserSettings/UserSettings.container.tsx@@ -120,6 +120,24 @@ const mapDispatchToProps = (dispatch: AppDispatch) => ({// setThemeType: (theme) => {// dispatch(UIActions.setThemeType(theme))// },+ linkSSO: (t: (key: string) => string, callback: (e: any) => void, provider: string) => {+ dispatch(+ sagaActions.linkSSO(+ t,+ callback,+ provider,+ ),+ )+ },+ unlinkSSO: (t: (key: string) => string, callback: (e: any) => void, provider: string) => {+ dispatch(+ sagaActions.unlinkSSO(+ t,+ callback,+ provider,+ ),+ )+ },})export default connect(mapStateToProps, mapDispatchToProps)(UserSettings)diff --git a/src/pages/UserSettings/UserSettings.tsx b/src/pages/UserSettings/UserSettings.tsxindex 4755f8276..b94d533d8 100644--- a/src/pages/UserSettings/UserSettings.tsx+++ b/src/pages/UserSettings/UserSettings.tsx@@ -42,6 +42,7 @@ import {import ProjectList from './components/ProjectList'import TwoFA from './components/TwoFA'import Integrations from './components/Integrations'+import Socialisations from './components/Socialisations'import NoSharedProjects from './components/NoSharedProjects'dayjs.extend(utc)@@ -67,6 +68,8 @@ interface IProps {user: IUser,dontRemember: boolean,isPaidTierUsed: boolean,+ linkSSO: (t: (key: string) => string, callback: (e: any) => void, provider: string) => void,+ unlinkSSO: (t: (key: string) => string, callback: (e: any) => void, provider: string) => void,}interface IForm extends Partial<IUser> {@@ -80,6 +83,7 @@ const UserSettings = ({setProjectsShareData, userSharedUpdate, sharedProjectError, updateUserData,genericError, onGDPRExportFailed, updateProfileFailed, updateUserProfileAsync,accountUpdated, setAPIKey, user, dontRemember, isPaidTierUsed, // setThemeType, themeType,+ linkSSO, unlinkSSO,}: IProps): JSX.Element => {const history = useHistory()const { t }: {@@ -538,6 +542,18 @@ const UserSettings = ({updateUserData={updateUserData}genericError={genericError}/>++ {/* Socialisations setup */}+ <hr className='mt-5 border-gray-200 dark:border-gray-600' />+ <h3 id='socialisations' className='flex items-center mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>+ {t('profileSettings.socialisations')}+ </h3>+ <Socialisations+ user={user}+ linkSSO={linkSSO}+ unlinkSSO={unlinkSSO}+ />+{/* Shared projects setting */}<hr className='mt-5 border-gray-200 dark:border-gray-600' /><h3 className='flex items-center mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>@@ -698,6 +714,8 @@ UserSettings.propTypes = {user: PropTypes.object.isRequired,dontRemember: PropTypes.bool.isRequired,isPaidTierUsed: PropTypes.bool.isRequired,+ linkSSO: PropTypes.func.isRequired,+ unlinkSSO: PropTypes.func.isRequired,}export default memo(withAuthentication(UserSettings, auth.authenticated))diff --git a/src/pages/UserSettings/components/Socialisations.tsx b/src/pages/UserSettings/components/Socialisations.tsxnew file mode 100644index 000000000..5e6707a63--- /dev/null+++ b/src/pages/UserSettings/components/Socialisations.tsx@@ -0,0 +1,148 @@+import React, { useState, memo } from 'react'+import { useTranslation } from 'react-i18next'+import _map from 'lodash/map'+import {+ CheckCircleIcon, XCircleIcon,+} from '@heroicons/react/24/solid'++import Tooltip from 'ui/Tooltip'+import Button from 'ui/Button'+import Google from 'ui/icons/GoogleG'+import { IUser } from 'redux/models/IUser'+import { SOCIALISATIONS } from 'redux/constants'++const AVAILABLE_SOCIALISATIONS = [+ {+ name: 'Google',+ key: SOCIALISATIONS.GOOGLE,+ Icon: Google,+ },+]++/**+ * @param {IUser} user - user object+ * @param {string} socialisation - key from SOCIALISATIONS+ * @returns {[boolean, boolean]} - [isConnected, isUnlinkable]+*/+const getStatusByUser = (user: IUser, socialisation: string) => {+ if (socialisation === SOCIALISATIONS.GOOGLE) {+ const connected = user.googleId+ const unlinkable = !user.registeredWithGoogle+ return [connected, unlinkable]+ }++ return [false, false]+}++interface ISocialisations {+ user: IUser,+ linkSSO: (t: (key: string) => string, callback: (e: any) => void, provider: string) => void,+ unlinkSSO: (t: (key: string) => string, callback: (e: any) => void, provider: string) => void,+}++const Socialisations = ({+ user, linkSSO, unlinkSSO,+}: ISocialisations) => {+ const { t }: {+ t: (key: string) => string,+ } = useTranslation('common')+ const [isLoading, setIsLoading] = useState(false)++ const _linkSSO = (key: string) => {+ setIsLoading(true)++ linkSSO(t, () => {+ setIsLoading(false)+ }, key)+ }++ const _unlinkSSO = (key: string) => {+ setIsLoading(true)++ unlinkSSO(t, () => {+ setIsLoading(false)+ }, key)+ }++ return (+ <>+ <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>+ {t('profileSettings.socialisationsDesc')}+ </p>+ <div className='overflow-hidden bg-white dark:bg-gray-700 mt-2 shadow sm:rounded-md'>+ <ul className='divide-y divide-gray-200'>+ {+ _map(AVAILABLE_SOCIALISATIONS, ({+ name, key, Icon,+ }) => {+ const [connected, unlinkable] = getStatusByUser(user, key)++ const status = connected ? 'connected' : 'notConnected'++ return (+ <li key={key}>+ <div className='sm:flex items-center px-1 py-4 sm:px-6'>+ <div className='flex min-w-0 flex-1 items-center'>+ <div className='flex-shrink-0 hidden sm:block'>+ <Icon className='max-h-12 max-w-12 h-12 w-12 rounded-full' />+ </div>+ <div className='min-w-0 flex-1 px-2 sm:px-4 md:grid md:grid-cols-2 md:gap-4'>+ <div>+ <p className='text-md font-medium text-gray-800 dark:text-gray-50'>+ {name}+ </p>+ <p className='mt-2 flex items-center text-sm text-gray-500 dark:text-gray-100'>+ {status === 'notConnected' && <XCircleIcon className='mr-1.5 h-5 w-5 flex-shrink-0 text-red-400' aria-hidden='true' />}+ {status === 'connected' && <CheckCircleIcon className='mr-1.5 h-5 w-5 flex-shrink-0 text-green-400' aria-hidden='true' />}+ {t(`common.${status}`)}+ </p>+ </div>+ </div>+ </div>+ <div className='flex justify-center mt-2 sm:block sm:mt-0'>+ {connected && !unlinkable && (+ <Tooltip+ className='max-w-content !w-full'+ tooltipNode={(+ <Button onClick={() => { }} disabled small danger>+ {t('common.unlink')}+ </Button>+ )}+ text={t('profileSettings.cantUnlinkSocialisation')}+ />+ )}++ {connected && unlinkable && (+ <Button+ onClick={() => _unlinkSSO(key)}+ loading={isLoading}+ small+ danger+ >+ {t('common.unlink')}+ </Button>+ )}++ {!connected && (+ <Button+ onClick={() => _linkSSO(key)}+ loading={isLoading}+ small+ primary+ >+ {t('common.link')}+ </Button>+ )}+ </div>+ </div>+ </li>+ )+ })+ }+ </ul>+ </div>+ </>+ )+}++export default memo(Socialisations)diff --git a/src/redux/constants/index.ts b/src/redux/constants/index.tsindex e892bc3c7..98dd5a010 100644--- a/src/redux/constants/index.ts+++ b/src/redux/constants/index.ts@@ -414,3 +414,7 @@ export const SSO_ACTIONS = Object.freeze({LINK: 'link',AUTH: 'auth',})++export const SOCIALISATIONS = Object.freeze({+ GOOGLE: 'google',+})diff --git a/src/redux/models/IUser.ts b/src/redux/models/IUser.tsindex 77c65f80b..0a282d36c 100644--- a/src/redux/models/IUser.ts+++ b/src/redux/models/IUser.ts@@ -1,32 +1,34 @@import { ISharedProject } from './ISharedProject'export interface IUser {- id: string- roles: string[]- planCode: string- nickname: string- email: string- isActive: boolean- trialEndDate: string- reportFrequency: string- emailRequests: number- created: string- updated: string- evWarningSentOn: string | null- exportedAt: string- subID: string | null- subUpdateURL: string | null- subCancelURL: string | null- timezone: string- theme: string | null- isTwoFactorAuthenticationEnabled: boolean- trialReminderSent: boolean- billingFrequency: string | null- nextBillDate: string | null- cancellationEffectiveDate: string | null- apiKey: string | null- telegramChatId: string | null- isTelegramChatIdConfirmed: boolean- timeFormat: string- sharedProjects: ISharedProject[]+ id: string+ roles: string[]+ planCode: string+ nickname: string+ email: string+ isActive: boolean+ trialEndDate: string+ reportFrequency: string+ emailRequests: number+ created: string+ updated: string+ evWarningSentOn: string | null+ exportedAt: string+ subID: string | null+ subUpdateURL: string | null+ subCancelURL: string | null+ timezone: string+ theme: string | null+ isTwoFactorAuthenticationEnabled: boolean+ trialReminderSent: boolean+ billingFrequency: string | null+ nextBillDate: string | null+ cancellationEffectiveDate: string | null+ apiKey: string | null+ telegramChatId: string | null+ isTelegramChatIdConfirmed: boolean+ timeFormat: string+ sharedProjects: ISharedProject[]+ registeredWithGoogle: boolean+ googleId: string | null}diff --git a/src/redux/reducers/auth.ts b/src/redux/reducers/auth.tsindex 74fd76c50..9d0db4e68 100644--- a/src/redux/reducers/auth.ts+++ b/src/redux/reducers/auth.ts@@ -9,12 +9,12 @@ import { FREE_TIER_KEY, isSelfhosted } from '../constants'import { ISharedProject } from '../models/ISharedProject'interface IAuthState {- user: IUser- redirectPath: string | null- authenticated: boolean- loading: boolean- dontRemember: boolean- isPaidTierUsed: boolean+ user: IUser+ redirectPath: string | null+ authenticated: boolean+ loading: boolean+ dontRemember: boolean+ isPaidTierUsed: boolean}const initialState: IAuthState = {diff --git a/src/redux/sagas/actions/index.ts b/src/redux/sagas/actions/index.tsindex 3d39c6213..a3bf89e0c 100644--- a/src/redux/sagas/actions/index.ts+++ b/src/redux/sagas/actions/index.ts@@ -50,6 +50,22 @@ const authSSO = (dontRemember: boolean, t: (key: string) => string = () => '', c},})+// currently only google is supported, in future we should provide a variable specifying the provider+const linkSSO = (t: (key: string) => string = () => '', callback: (res: any) => void = () => { }, provider = 'google') => ({+ type: types.LINK_SSO,+ payload: {+ callback, t, provider,+ },+})++// currently only google is supported, in future we should provide a variable specifying the provider+const unlinkSSO = (t: (key: string) => string = () => '', callback: (res: any) => void = () => { }, provider = 'google') => ({+ type: types.UNLINK_SSO,+ payload: {+ callback, t, provider,+ },+})+const signupAsync = (data: {email: string,password: string,@@ -119,6 +135,8 @@ const sagaActions = {deleteAccountAsync,logout,shareVerifyAsync,+ linkSSO,+ unlinkSSO,}export default sagaActionsdiff --git a/src/redux/sagas/actions/types.ts b/src/redux/sagas/actions/types.tsindex c62f04e35..c631fe86c 100644--- a/src/redux/sagas/actions/types.ts+++ b/src/redux/sagas/actions/types.ts@@ -11,6 +11,8 @@ const sagaTypes = Object.freeze({SHARE_VERIFY_ASYNC: 'SHARE_VERIFY_ASYNC',LOGOUT: 'LOGOUT',AUTH_SSO: 'AUTH_SSO',+ LINK_SSO: 'LINK_SSO',+ UNLINK_SSO: 'UNLINK_SSO',})export default sagaTypesdiff --git a/src/redux/sagas/auth/watchers/index.ts b/src/redux/sagas/auth/watchers/index.tsindex e5a4ef8f6..863adf079 100644--- a/src/redux/sagas/auth/watchers/index.ts+++ b/src/redux/sagas/auth/watchers/index.ts@@ -6,6 +6,8 @@ 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 ssoLink from 'redux/sagas/auth/workers/sso_link'+import ssoUnlink from 'redux/sagas/auth/workers/sso_unlink'import sagaTypes from '../../actions/types'function* watchLogin() {@@ -43,10 +45,21 @@ function* watchAuthSSO() {yield takeLatest(sagaTypes.AUTH_SSO, ssoAuth)}+function* watchLinkSSO() {+ // @ts-ignore+ yield takeLatest(sagaTypes.LINK_SSO, ssoLink)+}++function* watchUnlinkSSO() {+ // @ts-ignore+ yield takeLatest(sagaTypes.UNLINK_SSO, ssoUnlink)+}+export default function* watchAuth() {yield all([call(watchLogin), call(watchSignup), call(watchVerifyEmail),call(watchUpdateUserProfile), call(watchDeleteUserProfile),- call(watchLogout), call(watchAuthSSO),+ call(watchLogout), call(watchAuthSSO), call(watchLinkSSO),+ call(watchUnlinkSSO),])}diff --git a/src/redux/sagas/auth/workers/sso_link.ts b/src/redux/sagas/auth/workers/sso_link.tsindex 70b786d12..641148a7f 100644--- a/src/redux/sagas/auth/workers/sso_link.ts+++ b/src/redux/sagas/auth/workers/sso_link.ts@@ -1 +1,78 @@-// TODO+import { call, put, delay } from 'redux-saga/effects'++import { authActions } from 'redux/reducers/auth'+import { errorsActions } from 'redux/reducers/errors'+import { alertsActions } from 'redux/reducers/alerts'+import {+ linkByGoogleHash, generateGoogleAuthURL, authMe,+} from 'api'+import { openBrowserWindow } from 'utils/generic'++const AUTH_WINDOW_WIDTH = 600+const AUTH_WINDOW_HEIGHT = 800++const HASH_CHECK_FREQUENCY = 1000 // 1 second++export interface ISSOLink {+ payload: {+ callback: (isSuccess: boolean) => void+ t: (key: string) => string+ }+}++export default function* ssoLink({ payload: { callback, t } }: ISSOLink) {+ const authWindow = openBrowserWindow('', AUTH_WINDOW_WIDTH, AUTH_WINDOW_HEIGHT)++ if (!authWindow) {+ yield put(errorsActions.loginFailed({+ message: t('apiNotifications.socialisationGenericError'),+ }))+ callback(false)+ return+ }++ try {+ const { uuid, auth_url: authUrl } = yield call(generateGoogleAuthURL)++ // 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 {+ yield call(linkByGoogleHash, uuid)+ authWindow.close()++ // @ts-ignore+ const user = yield call(authMe)+ yield put(authActions.loginSuccessful(user))++ yield put(alertsActions.generateAlerts({+ message: t('apiNotifications.socialAccountLinked'),+ type: 'success',+ }))++ callback(true)+ return+ } catch (reason) {+ // Authentication is not finished yet+ }+ if (authWindow.closed) {+ callback(false)+ return+ }+ }+ } catch (reason) {+ yield put(errorsActions.loginFailed({+ message: t('apiNotifications.socialisationGenericError'),+ }))+ callback(false)+ }+}diff --git a/src/redux/sagas/auth/workers/sso_unlink.ts b/src/redux/sagas/auth/workers/sso_unlink.tsnew file mode 100644index 000000000..d30ce497f--- /dev/null+++ b/src/redux/sagas/auth/workers/sso_unlink.ts@@ -0,0 +1,47 @@+import { call, put } from 'redux-saga/effects'+import _values from 'lodash/values'+import _includes from 'lodash/includes'++import { authActions } from 'redux/reducers/auth'+import { errorsActions } from 'redux/reducers/errors'+import { alertsActions } from 'redux/reducers/alerts'+import {+ unlinkGoogle, authMe,+} from 'api'+import { SOCIALISATIONS } from 'redux/constants'++export interface ISSOUnlink {+ payload: {+ provider: string+ t: (key: string) => string+ callback: (isSuccess: boolean) => void+ }+}++export default function* ssoUnlink({ payload: { provider, t, callback } }: ISSOUnlink) {+ if (!_includes(_values(SOCIALISATIONS), provider)) {+ callback(false)+ return+ }++ try {+ if (provider === SOCIALISATIONS.GOOGLE) {+ yield call(unlinkGoogle)+ }++ // @ts-ignore+ const user = yield call(authMe)+ yield put(authActions.loginSuccessful(user))++ yield put(alertsActions.generateAlerts({+ message: t('apiNotifications.socialAccountUninked'),+ type: 'success',+ }))+ callback(true)+ } catch (reason) {+ yield put(errorsActions.loginFailed({+ message: t('apiNotifications.socialisationUnlinkGenericError'),+ }))+ callback(false)+ }+}