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

feat: Fetch avatars using user id #33214

Draft
wants to merge 12 commits into
base: develop
Choose a base branch
from
5 changes: 5 additions & 0 deletions .changeset/plenty-snakes-dream.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@rocket.chat/meteor": minor
---

Added a new route to allow fetching avatars by the user's id `/avatar/uid/<UserID>`
5 changes: 3 additions & 2 deletions apps/meteor/server/routes/avatar/index.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { WebApp } from 'meteor/webapp';

import { roomAvatar } from './room';
import { userAvatar } from './user';
import { userAvatarByUsername, userAvatarById } from './user';

import './middlewares';

WebApp.connectHandlers.use('/avatar/room/', roomAvatar);
WebApp.connectHandlers.use('/avatar/', userAvatar);
WebApp.connectHandlers.use('/avatar/uid/', userAvatarById);
WebApp.connectHandlers.use('/avatar/', userAvatarByUsername);
22 changes: 0 additions & 22 deletions apps/meteor/server/routes/avatar/middlewares/auth.js

This file was deleted.

47 changes: 47 additions & 0 deletions apps/meteor/server/routes/avatar/middlewares/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import type { ServerResponse } from 'http';

import type { IIncomingMessage } from '@rocket.chat/core-typings';
import type { NextFunction } from 'connect';

import { userCanAccessAvatar, renderSVGLetters } from '../utils';

const renderFallback = (req: IIncomingMessage, res: ServerResponse) => {
if (!req.url) {
res.writeHead(404);
res.end();
return;
}

let roomOrUsername;

if (req.url.startsWith('/room')) {
roomOrUsername = req.url.split('/')[2] || 'Room';
} else {
roomOrUsername = req.url.split('/')[1] || 'Anonymous';
}

res.writeHead(200, { 'Content-Type': 'image/svg+xml' });
res.write(renderSVGLetters(roomOrUsername, 200));
res.end();
};

const getProtectAvatars = (callback?: typeof renderFallback) => async (req: IIncomingMessage, res: ServerResponse, next: NextFunction) => {
if (!(await userCanAccessAvatar(req))) {
if (callback) {
callback(req, res);
return;
}

res.writeHead(404);
res.end();
return;
}

return next();
};

// If unauthorized returns the SVG fallback (letter avatar)
export const protectAvatarsWithFallback = getProtectAvatars(renderFallback);

// Just returns 404
export const protectAvatars = getProtectAvatars();
5 changes: 3 additions & 2 deletions apps/meteor/server/routes/avatar/middlewares/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { WebApp } from 'meteor/webapp';

import { protectAvatars } from './auth';
import { protectAvatars, protectAvatarsWithFallback } from './auth';

import './browserVersion';

WebApp.connectHandlers.use('/avatar/', protectAvatars);
WebApp.connectHandlers.use('/avatar/', protectAvatarsWithFallback);
WebApp.connectHandlers.use('/avatar/uid/', protectAvatars);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For users without permission to access the avatar, this will treat the uid as an username and render its first digit as an avatar. I don't know if that is an OK behavior?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I made another function for this specific case. Thanks for pointing this out, I took the function name at face value.

4 changes: 2 additions & 2 deletions apps/meteor/server/routes/avatar/room.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Cookies } from 'meteor/ostrio:cookies';

import { FileUpload } from '../../../app/file-upload/server';
import { roomCoordinator } from '../../lib/rooms/roomCoordinator';
import { renderSVGLetters, serveAvatar, wasFallbackModified, setCacheAndDispositionHeaders } from './utils';
import { renderSVGLetters, serveSvgAvatarInRequestedFormat, wasFallbackModified, setCacheAndDispositionHeaders } from './utils';

const MAX_ROOM_SVG_AVATAR_SIZE = 1024;
const MIN_ROOM_SVG_AVATAR_SIZE = 16;
Expand Down Expand Up @@ -74,5 +74,5 @@ export const roomAvatar = async function (req, res /* , next*/) {

const svg = renderSVGLetters(roomName, avatarSize);

return serveAvatar(svg, req.query.format, res);
return serveSvgAvatarInRequestedFormat(svg, req.query.format, res);
};
84 changes: 0 additions & 84 deletions apps/meteor/server/routes/avatar/user.js

This file was deleted.

169 changes: 169 additions & 0 deletions apps/meteor/server/routes/avatar/user.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
import type { ServerResponse } from 'http';

import type { IUpload, IIncomingMessage } from '@rocket.chat/core-typings';
import { Avatars, Users } from '@rocket.chat/models';
import { serverFetch as fetch } from '@rocket.chat/server-fetch';
import type { NextFunction } from 'connect';

import { FileUpload } from '../../../app/file-upload/server';
import { settings } from '../../../app/settings/server';
import { renderSVGLetters, serveSvgAvatarInRequestedFormat, wasFallbackModified, setCacheAndDispositionHeaders } from './utils';

const MAX_USER_SVG_AVATAR_SIZE = 1024;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This same constants are in /room.js file, maybe we can put them in a place both files can access?

const MIN_USER_SVG_AVATAR_SIZE = 16;

const serveSvgAvatar = (nameOrUsername: string, size: number, format: string, res: ServerResponse) => {
const svg = renderSVGLetters(nameOrUsername, size);
serveSvgAvatarInRequestedFormat(svg, format, res);
};

const getAvatarSizeFromRequest = (req: IIncomingMessage) => {
const requestSize = req.query.size && parseInt(req.query.size);
return Math.min(Math.max(requestSize, MIN_USER_SVG_AVATAR_SIZE), MAX_USER_SVG_AVATAR_SIZE);
};

const serveAvatarFile = (file: IUpload, req: IIncomingMessage, res: ServerResponse, next: NextFunction) => {
res.setHeader('Content-Security-Policy', "default-src 'none'");
const reqModifiedHeader = req.headers['if-modified-since'];

if (reqModifiedHeader && reqModifiedHeader === file.uploadedAt?.toUTCString()) {
res.setHeader('Last-Modified', reqModifiedHeader);
res.writeHead(304);
res.end();
return;
}

res.setHeader('Last-Modified', `${file.uploadedAt?.toUTCString()}`);
res.setHeader('Content-Type', file.type || '');
res.setHeader('Content-Length', file.size || 0);

return FileUpload.get(file, req, res, next);
};

const handleExternalProvider = async (externalProviderUrl: string, username: string, res: ServerResponse): Promise<boolean> => {
const response = await fetch(externalProviderUrl.replace('{username}', username));
response.headers.forEach((value, key) => res.setHeader(key, value));
response.body.pipe(res);
return true;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The 2 places where this is called don't care about the return value, we can omit the return and make the func return void

};

// request /avatar/@name forces returning the svg
export const userAvatarByUsername = async function (req: IIncomingMessage, res: ServerResponse, next: NextFunction) {
if (!req.url) {
return;
}

const requestUsername = decodeURIComponent(req.url?.substr(1).replace(/\?.*$/, ''));

if (!requestUsername) {
res.writeHead(404);
res.end();
return;
}

setCacheAndDispositionHeaders(req, res);

const externalProviderUrl = settings.get<string>('Accounts_AvatarExternalProviderUrl');
if (externalProviderUrl) {
void handleExternalProvider(externalProviderUrl, requestUsername, res);
return;
}

const avatarSize = getAvatarSizeFromRequest(req);
// if request starts with @ always return the svg letters
if (requestUsername[0] === '@') {
serveSvgAvatar(requestUsername.slice(1), avatarSize, req.query.format, res);
return;
}

const file = await Avatars.findOneByName(requestUsername);
if (file) {
void serveAvatarFile(file, req, res, next);
return;
}

// if still using "letters fallback"
if (!wasFallbackModified(req.headers['if-modified-since'])) {
res.writeHead(304);
res.end();
return;
}

// Use real name for SVG letters
if (settings.get('UI_Use_Name_Avatar')) {
const user = await Users.findOneByUsernameIgnoringCase(requestUsername, {
projection: {
name: 1,
},
});

if (user?.name) {
serveSvgAvatar(user.name, avatarSize, req.query.format, res);
return;
}
}

serveSvgAvatar(requestUsername, avatarSize, req.query.format, res);
};

// This handler wont support `@` to force SVG letters
export const userAvatarById = async function (req: IIncomingMessage, res: ServerResponse, next: NextFunction) {
if (!req.url) {
return;
}

const requestUserId = decodeURIComponent(req.url?.substr(1).replace(/\?.*$/, ''));

if (!requestUserId) {
res.writeHead(404);
res.end();
return;
}

setCacheAndDispositionHeaders(req, res);

const externalProviderUrl = settings.get<string>('Accounts_AvatarExternalProviderUrl');
if (externalProviderUrl) {
const user = await Users.findOneById(requestUserId, { projection: { username: 1, name: 1 } });
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
const user = await Users.findOneById(requestUserId, { projection: { username: 1, name: 1 } });
const user = await Users.findOneById<Pick<...>>(requestUserId, { projection: { username: 1, name: 1 } });


if (!user?.username) {
res.writeHead(404);
res.end();
return;
}

void handleExternalProvider(externalProviderUrl, user.username, res);
return;
}

const file = await Avatars.findOne({ userId: requestUserId });
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we maybe create a findOneByUserId func inside the model?

if (file) {
void serveAvatarFile(file, req, res, next);
return;
}

const user = await Users.findOneById(requestUserId, { projection: { username: 1, name: 1 } });
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
const user = await Users.findOneById(requestUserId, { projection: { username: 1, name: 1 } });
const user = await Users.findOneById<Pick<...>>(requestUserId, { projection: { username: 1, name: 1 } });


if (!user?.username) {
res.writeHead(404);
res.end();
return;
}

// if still using "letters fallback"
if (!wasFallbackModified(req.headers['if-modified-since'])) {
res.writeHead(304);
res.end();
return;
}

const avatarSize = getAvatarSizeFromRequest(req);

// Use real name for SVG letters
if (settings.get('UI_Use_Name_Avatar') && user?.name) {
serveSvgAvatar(user.name, avatarSize, req.query.format, res);
return;
}

serveSvgAvatar(user.username, avatarSize, req.query.format, res);
};
2 changes: 1 addition & 1 deletion apps/meteor/server/routes/avatar/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const FALLBACK_LAST_MODIFIED = 'Thu, 01 Jan 2015 00:00:00 GMT';

const cookie = new Cookies();

export const serveAvatar = (avatar, format, res) => {
export const serveSvgAvatarInRequestedFormat = (avatar, format, res) => {
res.setHeader('Last-Modified', FALLBACK_LAST_MODIFIED);

if (['png', 'jpg', 'jpeg'].includes(format)) {
Expand Down
Loading