Exemplo n.º 1
0
        internal static async Task <DLUserToken> BuildToken(DALUserAccount efUserAccount, UserManager <DALUserAccount> userManager, string issuerSigningKey)
        {
            IList <Claim> claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.UniqueName, $"{efUserAccount.Email.GetHashCode()}{DateTime.UtcNow}{efUserAccount.PasswordHash.GetHashCode()}"),
                new Claim(ClaimTypes.Name, efUserAccount.ToString()),
                new Claim(ClaimTypes.Email, efUserAccount.Email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            };

            foreach (var role in await userManager.GetRolesAsync(efUserAccount))
            {
                claims.Add(new Claim(ClaimTypes.Role, role));
            }

            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(issuerSigningKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var expiration = DateTime.UtcNow.AddMinutes(10);

            JwtSecurityToken token = new JwtSecurityToken(
                issuer: Constants.API_BASE_ADDRESS,
                audience: Constants.API_BASE_ADDRESS,
                claims: claims,
                expires: expiration,
                signingCredentials: creds);

            return(new DLUserToken(
                       userId: efUserAccount.Id,
                       loginProvider: "MTS-Security",
                       userName: efUserAccount.FirstName ?? efUserAccount.Email.Split('@')[0],
                       expiration: expiration,
                       jwtSecurityToken: new JwtSecurityTokenHandler().WriteToken(token)));
        }
 protected void GetEmailConfirmedMessages(DALUserAccount efUserAccount, List <string> responses)
 {
     if (efUserAccount.EmailConfirmed == false)
     {
         responses.Add("Email not yet confirmed by user");
     }
 }
 protected void GetIsAdmittedMessages(DALUserAccount efUserAccount, List <string> responses)
 {
     if (efUserAccount.IsAdmitted == false)
     {
         responses.Add("Email not yet confirmed by admin");
     }
 }
Exemplo n.º 4
0
    {        // TODO Make callback url redirect to either webpage or mobile depending on what platform was used creating the account
        internal static async Task SendConfirmationEmailAsync(DALUserAccount dalUserAccount, UserManager <DALUserAccount> userManager, IEmailSender emailSender)
        {
            var code = await userManager.GenerateEmailConfirmationTokenAsync(dalUserAccount);

            code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
            var callbackUrl = $"{Constants.BLAZOR_WEB_BASE_ADDRESS}/account/register/confirmemail?userid={dalUserAccount.Id}&code={code}";

            await emailSender.SendEmailAsync(
                dalUserAccount.Email,
                "Confirm your email",
                $"Welcome to the Maurice Tech Community!\n" +
                $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
        }
        /// <exception cref="System.Exception">Thrown when the UserManager was not able to create the useraccount</exception>
        /// <exception cref="System.ArgumentException">Thrown when the UserAccount parameter was null or invalid</exception>
        public async Task <IBLUserAccount> CreateByAccountAsync(IPLUserAccount userAccount)
        {
            if (userAccount == null || String.IsNullOrEmpty(userAccount.Email) || String.IsNullOrEmpty(userAccount.Password))
            {
                throw new ArgumentException("Parameter cannot be null or invalid");
            }

            var dalUserAccount = new DALUserAccount();

            PropertyCopier <PLUserAccount, DALUserAccount> .Copy((PLUserAccount)userAccount, dalUserAccount);

            dalUserAccount.UserName = dalUserAccount.Email;
            dalUserAccount.Id       = Guid.NewGuid().ToString();

            IdentityResult result = await _userManager.CreateAsync(dalUserAccount, userAccount.Password);

            return(await HandleAccountCreationResult(result, dalUserAccount));
        }
        /// <exception cref="System.Exception">Thrown when the UserManager was not able to create the useraccount</exception>
        /// <exception cref="System.ArgumentException">Thrown when one or both of the parameters was null or empty</exception>
        public async Task <IBLUserAccount> CreateByEmailAndPasswordAsync(string email, string password)
        {
            if (String.IsNullOrEmpty(email) || String.IsNullOrEmpty(password))
            {
                throw new ArgumentException("Parameters cannot be null or empty");
            }

            var dalUserAccount = new DALUserAccount
            {
                UserName = email,
                Email    = email,
                Id       = Guid.NewGuid().ToString()
            };

            IdentityResult result = await _userManager.CreateAsync(dalUserAccount, password);

            return(await HandleAccountCreationResult(result, dalUserAccount));
        }
        protected void HandleNegativeSignInResult(SignInResult result, DALUserAccount efUserAccount, List <string> responses)
        {
            if (result.IsLockedOut == true)
            {
                responses.Add("You are locked out for some time.");
            }

            if (result.IsNotAllowed == true)
            {
                responses.Add($"You are not allowed to login");
            }

            if (responses.Count == 0)
            {
                responses.Add("Wrong password");
            }

            responses.Add($"Login attempts remaining: { _signInManager.Options.Lockout.MaxFailedAccessAttempts - efUserAccount.AccessFailedCount }");
        }
        private async Task <IBLUserAccount> HandleAccountCreationResult(IdentityResult result, DALUserAccount dalUserAccount)
        {
            if (result.Succeeded == false)
            {
                var errors = new string[result.Errors.Count()];
                for (int i = 0; i < errors.Length; i++)
                {
                    errors[i] = result.Errors.ElementAt(i).Description;
                }

                throw new Exception(JsonConvert.SerializeObject(errors));
            }

            await EmailHelper.SendConfirmationEmailAsync(dalUserAccount, _userManager, _emailSender);

            dalUserAccount = await _userManager.FindByEmailAsync(dalUserAccount.Email);

            await AddRolesToAccountAsync(dalUserAccount.Id, Constants.Roles.StandardUser);

            return(dalUserAccount);
        }
        public async Task <IAuthentificationResult> LogIn(ICredentialHolder credentials)
        {
            if (credentials == null)
            {
                return new BLAuthentificationResult {
                           IsSucceeded = false, Errors = new[] { "The credentials parameter was null" }
                }
            }
            ;

            DALUserAccount dalUserAccount = await _userManager.FindByEmailAsync(credentials.Email);

            if (dalUserAccount == null)
            {
                return new BLAuthentificationResult {
                           IsSucceeded = false, Errors = new[] { "No user exists with this email and password" }
                }
            }
            ;

            List <string> errorMessages = new List <string>();

            GetEmailConfirmedMessages(dalUserAccount, errorMessages);

            GetIsAdmittedMessages(dalUserAccount, errorMessages);

            if (errorMessages.Count > 0)
            {
                return new BLAuthentificationResult {
                           IsSucceeded = false, Errors = errorMessages
                }
            }
            ;

            SignInResult result = await _signInManager.PasswordSignInAsync(
                credentials.Email,
                credentials.Password,
                isPersistent : credentials.RememberMe,
                lockoutOnFailure : true);

            if (result.Succeeded == false)
            {
                HandleNegativeSignInResult(result, dalUserAccount, errorMessages);

                return(new BLAuthentificationResult {
                    IsSucceeded = false, Errors = errorMessages
                });
            }

            try
            {
                var authResult = new BLAuthentificationResult
                {
                    IsSucceeded = true,
                    UserToken   = await UserTokenBuilder.BuildToken(dalUserAccount, _userManager, _dbConfigurations.IssuerSigningKey)
                };

                return(authResult);
            }
            catch
            {
                throw;
            }
        }