Ejemplo n.º 1
0
        public async Task <ActionResult <MirzaUser> > PostUser(MirzaUser user)
        {
            try
            {
                var registeredUser = await _userService.Register(user).ConfigureAwait(false);

                return(CreatedAtAction(nameof(Detail), new { id = registeredUser.Id }, null));
            }
            catch (ArgumentNullException)
            {
                return(BadRequest("Input was null"));
            }
            catch (UserModelValidationException e)
            {
                return(BadRequest(e.ValidationErrors));
            }
            catch (DuplicateEmailException e)
            {
                return(BadRequest(e.Message));
            }
            catch (Exception e)
            {
                _logger.LogError(e.ToString());
                return(StatusCode(500, $"Internal Error. LogId: {HttpContext.TraceIdentifier}"));
            }
        }
Ejemplo n.º 2
0
        public async Task Register_Valid_Model_Ok()
        {
            var u = new MirzaUser
            {
                Email     = "*****@*****.**",
                FirstName = "sample_firstname",
                LastName  = "sample_lastname"
            };

            var result = await UserService.Register(u);

            Assert.NotNull(result);

            Assert.True(result.Id > 0);
            Assert.Equal(u.Email, result.Email);
            Assert.Equal(u.FirstName, result.FirstName);
            Assert.Equal(u.LastName, result.LastName);
            Assert.True(result.IsActive);

            Assert.Null(result.Team);

            Assert.NotNull(result.AccessKeys);
            Assert.Equal(0, result.AccessKeys.Count);

            Assert.NotNull(result.WorkLog);
            Assert.Equal(0, result.WorkLog.Count);
        }
Ejemplo n.º 3
0
        public void FirstName_Should_Be_Valid()
        {
            var model = new MirzaUser {
                FirstName = new string('a', 20)
            };

            _validator.TestValidate(model)
            .ShouldNotHaveValidationErrorFor(u => u.FirstName);
        }
Ejemplo n.º 4
0
        public void Email_Should_Be_Valid()
        {
            var model = new MirzaUser {
                Email = "*****@*****.**"
            };

            _validator.TestValidate(model)
            .ShouldNotHaveValidationErrorFor(u => u.Email);
        }
Ejemplo n.º 5
0
        public void FirstName_Should_Have_Validation_Error_When_Null()
        {
            var model = new MirzaUser {
                FirstName = null
            };

            _validator.TestValidate(model)
            .ShouldHaveValidationErrorFor(u => u.FirstName)
            .WithErrorMessage("FirstName must be a non-empty value")
            .WithSeverity(FluentValidation.Severity.Error);
        }
Ejemplo n.º 6
0
        public void Email_Should_Have_Validation_Error_When_NotValidEmail()
        {
            var model = new MirzaUser {
                Email = Guid.NewGuid().ToString()
            };

            _validator.TestValidate(model)
            .ShouldHaveValidationErrorFor(u => u.Email)
            .WithErrorMessage("Email field must abide by the simple email structure. i.e. [email protected]")
            .WithSeverity(FluentValidation.Severity.Error);
        }
Ejemplo n.º 7
0
        public async Task Register_Invalid_Model_Throws()
        {
            var u = new MirzaUser
            {
                Email     = Guid.NewGuid().ToString(),
                FirstName = new string('a', 60),
                LastName  = new string('b', 100)
            };

            await Assert.ThrowsAsync <UserModelValidationException>(() => UserService.Register(u));
        }
Ejemplo n.º 8
0
        public void LastName_Should_Have_Validation_Error_When_MoreThan50Characters()
        {
            var model = new MirzaUser {
                LastName = new string('a', 55)
            };

            _validator.TestValidate(model)
            .ShouldHaveValidationErrorFor(u => u.LastName)
            .WithErrorMessage("LastName must be at most 50 characters long")
            .WithSeverity(FluentValidation.Severity.Error);
        }
Ejemplo n.º 9
0
        public void LastName_Should_Have_Validation_Error_When_EmptyString()
        {
            var model = new MirzaUser {
                LastName = string.Empty
            };

            _validator.TestValidate(model)
            .ShouldHaveValidationErrorFor(u => u.LastName)
            .WithErrorMessage("LastName must be a non-empty value")
            .WithSeverity(FluentValidation.Severity.Error);
        }
Ejemplo n.º 10
0
        public void Model_Should_be_Valid()
        {
            var u = new MirzaUser
            {
                FirstName = "sample_first_name",
                LastName  = "sample_last_name",
                Email     = "*****@*****.**"
            };

            _validator.TestValidate(u)
            .ShouldNotHaveAnyValidationErrors();
        }
Ejemplo n.º 11
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync().ConfigureAwait(false)).ToList();
            if (ModelState.IsValid)
            {
                var user = new MirzaUser
                {
                    UserName  = Input.Email,
                    Email     = Input.Email,
                    FirstName = Input.FirstName,
                    LastName  = Input.LastName,
                    IsActive  = true
                };
                var result = await _userManager.CreateAsync(user, Input.Password).ConfigureAwait(false);

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

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user).ConfigureAwait(false);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code },
                        protocol: Request.Scheme);

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

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false).ConfigureAwait(false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Ejemplo n.º 12
0
        private async Task LoadAsync(MirzaUser user)
        {
            var email = await _userManager.GetEmailAsync(user);

            Email = email;

            Input = new InputModel
            {
                NewEmail = email,
            };

            IsEmailConfirmed = await _userManager.IsEmailConfirmedAsync(user);
        }
Ejemplo n.º 13
0
        private async Task LoadAsync(MirzaUser user)
        {
            var userName = await _userManager.GetUserNameAsync(user);

            var phoneNumber = await _userManager.GetPhoneNumberAsync(user);

            Username = userName;

            Input = new InputModel
            {
                PhoneNumber = phoneNumber
            };
        }
        private async Task LoadSharedKeyAndQrCodeUriAsync(MirzaUser user)
        {
            // Load the authenticator key & QR code URI to display on the form
            var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);

            if (string.IsNullOrEmpty(unformattedKey))
            {
                await _userManager.ResetAuthenticatorKeyAsync(user);

                unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);
            }

            SharedKey = FormatKey(unformattedKey);

            var email = await _userManager.GetEmailAsync(user);

            AuthenticatorUri = GenerateQrCodeUri(email, unformattedKey);
        }
Ejemplo n.º 15
0
        public async Task Register_Duplicate_Email_Throws()
        {
            var u1 = new MirzaUser
            {
                FirstName = "first_name_1",
                LastName  = "last_name_1",
                Email     = "*****@*****.**"
            };

            var u2 = new MirzaUser
            {
                FirstName = "first_name_2",
                LastName  = "last_name_2",
                Email     = "*****@*****.**"
            };

            _ = await UserService.Register(u1);

            await Assert.ThrowsAsync <DuplicateEmailException>(() => UserService.Register(u2));
        }
Ejemplo n.º 16
0
        public async Task <MirzaUser> Register(MirzaUser user)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            var validationResult = _userValidator.Validate(user);

            if (!validationResult.IsValid)
            {
                throw new UserModelValidationException(validationResult.Errors.Select(e => e.ErrorMessage).ToArray());
            }

            var duplicateEmail = await _dbContext.UserSet
                                 .AnyAsync(u => u.IsActive && u.Email == user.Email)
                                 .ConfigureAwait(false);

            if (duplicateEmail)
            {
                throw new DuplicateEmailException(user.Email);
            }

            try
            {
                await _dbContext.UserSet.AddAsync(user);

                await _dbContext.SaveChangesAsync().ConfigureAwait(true);

                return(user);
            }
            catch (Exception e)
            {
                _logger.LogError("Exception occured while saving user entity", e);
                throw;
            }
        }
Ejemplo n.º 17
0
        public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            // Get the information about the user from the external login provider
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ErrorMessage = "Error loading external login information during confirmation.";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }

            if (ModelState.IsValid)
            {
                var user = new MirzaUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user, info);

                    if (result.Succeeded)
                    {
                        _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);

                        var userId = await _userManager.GetUserIdAsync(user);

                        var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                        var callbackUrl = Url.Page(
                            "/Account/ConfirmEmail",
                            pageHandler: null,
                            values: new { area = "Identity", userId = userId, code = code },
                            protocol: Request.Scheme);

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

                        // If account confirmation is required, we need to show the link if we don't have a real email sender
                        if (_userManager.Options.SignIn.RequireConfirmedAccount)
                        {
                            return(RedirectToPage("./RegisterConfirmation", new { Email = Input.Email }));
                        }

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

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            LoginProvider = info.LoginProvider;
            ReturnUrl     = returnUrl;
            return(Page());
        }