Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chore: create roomNameExists endpoint #26386

Merged
merged 18 commits into from
Aug 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion apps/meteor/app/api/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ import './v1/misc';
import './v1/permissions';
import './v1/push';
import './v1/roles';
import './v1/rooms';
import './v1/rooms.js';
import './v1/rooms.ts';
import './v1/settings';
import './v1/stats';
import './v1/subscriptions';
Expand Down
39 changes: 39 additions & 0 deletions apps/meteor/app/api/server/v1/rooms.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { Meteor } from 'meteor/meteor';
import Ajv from 'ajv';

import { API } from '../api';

// TO-DO: Replace this instance by only one Ajv import
const ajv = new Ajv({ coerceTypes: true });

type GETRoomsNameExists = {
roomName: string;
};

const GETRoomsNameExistsSchema = {
type: 'object',
properties: {
roomName: {
type: 'string',
},
},
required: ['roomName'],
additionalProperties: false,
};

export const isGETRoomsNameExists = ajv.compile<GETRoomsNameExists>(GETRoomsNameExistsSchema);

API.v1.addRoute(
'rooms.nameExists',
{
authRequired: true,
validateParams: isGETRoomsNameExists,
},
{
get() {
const { roomName } = this.queryParams;

return API.v1.success({ exists: Meteor.call('roomNameExists', roomName) });
},
},
);
9 changes: 5 additions & 4 deletions apps/meteor/client/sidebar/header/CreateChannel.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Box, Modal, ButtonGroup, Button, TextInput, Icon, Field, ToggleSwitch, FieldGroup } from '@rocket.chat/fuselage';
import { useDebouncedCallback } from '@rocket.chat/fuselage-hooks';
import { useSetting, useMethod, useTranslation, TranslationKey } from '@rocket.chat/ui-contexts';
import { useSetting, useTranslation, TranslationKey, useEndpoint } from '@rocket.chat/ui-contexts';
import React, { ReactElement, useEffect, useMemo, useState } from 'react';

import { useHasLicenseModule } from '../../../ee/client/hooks/useHasLicenseModule';
Expand Down Expand Up @@ -61,7 +61,7 @@ const CreateChannel = ({
const namesValidation = useSetting('UTF8_Channel_Names_Validation');
const allowSpecialNames = useSetting('UI_Allow_room_names_with_special_chars');
const federationEnabled = useSetting('Federation_Matrix_enabled');
const channelNameExists = useMethod('roomNameExists');
const channelNameExists = useEndpoint('GET', '/v1/rooms.nameExists');

const channelNameRegex = useMemo(() => new RegExp(`^${namesValidation}$`), [namesValidation]);

Expand All @@ -83,8 +83,9 @@ const CreateChannel = ({
if (!allowSpecialNames && !channelNameRegex.test(name)) {
return setNameError(t('error-invalid-name'));
}
const isNotAvailable = await channelNameExists(name);
if (isNotAvailable) {
const { exists } = await channelNameExists({ roomName: name });

if (exists) {
return setNameError(t('Channel_already_exist', name));
}
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { IUser } from '@rocket.chat/core-typings';
import { useMutableCallback, useDebouncedCallback } from '@rocket.chat/fuselage-hooks';
import { useSetting, usePermission, useMethod, useTranslation } from '@rocket.chat/ui-contexts';
import { useSetting, usePermission, useTranslation, useEndpoint } from '@rocket.chat/ui-contexts';
import { useCallback, useEffect, useMemo, useState } from 'react';

import { useEndpointActionExperimental } from '../../../hooks/useEndpointActionExperimental';
Expand Down Expand Up @@ -70,7 +70,8 @@ export const useCreateTeamModalState = (onClose: () => void): CreateTeamModalSta

const [nameError, setNameError] = useState<string>();

const teamNameExists = useMethod('roomNameExists');
const teamNameExists = useEndpoint('GET', '/v1/rooms.nameExists');
// const teamNameExists = useMethod('roomNameExists');

const checkName = useDebouncedCallback(
async (name: string) => {
Expand All @@ -90,7 +91,7 @@ export const useCreateTeamModalState = (onClose: () => void): CreateTeamModalSta
return;
}

const isNotAvailable = await teamNameExists(name);
const isNotAvailable = await teamNameExists({ roomName: name });
if (isNotAvailable) {
setNameError(t('Teams_Errors_team_name', { name }));
}
Expand Down
18 changes: 0 additions & 18 deletions apps/meteor/server/methods/roomNameExists.js

This file was deleted.

26 changes: 26 additions & 0 deletions apps/meteor/server/methods/roomNameExists.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Meteor } from 'meteor/meteor';
import { check } from 'meteor/check';

import { Rooms } from '../../app/models/server';
import { methodDeprecationLogger } from '../../app/lib/server/lib/deprecationWarningLogger';

Meteor.methods({
roomNameExists(roomName) {
check(roomName, String);

methodDeprecationLogger.warn('roomNameExists will be deprecated in future versions of Rocket.Chat');

if (!Meteor.userId()) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'roomExists',
});
}
const room = Rooms.findOneByName(roomName);

if (room === undefined || room === null) {
return false;
}

return true;
},
});
52 changes: 52 additions & 0 deletions apps/meteor/tests/end-to-end/api/09-rooms.js
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,58 @@ describe('[Rooms]', function () {
});
});

describe('/rooms.nameExists', () => {
it('should return 401 unauthorized when user is not logged in', (done) => {
request
.get(api('rooms.nameExists'))
.expect('Content-Type', 'application/json')
.expect(401)
.expect((res) => {
expect(res.body).to.have.property('message');
})
.end(done);
});

// eslint-disable-next-line no-unused-vars
let testChannel;
const testChannelName = `channel.test.${Date.now()}-${Math.random()}`;
it('create an channel', (done) => {
createRoom({ type: 'c', name: testChannelName }).end((err, res) => {
testChannel = res.body.channel;
done();
});
});
it('should return true if this room name exists', (done) => {
request
.get(api('rooms.nameExists'))
.set(credentials)
.query({
roomName: testChannelName,
})
.expect(200)
.expect((res) => {
expect(res.body).to.have.property('success', true);
expect(res.body).to.have.property('exists', true);
})
.end(done);
});

it('should return an error when send an invalid room', (done) => {
request
.get(api('rooms.nameExists'))
.set(credentials)
.query({
roomId: 'foo',
})
.expect(400)
.expect((res) => {
expect(res.body).to.have.property('success', false);
expect(res.body).to.have.property('error');
})
.end(done);
});
});

describe('[/rooms.cleanHistory]', () => {
let publicChannel;
let privateChannel;
Expand Down
32 changes: 32 additions & 0 deletions packages/rest-typings/src/v1/rooms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -393,21 +393,25 @@ export type RoomsEndpoints = {
items: IRoom[];
};
};

'/v1/rooms.autocomplete.channelAndPrivate.withPagination': {
GET: (params: RoomsAutocompleteChannelAndPrivateWithPaginationProps) => PaginatedResult<{
items: IRoom[];
}>;
};

'/v1/rooms.autocomplete.availableForTeams': {
GET: (params: RoomsAutocompleteAvailableForTeamsProps) => {
items: IRoom[];
};
};

'/v1/rooms.info': {
GET: (params: RoomsInfoProps) => {
room: IRoom;
};
};

'/v1/rooms.cleanHistory': {
POST: (params: {
roomId: IRoom['_id'];
Expand All @@ -422,34 +426,41 @@ export type RoomsEndpoints = {
ignoreThreads?: boolean;
}) => { _id: IRoom['_id']; count: number; success: boolean };
};

'/v1/rooms.createDiscussion': {
POST: (params: RoomsCreateDiscussionProps) => {
discussion: IRoom;
};
};

'/v1/rooms.export': {
POST: (params: RoomsExportProps) => {
missing?: [];
success: boolean;
};
};

'/v1/rooms.adminRooms': {
GET: (params: RoomsAdminRoomsProps) => PaginatedResult<{ rooms: Pick<IRoom, RoomAdminFieldsType>[] }>;
};

'/v1/rooms.adminRooms.getRoom': {
GET: (params: RoomsAdminRoomsGetRoomProps) => Pick<IRoom, RoomAdminFieldsType>;
};

'/v1/rooms.saveRoomSettings': {
POST: (params: RoomsSaveRoomSettingsProps) => {
success: boolean;
rid: string;
};
};

'/v1/rooms.changeArchivationState': {
POST: (params: RoomsChangeArchivationStateProps) => {
success: boolean;
};
};

'/v1/rooms.upload/:rid': {
POST: (params: {
file: File;
Expand All @@ -462,6 +473,7 @@ export type RoomsEndpoints = {
tmid?: string;
}) => { message: IMessage };
};

'/v1/rooms.saveNotification': {
POST: (params: {
roomId: string;
Expand All @@ -478,4 +490,24 @@ export type RoomsEndpoints = {
success: boolean;
};
};

'/v1/rooms.favorite': {
POST: (
params:
| {
roomId: string;
favorite: boolean;
}
| {
roomName: string;
favorite: boolean;
},
) => void;
};

'/v1/rooms.nameExists': {
GET: (params: { roomName: string }) => {
exists: boolean;
};
};
};