RegisterUser(with base64image) - 370 App Security
Thu Jun 20 2024 17:31:11 GMT+0000 (Coordinated Universal Time)
Saved by @iamkatmakhafola
//Controller
[HttpPost]
[DisableRequestSizeLimit]
[Route("Register")]
public async Task<IActionResult> Register([FromForm] UserViewModel uvm)
{
try
{
var formCollection = await Request.ReadFormAsync();
// Retrieves the first file from the form data, which is expected to be the user's photo.
var photo = formCollection.Files.FirstOrDefault();
// Attempts to find an existing user by the provided email.
var user = await _userManager.FindByEmailAsync(uvm.Email);
// If the user is not found, proceed with registration.
if (user == null)
{
// Uses a memory stream to process the photo file.
using (var memoryStream = new MemoryStream())
{
// Copies the photo file data into the memory stream asynchronously.
await photo.CopyToAsync(memoryStream);
// Converts the memory stream data into a byte array.
var fileBytes = memoryStream.ToArray();
// Encodes the byte array to a base64 string.
string base64Image = Convert.ToBase64String(fileBytes);
// Creates a new user object with the provided details and hashed password.
user = new User
{
UserName = uvm.Email,
Email = uvm.Email,
PasswordHash = _userManager.PasswordHasher.HashPassword(null, uvm.Password),
Photo = base64Image // Stores the base64 string in the user's profile.
};
// Attempts to create the new user asynchronously.
IdentityResult result = await _userManager.CreateAsync(user);
// If the user creation is successful, return a success response.
if (result.Succeeded)
{
return Ok(new { Status = "Success", Message = "User created successfully!" });
}
// If user creation fails, return an error response with the first error message.
else
{
return StatusCode(StatusCodes.Status500InternalServerError, result.Errors.FirstOrDefault()?.Description);
}
}
}
// If the user already exists, return a forbidden response.
else
{
return Forbid("Account already exists.");
}
}
catch (Exception ex)
{
// If an exception occurs, return a generic error response.
return StatusCode(StatusCodes.Status500InternalServerError, "An error occurred while processing your request.");
}
}
//program cs
// Configure FormOptions for file uploads
builder.Services.Configure<FormOptions>(o =>
{
o.ValueLengthLimit = int.MaxValue;
o.MultipartBodyLengthLimit = int.MaxValue;
o.MemoryBufferThreshold = int.MaxValue;
});



Comments