Exemple #1
0
        public async Task <ActionResult> PostAsync([FromBody] UserRegDto reg)
        {
            if (ModelState.IsValid)
            {
                var user = new IdentityUser {
                    UserName = reg.UserName, Email = reg.Email
                };
                var result = await _userManager.CreateAsync(user, reg.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    //var callbackUrl = Url.Page(
                    //    "/Account/ConfirmEmail",
                    //    pageHandler: null,
                    //    values: new { userId = user.Id, code = code },
                    //    protocol: Request.Scheme);

                    //await _emailSender.SendEmailAsync(reg.Email, "Confirm your email",
                    //    $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    //await _signInManager.SignInAsync(user, isPersistent: false);

                    return(Ok(new UserDto {
                        Id = user.Id,
                        UserName = user.UserName
                    }));
                }
            }
            return(BadRequest());
        }
Exemple #2
0
        public async Task <IActionResult> OnPostAsync([FromBody] UserRegDto dto)
        {
            if (!ModelState.IsValid)
            {
                return(await Task.FromResult(new JsonResult(new
                {
                    Status = false,
                    ErrorMessage = ModelState.Where(e => e.Value.Errors.Count > 0).Select(e => e.Value.Errors.First().ErrorMessage).First()
                })));
            }

            var userId = _accountContext.UserId;

            var command = new RegCommand(dto.Email, dto.Password);
            await _bus.SendCommand(command);

            if (_notifications.HasNotifications())
            {
                var errorMessage = string.Join(";", _notifications.GetNotifications().Select(x => x.Content));
                return(await Task.FromResult(new JsonResult(new
                {
                    status = false,
                    errorMessage
                })));
            }

            return(await Task.FromResult(new JsonResult(new
            {
                status = true
            })));
        }
        public async Task <IActionResult> Register([FromBody] UserRegDto user)
        {
            if (ModelState.IsValid)
            {
                var existingUser = await _userManager.FindByEmailAsync(user.Email);

                if (existingUser != null)
                {
                    return(BadRequest(new RegistrationResponse()
                    {
                        Errors = new List <string>()
                        {
                            "Email already in Use"
                        },

                        IsSuccess = false
                    }));
                }

                var newUser = new IdentityUser()
                {
                    Email = user.Email, UserName = user.UserName
                };
                var isCreated = await _userManager.CreateAsync(newUser, user.Password);

                if (isCreated.Succeeded)
                {
                    var jwToekn = GenerateJwtToken(newUser);
                    return(Ok(new RegistrationResponse()
                    {
                        IsSuccess = true,
                        Token = jwToekn
                    }));
                }
                else
                {
                    return(BadRequest(new RegistrationResponse()
                    {
                        Errors = isCreated.Errors.Select(x => x.Description).ToList(),
                        IsSuccess = false
                    }));
                }
            }

            return(BadRequest(new RegistrationResponse()
            {
                Errors = new List <string>()
                {
                    "Invalid Payload"
                },
                IsSuccess = false
            }));
        }
Exemple #4
0
        public async Task PostUser_Failed()
        {
            //Mocking host address.
            _userController.ControllerContext             = new ControllerContext();
            _userController.ControllerContext.HttpContext = new DefaultHttpContext();
            _userController.ControllerContext.HttpContext.Request.Host = new HostString("https://*****:*****@guest.com",
                Password        = "******",
                FirstName       = "Guest",
                LastName        = "Test",
                PhoneNumber     = "0225689994",
                OrgName         = "Christchurch",
                OrgCode         = "CHRCH",
                StreetAddrL1    = "1/32 catelina drive",
                StreetAddrL2    = "",
                City            = "Auckland",
                Country         = "Newzealand",
                OrgPhoneNumber  = "0203388485",
                LogoURL         = "",
                CharitiesNumber = "",
                GSTNumber       = ""
            };

            CBAUser objCBAUser = new CBAUser()
            {
                Email     = "*****@*****.**",
                FirstName = "Guest",
                LastName  = "Test",
                UserName  = "******"
            };

            IdentityError err = new IdentityError();

            err.Description = "Failed to create the user";

            //Mocking methods.
            _mockUserManager.Setup(x => x.CreateAsync(It.IsAny <CBAUser>(), It.IsAny <string>())).ReturnsAsync(IdentityResult.Failed(err));
            _mockUserManager.Setup(x => x.GenerateEmailConfirmationTokenAsync(It.IsAny <CBAUser>())).ReturnsAsync("CfDJ8I9H5drWaGxHgWTL+ERlWjwsoqt2f5ZNoc4xdQXmlFVvLV3crqNf8lyPN2+1i7zONZT+OR6gYFJZm6N3cjM2LnsnzobTpGLdznAhTQ3LEE/sW/F9b7AtIT2cvGDVFbsjSJN0GUTdXaJFiZR8yrBI2fggnAB5rDqGBnq3UOyJN0qa68Xwj6bsifkPFy25xRlOnNh83MPVFwzUuGwOpsWMsaUnaTb+XCWGQgBUzSISlKyv+wLS7mU1+iOKqpWpI/HPSg==");

            var result = await _userController.PostUser(cbaUserRegDto);

            Assert.AreEqual(((ObjectResult)result).Value, "Failed to create the user");
        }
Exemple #5
0
        public async Task <IActionResult> OnPostAsync([FromBody] UserRegDto dto)
        {
            var userId = _accountContext.UserId;

            var command = new RegCommand(dto.Email, dto.Password, dto.Code);
            await _bus.SendCommand(command);

            if (_notifications.HasNotifications())
            {
                var errorMessage = string.Join(";", _notifications.GetNotifications().Select(x => x.Content));
                return(await Task.FromResult(new JsonResult(new
                {
                    status = false,
                    errorMessage
                })));
            }

            return(await Task.FromResult(new JsonResult(new
            {
                status = true
            })));
        }
        public async Task <IActionResult> PostUser([FromBody] UserRegDto regUser)
        {
            var cbaUser = new CBAUser()
            {
                Email        = regUser.Email,
                FirstName    = regUser.FirstName,
                LastName     = regUser.LastName,
                PhoneNumber  = regUser.PhoneNumber,
                UserName     = regUser.Email,
                Organisation = new Organisation
                {
                    Name             = regUser.OrgName,
                    Code             = regUser.OrgCode,
                    StreetAddressOne = regUser.StreetAddrL1,
                    StreetAddressTwo = regUser.StreetAddrL2,
                    City             = regUser.City,
                    Country          = regUser.Country,
                    PhoneNumber      = regUser.OrgPhoneNumber,
                    Logo             = regUser.LogoURL,
                    CharitiesNumber  = regUser.CharitiesNumber,
                    GSTNumber        = regUser.GSTNumber,
                    CreatedAt        = DateTime.Now,
                }
            };

            try
            {
                var result = await _userManager.CreateAsync(cbaUser, regUser.Password);

                if (result != null && result.Succeeded)
                {
                    //_logger.LogInformation("User created a new account with password");
                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(cbaUser);

                    var hostAddress = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host}";
                    var queryPrarms = new Dictionary <string, string>()
                    {
                        { "userId", cbaUser.Id + "" },
                        { "token", code + "" }
                    };

                    string callbackUrl = QueryHelpers.AddQueryString($"{hostAddress}/api/user/confirmEmail", queryPrarms);
                    var    pathToFile  = Directory.GetCurrentDirectory()
                                         + Path.DirectorySeparatorChar.ToString()
                                         + "EmailTemplates"
                                         + Path.DirectorySeparatorChar.ToString()
                                         + "ConfirmRegEmailTemplate.html";

                    string htmlBody = "";

                    using (StreamReader SourceReader = System.IO.File.OpenText(pathToFile))
                    {
                        htmlBody = await SourceReader.ReadToEndAsync();
                    };

                    Email emailContent = new Email()
                    {
                        To      = cbaUser.Email,
                        Subject = $"CBA user validation email for {cbaUser.FirstName} {cbaUser.LastName}",
                        Body    = string.Format(htmlBody, cbaUser.FirstName, callbackUrl)
                    };
                    var sentEmailRes = await _emailService.SendEmail(_emailConfig, emailContent);

                    return(sentEmailRes? Ok("succeed") : StatusCode(500, "Failed to send confirmation email, please contact CBA"));
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        //_logger.LogError(error.ToString());
                        Console.WriteLine(error.ToString());
                    }
                    return(StatusCode(500, "Failed to create the user"));
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            #region Old code
            //if (!ModelState.IsValid)
            //{
            //    return BadRequest(ModelState);
            //}

            //if (LoginExists(user.Email))
            //{
            //    return BadRequest("Login Invalid");
            //}


            //user.Password = _crypto.HashMD5(user.Password);
            //_context.User.Add(user);
            //await _context.SaveChangesAsync();

            //return CreatedAtAction("GetUsers", new { id = user.Id }, user);
            #endregion
        }