Skip to content

[AvatarController] Restrict UploadAvatar to current user #3839

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

Merged
merged 5 commits into from
Jun 5, 2025
Merged
Show file tree
Hide file tree
Changes from 3 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
63 changes: 57 additions & 6 deletions Backend.Tests/Controllers/AvatarControllerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ protected virtual void Dispose(bool disposing)
}

private User _jwtAuthenticatedUser = null!;
private const string FileName = "combine.png"; // File in Backend.Tests/Assets/
private readonly string _filePath = Path.Combine(Util.AssetsDir, FileName);

[SetUp]
public void Setup()
Expand All @@ -48,6 +50,7 @@ public void Setup()
_userRepo.Create(_jwtAuthenticatedUser);
_jwtAuthenticatedUser = _permissionService.Authenticate(_jwtAuthenticatedUser.Username,
_jwtAuthenticatedUser.Password).Result ?? throw new UserAuthenticationException();
_avatarController.ControllerContext.HttpContext.Request.Headers["UserId"] = _jwtAuthenticatedUser.Id;
}

/// <summary> Delete the image file stored on disk for a particular user. </summary>
Expand All @@ -62,19 +65,67 @@ private static void DeleteAvatarFile(string userId)
}

[Test]
public void TestAvatarImport()
public void TestDownloadAvatarNoUser()
{
const string fileName = "combine.png"; // file in Backend.Tests/Assets/
var filePath = Path.Combine(Util.AssetsDir, fileName);
using var stream = File.OpenRead(filePath);
var file = new FormFile(stream, 0, stream.Length, "dave", fileName);
var result = _avatarController.DownloadAvatar("false-user-id").Result;
Assert.That(result, Is.InstanceOf<NotFoundResult>());
}

[Test]
public void TestDownloadAvatarNoAvatar()
{
var result = _avatarController.DownloadAvatar(_jwtAuthenticatedUser.Id).Result;
Assert.That(result, Is.InstanceOf<NotFoundResult>());
}

[Test]
public void TestUploadAvatarUnauthorizedUser()
{
using var stream = File.OpenRead(_filePath);
var file = new FormFile(stream, 0, stream.Length, "formFileName", FileName);
_avatarController.ControllerContext.HttpContext = PermissionServiceMock.UnauthorizedHttpContext();

_ = _avatarController.UploadAvatar(_jwtAuthenticatedUser.Id, file).Result;
var result = _avatarController.UploadAvatar(file).Result;
Assert.That(result, Is.InstanceOf<ForbidResult>());
}

[Test]
public void TestUploadAudioFileNullFile()
{
var result = _avatarController.UploadAvatar(null).Result;
Assert.That(result, Is.InstanceOf<BadRequestObjectResult>());
}

[Test]
public void TestUploadAudioFileEmptyFile()
{
using var stream = File.OpenRead(_filePath);
// Use 0 for the third argument
Copy link

Choose a reason for hiding this comment

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

This looks forgotten or incomplete

var file = new FormFile(stream, 0, 0, "formFileName", FileName);

var result = _avatarController.UploadAvatar(file).Result;
Assert.That(result, Is.InstanceOf<BadRequestObjectResult>());
}

[Test]
public void TestUploadAvatarAndDownloadAvatar()
{
using var stream = File.OpenRead(_filePath);
var file = new FormFile(stream, 0, stream.Length, "formFileName", FileName);
var uploadResult = _avatarController.UploadAvatar(file).Result;
Assert.That(uploadResult, Is.TypeOf<OkResult>());

var foundUser = _userRepo.GetUser(_jwtAuthenticatedUser.Id).Result;
Assert.That(foundUser?.Avatar, Is.Not.Null);

// No permissions should be required to download an avatar.
_avatarController.ControllerContext.HttpContext = PermissionServiceMock.UnauthorizedHttpContext();

var fileResult = _avatarController.DownloadAvatar(_jwtAuthenticatedUser.Id).Result as FileStreamResult;
Assert.That(fileResult, Is.TypeOf<FileStreamResult>());

// Clean up.
fileResult!.FileStream.Dispose();
DeleteAvatarFile(_jwtAuthenticatedUser.Id);
}
}
Expand Down
22 changes: 13 additions & 9 deletions Backend/Controllers/AvatarController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,10 @@ public AvatarController(IUserRepository userRepo, IPermissionService permissionS

/// <summary> Get user's avatar on disk </summary>
/// <returns> Stream of local avatar file </returns>
[AllowAnonymous]
[HttpGet("download", Name = "DownloadAvatar")]
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(FileContentResult))]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> DownloadAvatar(string userId)
{
// SECURITY: Omitting authentication so the frontend can use the API endpoint directly as a URL.
Copy link

Choose a reason for hiding this comment

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

This comment feels somewhat superfluous with the method now explicitly being marked with [AllowAnonymous]

Expand All @@ -35,27 +37,28 @@ public async Task<IActionResult> DownloadAvatar(string userId)
// return Forbid();
// }

var user = await _userRepo.GetUser(userId, false);
var avatar = string.IsNullOrEmpty(user?.Avatar) ? null : user.Avatar;

if (avatar is null)
var avatar = (await _userRepo.GetUser(userId, false))?.Avatar;
if (string.IsNullOrEmpty(avatar))
{
return NotFound(userId);
return NotFound();
}

var imageFile = System.IO.File.OpenRead(avatar);
return File(imageFile, "application/octet-stream");
}

/// <summary>
/// Adds an avatar image to a <see cref="User"/> and saves locally to ~/.CombineFiles/{ProjectId}/Avatars
/// Adds an avatar image to current <see cref="User"/> and saves locally to ~/.CombineFiles/{ProjectId}/Avatars
/// </summary>
/// <returns> Path to local avatar file </returns>
[HttpPost("upload", Name = "UploadAvatar")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<IActionResult> UploadAvatar(string userId, IFormFile? file)
[ProducesResponseType(StatusCodes.Status400BadRequest, Type = typeof(string))]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> UploadAvatar(IFormFile? file)
{
if (!_permissionService.IsUserIdAuthorized(HttpContext, userId))
if (!_permissionService.IsCurrentUserAuthorized(HttpContext))
Copy link

Choose a reason for hiding this comment

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

It's intriguing to me that this isn't already handled via the [Authorize] attribute on the controller.
But that's outside the scope of this PR.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

It may be superfluous. I'll look into that, thank you.

{
return Forbid();
}
Expand All @@ -72,10 +75,11 @@ public async Task<IActionResult> UploadAvatar(string userId, IFormFile? file)
}

// Get user to apply avatar to.
var userId = _permissionService.GetUserId(HttpContext);
var user = await _userRepo.GetUser(userId, false);
if (user is null)
{
return NotFound(userId);
return NotFound();
}

// Generate path to store avatar file.
Expand Down
10 changes: 6 additions & 4 deletions src/backend/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,11 +169,13 @@ export function getAudioUrl(wordId: string, fileName: string): string {

/* AvatarController.cs */

export async function uploadAvatar(userId: string, file: File): Promise<void> {
/** Uploads avatar for current user. */
export async function uploadAvatar(file: File): Promise<void> {
// Backend ignores userId and gets current user from HttpContext,
// but userId is still required in the url and helpful for analytics.
const userId = LocalStorage.getUserId();
await avatarApi.uploadAvatar({ userId, file }, fileUploadOptions());
if (userId === LocalStorage.getUserId()) {
LocalStorage.setAvatar(await avatarSrc(userId));
}
LocalStorage.setAvatar(await avatarSrc(userId));
}

/** Returns the string to display the image inline in Base64 <img src= */
Expand Down
4 changes: 2 additions & 2 deletions src/components/UserSettings/ClickableAvatar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Avatar } from "@mui/material";
import { ReactElement, useState } from "react";

import { uploadAvatar } from "backend";
import { getAvatar, getUserId } from "backend/localStorage";
import { getAvatar } from "backend/localStorage";
import { UploadImageDialog } from "components/Dialogs";

const avatarStyle = { height: 60, width: 60 };
Expand Down Expand Up @@ -53,7 +53,7 @@ export default function ClickableAvatar(
close={closeDialog}
open={avatarDialogOpen}
titleId="userSettings.uploadAvatarTitle"
uploadImage={(imgFile: File) => uploadAvatar(getUserId(), imgFile)}
uploadImage={(imgFile: File) => uploadAvatar(imgFile)}
/>
</>
);
Expand Down
Loading