Skip to content

Commit

Permalink
🛠 Before go to production 21/04 fixes (#2105)
Browse files Browse the repository at this point in the history
* Fix securirty issue

* Fix ensure badge is reachable

* Fix missing user name in mentions

* Fix channels bar load time and bold channels

* Fix search for start direct chat with user

* Fix #2083
  • Loading branch information
RomaricMourgues authored Apr 21, 2022
1 parent ccd6266 commit 75ccf10
Show file tree
Hide file tree
Showing 15 changed files with 81 additions and 56 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ public function generatePreview($filename, $file, $path, $ext, $entity = null)
$filetype === 'image/gif' ||
$filetype === 'image/x-icon' ||
$filetype === 'image/jpeg' ||
$filetype === 'image/svg+xml' ||
$filetype === 'image/tiff' ||
$filetype === 'image/webp' ||
$this->isImage($ext)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,11 @@ export class UserNotificationBadgeService implements UserNotificationBadgeServic
user: { id: channelMemberPk.user_id, server_request: true },
channel: { id: channelId, ...channelMemberPk },
};
const exists = await this.channelsService.members.get(channelMemberPk, context);
const exists =
(await this.channelsService.channels.get({
id: channelId,
..._.pick(channelMemberPk, "company_id", "workspace_id"),
})) && (await this.channelsService.members.get(channelMemberPk, context));
if (!exists) {
for (const badge of badges.getEntities()) {
if (badge.channel_id === channelId) this.removeUserChannelBadges(badge);
Expand All @@ -179,10 +183,15 @@ export class UserNotificationBadgeService implements UserNotificationBadgeServic
continue;
}
try {
const exists = await this.userService.workspaces.getUser({
workspaceId,
userId,
});
const exists =
(await this.userService.workspaces.get({
id: workspaceId,
company_id: companyId,
})) &&
(await this.userService.workspaces.getUser({
workspaceId,
userId,
}));
if (!exists) {
await this.channelsService.members.ensureUserNotInWorkspaceIsNotInChannel(
{ id: userId },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ export const DynamicComponent = ({
(data.full_width ? 'full_width ' : '')
}
defaultValue={data.content || ''}
placeholder={data.placeholder}
placeholder={data.placeholder || 'Write something...'}
onChange={(evt: any) => {
eventContainer.onAction(
'interactive_change',
Expand Down
12 changes: 11 additions & 1 deletion twake/frontend/src/app/components/ui/user-or-mail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,22 @@ const EmailRow = ({ email }: { email: string }): JSX.Element => {
const UserRow = ({ id }: { id: string }): JSX.Element => {
const user = useUser(id);

if (user) {
console.log(UsersService.getFullName(user));
} else {
console.log('user not found');
}

return user ? (
<>
<Col className="icon">
<Avatar size={20} src={UsersService.getThumbnail(user)} />
</Col>
<Col className="text" flex="auto">
<Col
className="text"
flex="auto"
style={{ overflow: 'auto', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}
>
<Text strong>{UsersService.getFullName(user)}</Text>
<Text>{user.email ? `, ${user.email}` : ''}</Text>
</Col>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useState, useEffect } from 'react';
import React, { useState, useEffect, useRef } from 'react';
import { Button, Col, Row, Typography } from 'antd';
import classNames from 'classnames';
import TrashIcon from '@material-ui/icons/DeleteOutlined';
Expand Down Expand Up @@ -30,13 +30,18 @@ const UserListManager = (props: PropsType) => {
const [input, setInput] = useState<string>('');
const [editing, setEditing] = useState<boolean>(props.autoFocus ? props.autoFocus : false);
const [usersIds, setUsersIds] = useState<string[]>([...props.users]);
const callback = useRef<Function>(() => {});
let savedUserProps: string;

useEffect(() => {
updateStateFromProps(props, true);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

useEffect(() => {
callback.current(result.map(u => u.id));
}, [result]);

const updateStateFromProps = (props: PropsType, force?: boolean) => {
let anti_duplicates: string[] = [];

Expand All @@ -54,23 +59,25 @@ const UserListManager = (props: PropsType) => {
}
};

const filter = (text: string, callback: (arr: any[]) => any) => {
const filter = (text: string, cb: (arr: any[]) => any) => {
setInput(text);
if ((text || '').indexOf('@') > 0) {
if (
props.allowMails &&
Strings.verifyMail(text) &&
usersIds.indexOf(text.toLocaleLowerCase()) < 0
) {
callback([{ email: text.toLocaleLowerCase() }]);
cb([{ email: text.toLocaleLowerCase() }]);
return;
}
callback([]);
cb([]);
return;
}

search(text);
callback([...result.map(u => u.id)]);
const tmp = search(text);
cb([...tmp.map(u => u.id)]);

callback.current = cb;
};

const renderLine = (item: any, added?: boolean): JSX.Element => {
Expand Down Expand Up @@ -139,7 +146,7 @@ const UserListManager = (props: PropsType) => {
<div className={'users-list no-background'}>
{usersIds.map((item: string, index: number) => (
<div key={index} style={props.collapsed ? { display: 'inline-block' } : {}}>
<Row align="middle" gutter={[8, 8]}>
<Row align="middle" gutter={[8, 8]} style={{ flexFlow: 'nowrap' }}>
{renderLine(item, true)}
</Row>
</div>
Expand Down Expand Up @@ -182,7 +189,7 @@ const UserListManager = (props: PropsType) => {
}
render={(user: UserType) => (
<React.Suspense fallback={<></>}>
<Row align="middle" gutter={[8, 8]}>
<Row align="middle" gutter={[8, 8]} style={{ flexFlow: 'nowrap' }}>
<UserOrMail item={user} />
</Row>
</React.Suspense>
Expand Down
3 changes: 2 additions & 1 deletion twake/frontend/src/app/deprecated/user/CurrentUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import JWTStorage from 'app/features/auth/jwt-storage-service';
import Globals from 'app/features/global/services/globals-twake-app-service';
import { useCurrentUser } from 'app/features/users/hooks/use-current-user';
import UserAPIClient from '../../features/users/api/user-api-client';
import { getUser } from 'app/features/users/hooks/use-user-list';

class CurrentUser extends Observable {
loading: boolean;
Expand Down Expand Up @@ -48,7 +49,7 @@ class CurrentUser extends Observable {
start() {}

get() {
return Collections.get('users').find(Login.currentUserId);
return getUser(Login.currentUserId);
}

updateUserStatus = (newStatus: string[]) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ import { useRecoilCallback, useRecoilState } from 'recoil';
import { AtomMessageKey, MessageState } from '../state/atoms/messages';
import { NodeMessage, NodeMessageSubType, ReactionType } from 'app/features/messages/types/message';
import { messageToMessageWithReplies } from '../utils/message-with-replies';
import { UserState } from 'app/features/users/state/atoms/user';
import { setUserList, useSetUserList } from 'app/features/users/hooks/use-user-list';
import { UserListState } from 'app/features/users/state/atoms/user-list';
import { useSetUserList } from 'app/features/users/hooks/use-user-list';

export const useMessage = (partialKey: AtomMessageKey) => {
const key = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import UserAPIClient, { SearchContextType } from '../api/user-api-client';
import { delayRequest } from 'app/features/global/utils/managedSearchRequest';
import Strings from 'app/features/global/utils/strings';
import useRouterWorkspace from 'app/features/router/hooks/use-router-workspace';
import _ from 'lodash';

export const searchBackend = async (
query: string | undefined,
Expand Down Expand Up @@ -102,16 +103,19 @@ export const useSearchUserList = ({
}: {
scope: SearchContextType['scope'];
}): {
search: (str?: string) => void;
search: (str?: string) => UserType[];
result: UserType[];
} => {
const { set: setUserList } = useSetUserList('use-search-user-list');
const [query, setQuery] = useState<string | undefined>();
const { userList } = useUserList();
let { userList } = useUserList();
userList = _.uniqBy(userList, 'id');

const companyId = useRouterCompany();
const workspaceId = useRouterWorkspace();
const search = async (str?: string) => {
const search = (str?: string) => {
setQuery(str);
return searchFrontend(str, { workspaceId, scope, companyId, userList: userList || [] });
};

useEffect(() => {
Expand Down
5 changes: 4 additions & 1 deletion twake/frontend/src/app/features/users/hooks/use-user-list.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import { useEffect } from 'react';
import { cloneDeep, concat, isEqual, uniqBy } from 'lodash';
import { RecoilState, useRecoilCallback, useRecoilValueLoadable } from 'recoil';
import { useRecoilCallback, useRecoilValueLoadable } from 'recoil';

import useRouterCompany from 'app/features/router/hooks/use-router-company';
import useRouterWorkspace from 'app/features/router/hooks/use-router-workspace';
import { UserCompanyType, UserType, UserWorkspaceType } from 'app/features/users/types/user';
import WorkspaceUserAPIClient from 'app/features/workspace-members/api/workspace-members-api-client';
import { UserListState } from '../state/atoms/user-list';
import Logger from 'app/features/global/framework/logger-service';
import Collections from 'app/deprecated/CollectionsV1/Collections/Collections';
import _ from 'lodash';

export const usePreloadSomeUsers = () => {
const companyId = useRouterCompany();
Expand Down Expand Up @@ -84,6 +86,7 @@ export function useSetUserList(key: string) {

if (currentList && newList && !isEqual(currentList, newList)) {
set(UserListState, newList);
newList.forEach(user => Collections.get('users').completeObject(_.cloneDeep(user)));
currentUserList = newList;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import Languages from 'app/features/global/services/languages-service';
import { UserType } from 'app/features/users/types/user';
import { TwakeService } from 'app/features/global/framework/registry-decorator-service';
import { addApiUrlIfNeeded, getAsFrontUrl } from 'app/features/global/utils/URLUtils';
import { getUser } from '../hooks/use-user-list';

type SearchQueryType = {
searching: boolean;
Expand All @@ -29,7 +30,7 @@ class User {
}

getCurrentUser(): UserType & { id: string } {
return Collections.get('users').find(Login.currentUserId);
return getUser(Login.currentUserId) as UserType & { id: string };
}

getCurrentUserId(): string {
Expand All @@ -45,14 +46,9 @@ class User {

if (user.deleted) {
name = Languages.t('general.user.deleted');
}

if (user.first_name?.length) {
name = user.first_name;
}

if (user.first_name?.length && user.last_name?.length) {
name = `${user.first_name} ${user.last_name}`;
} else {
name = [user.first_name, user.last_name].filter(a => a).join(' ');
name = name || user.username;
}

return name.charAt(0).toUpperCase() + name.slice(1);
Expand Down
18 changes: 0 additions & 18 deletions twake/frontend/src/app/features/users/state/atoms/user.ts

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import classNames from 'classnames';
import { MessageContext } from '../message-with-replies';
import { useMessage } from 'app/features/messages/hooks/use-message';
import _ from 'lodash';
import { getUser } from 'app/features/users/hooks/use-user-list';

export default () => {
const context = useContext(MessageContext);
Expand Down Expand Up @@ -64,7 +65,7 @@ const Reaction = ({
const ReactionTooltip = ({ users }: { users: ReactionType['users'] }): JSX.Element => (
<>
{users.map(id => {
const user = Collections.get('users').find(id);
const user = getUser(id);

if (!user) return <></>;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { useDirectChannels } from 'app/features/channels/hooks/use-direct-channe
export default () => {
const { companyId } = RouterServices.getStateFromRoute();
let { directChannels } = useDirectChannels();
let [max, setMax] = useState(20);

const openConv = () => {
return MediumPopupComponent.open(<NewDirectMessagesPopup />, {
Expand All @@ -36,6 +37,10 @@ export default () => {
return <></>;
}

const nonfavoriteDirectChannels = directChannels.filter(
channel => !channel.user_member?.favorite,
);

return (
<div className="users_channels">
<ChannelCategory
Expand All @@ -50,17 +55,25 @@ export default () => {
)}
onAdd={AccessRightsService.hasCompanyLevel(companyId, 'member') ? () => openConv() : null}
/>
{directChannels
.filter(channel => !channel.user_member?.favorite)
{nonfavoriteDirectChannels
.sort(
(a, b) =>
(parseInt(b.last_activity?.toString() || '') || 0) -
(parseInt(a.last_activity?.toString() || '') || 0),
)
.slice(0, max)
.map(channel => {
return <ChannelIntermediate key={channel.id} channel={channel} />;
})}

{max < nonfavoriteDirectChannels.length && (
<div style={{ textAlign: 'center' }}>
<a href="#" onClick={() => setMax(max + 20)}>
Load more...
</a>
</div>
)}

{directChannels.length === 0 && (
<div className="channel_small_text">
{Languages.t(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,10 @@ export default (props: Props): JSX.Element => {
: { avatar: '', name: '' };

const unreadMessages =
(channel.last_activity || 0) !== 0 &&
(channel.last_activity || 0) > (channel?.user_member?.last_access || 0) &&
channel.last_message?.sender !== channel.user_member?.user_id;
channel.last_message?.sender !== channel.user_member?.user_id &&
!(isDirectChannel && notifications.length === 0);

const channelIcon = isDirectChannel ? avatar : channel.icon || '';
const channelName = isDirectChannel ? name : channel.name || '';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ export default () => {
onClick={async () => {
setLoading(true);
await WorkspaceAPIClient.delete(workspace.company_id, workspace.id);
(window as any).location.reload();
(window as any).location.replace('/');
setLoading(false);
ModalManager.close();
}}
Expand Down

0 comments on commit 75ccf10

Please sign in to comment.