chore: Add a check for data diff in setUser call (#1272)

This commit is contained in:
Pranav Raj S
2020-09-26 22:33:20 +05:30
committed by GitHub
parent 701eccb35c
commit dbd1720aeb
4 changed files with 114 additions and 9 deletions

View File

@@ -1,6 +1,31 @@
import Cookies from 'js-cookie';
import { IFrameHelper } from '../sdk/IFrameHelper';
import { getBubbleView } from '../sdk/bubbleHelpers';
import md5 from 'md5';
const ALLOWED_LIST_OF_SET_USER_ATTRIBUTES = ['avatar_url', 'email', 'name'];
export const getUserCookieName = () => {
const SET_USER_COOKIE_PREFIX = 'cw_user_';
const { websiteToken: websiteIdentifier } = window.$chatwoot;
return `${SET_USER_COOKIE_PREFIX}${websiteIdentifier}`;
};
export const getUserString = ({ identifier = '', user }) => {
const userStringWithSortedKeys = ALLOWED_LIST_OF_SET_USER_ATTRIBUTES.reduce(
(acc, key) => `${acc}${key}${user[key] || ''}`,
''
);
return `${userStringWithSortedKeys}identifier${identifier}`;
};
const computeHashForUserData = (...args) => md5(getUserString(...args));
export const hasUserKeys = user =>
ALLOWED_LIST_OF_SET_USER_ATTRIBUTES.reduce(
(acc, key) => acc || !!user[key],
false
);
const runSDK = ({ baseUrl, websiteToken }) => {
const chatwootSettings = window.chatwootSettings || {};
@@ -21,16 +46,30 @@ const runSDK = ({ baseUrl, websiteToken }) => {
},
setUser(identifier, user) {
if (typeof identifier === 'string' || typeof identifier === 'number') {
window.$chatwoot.identifier = identifier;
window.$chatwoot.user = user || {};
IFrameHelper.sendMessage('set-user', {
identifier,
user: window.$chatwoot.user,
});
} else {
if (typeof identifier !== 'string' && typeof identifier !== 'number') {
throw new Error('Identifier should be a string or a number');
}
if (!hasUserKeys()) {
throw new Error(
'User object should have one of the keys [avatar_url, email, name]'
);
}
const userCookieName = getUserCookieName();
const existingCookieValue = Cookies.get(userCookieName);
const hashToBeStored = computeHashForUserData({ identifier, user });
if (hashToBeStored === existingCookieValue) {
return;
}
window.$chatwoot.identifier = identifier;
window.$chatwoot.user = user;
IFrameHelper.sendMessage('set-user', { identifier, user });
Cookies.set(userCookieName, hashToBeStored, {
expires: 365,
sameSite: 'Lax',
});
},
setCustomAttributes(customAttributes = {}) {
@@ -69,6 +108,8 @@ const runSDK = ({ baseUrl, websiteToken }) => {
}
Cookies.remove('cw_conversation');
Cookies.remove(getUserCookieName());
const iframe = IFrameHelper.getAppFrame();
iframe.src = IFrameHelper.getUrl({
baseUrl: window.$chatwoot.baseUrl,