Register - 2023 App Security

PHOTO EMBED

Mon Jun 17 2024 08:48:51 GMT+0000 (Coordinated Universal Time)

Saved by @iamkatmakhafola

[Route("api/[controller]")]
[ApiController]
public class AuthenticationController : ControllerBase
{
    private readonly UserManager<AppUser> _userManager;
    private readonly IRepository _repository;
    private readonly IUserClaimsPrincipalFactory<AppUser> _claimsPrincipalFactory;
    private readonly IConfiguration _configuration;

    public AuthenticationController(UserManager<AppUser> userManager, IUserClaimsPrincipalFactory<AppUser> claimsPrincipalFactory, IConfiguration configuration, IRepository repository)
    {
        _userManager = userManager;
        _claimsPrincipalFactory = claimsPrincipalFactory;
        _configuration = configuration;
        _repository = repository;
    }

    [HttpPost]
    [Route("RegisterUser")]
    public async Task<IActionResult>RegisterUser(UserViewModel uvm)
    {
        var user = await _userManager.FindByNameAsync(uvm.username);
        if (user == null)
        {
            try
            {
                string phoneNumberPattern = @"^0\d{9}$";
                bool isValidPhoneNumber = Regex.IsMatch(uvm.phonenumber, phoneNumberPattern);
                if (!isValidPhoneNumber) return BadRequest("Please enter a valid 10-digit phone number");
                user = new AppUser
                {
                    Id= Guid.NewGuid().ToString(),
                    UserName= uvm.username,
                    Email=  uvm.emailaddress,
                    PhoneNumber= uvm.phonenumber
                };
                var result= await _userManager.CreateAsync(user, uvm.password);
                if (result.Errors.Count() > 0)
                {
                    StringBuilder errorlist = new StringBuilder("These registration errors need to be resolved");
                    foreach (var error in result.Errors)
                    {
                        errorlist.Append($"{error.Code}: {error.Description}");
                    }
                    return BadRequest($"{errorlist}");
                }
            }
            catch (Exception ex)
            {
                return StatusCode(StatusCodes.Status500InternalServerError, $"Error occured{ex.Message}");
            }
        }
        else
        {
            return Conflict($"The username '{uvm.username}' already exists. Please use a different username");
        }
        return Ok($"Your account '{uvm.username}' was created successfully. You may proceed with logging in");
    }
}
content_copyCOPY

2023 - Register method: 1.2 In“AuthenticationController.cs”: a) Create a “RegisterUser” endpoint/function to allow a User to register on the application. Note: The endpoint/function route name should be the same as the endpoint/function name. Furthermore, the endpoint/function is an asynchronous endpoint/method taking a view model as a parameter and returning an “IActionResult”. b) The username should be compared to the existing account names to check if it already exists c) If the account name does not exist, the account creation code should be done inside a try/catch block. If any Exceptions happen it should be caught in the catch block and a 500-status code with the specific details of the Exception should be returned. d) If the account already exists, a 409-status code with the name of the existing account should be returned. e) The account should be created in the database passing through the User name, Email, Phone number, and User id. f) Phone number validation should only allow for ten digits and the first digit must be a zero. If the phone number is not valid, a 400-status code with the message “Please enter a valid 10-digit phone number” must be returned. g) All Identity errors that are returned during the account creation attempt, should be logged with a 400-status code with the details of any returned errors. h) If the account is created successfully a 200-status code with the message "Your account 'add your username' was created successfully. You may proceed with logging in"