Exemplo n.º 1
0
        public async Task <IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null)
        {
            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await _signInManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    return(View("ExternalLoginFailure"));
                }
                var user = new DapperIdentityUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await _userManager.CreateAsync(user);

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

                    if (result.Succeeded)
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        _logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider);
                        return(RedirectToLocal(returnUrl));
                    }
                }
                AddErrors(result);
            }

            ViewData["ReturnUrl"] = returnUrl;
            return(View(model));
        }
        public async Task <IActionResult> Register(RegisterViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                var user = new DapperIdentityUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
                    // Send an email with this link
                    //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
                    //await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
                    //    $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");
                    await _signInManager.SignInAsync(user, isPersistent : false);

                    _logger.LogInformation(3, "User created a new account with password.");
                    return(RedirectToLocal(returnUrl));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Exemplo n.º 3
0
        public async Task <Response> Handle(Request request, CancellationToken cancellationToken)
        {
            var user = new DapperIdentityUser {
                UserName = request.Email, Email = request.Email
            };
            var result = await _userManager.CreateAsync(user, request.Password);

            if (result.Succeeded)
            {
                // Send an email with this link
                var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                var callbackUrl = $"{_configuration["User:EmailConfirmationUrl"]}?userId={user.Id}&code={Uri.EscapeDataString(code)}";
                await _emailSender.SendEmailAsync(
                    request.Email,
                    "Confirm Email",
                    $@"<p>Please confirm your email by clicking here: <a href='{callbackUrl}'>link</a>.</p> <p>For testing purposes, please send this JSON to {_configuration["User:EmailConfirmationUrl"]}.</p> Here is some JSON:
<pre>
{{
    ""userId"": ""{user.Id}"",
    ""code"": ""{code}""
}}
</pre>");

                return(new Response());
            }

            throw new AggregateException(result.Errors.Select(x => new ValidationException(x.Description)));
        }
        public WhenRegisteringANewUser()
        {
            var email   = "*****@*****.**";
            var request = new Request {
                Email = email, Password = "******", ConfirmPassword = "******"
            };

            Testing.Send(request);

            _user = Testing.QueryFirst <DapperIdentityUser>("SELECT TOP 1 * FROM [dbo].[IdentityUser] WHERE [Email] = @Email", new { Email = email });
        }
Exemplo n.º 5
0
        internal string GenerateJwtToken(string email, DapperIdentityUser user)
        {
            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())
            };

            var key     = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));
            var creds   = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var expires = DateTime.Now.AddDays(Convert.ToDouble(_configuration["Jwt:ExpireDays"]));

            var token = new JwtSecurityToken(_configuration["Jwt:Issuer"], _configuration["Jwt:Issuer"], claims, expires: expires, signingCredentials: creds);

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
Exemplo n.º 6
0
        public async Task <int> CreateEmployeeAsync(UserViewModel model)
        {
            try
            {
                // Create objects for CreateEmployee Transaction

                // Generate Default Password
                var dob = model.DateOfBirth.ToString("ddMMyy");
                // Create temporary User to generate the PasswordHash
                var user = new DapperIdentityUser {
                    UserName = model.Email, Email = model.Email
                };
                var passwordHash  = _userManager.PasswordHasher.HashPassword(user, dob);
                var roleString    = string.Join(',', model.SelectedRoles);
                var securityStamp = Guid.NewGuid().ToString("D");

                using (var connection = _connectionProvider.Create())
                {
                    return(await connection.QuerySingleAsync <int>("dbig5_admin.ADD_USER_VIASQLDEV", new
                    {
                        pEmail = model.Email,
                        pPasswordHash = passwordHash,
                        pSecurityStamp = securityStamp,
                        pFirstname = model.FirstName,
                        pLastname = model.LastName,
                        pDateOfBirth = model.DateOfBirth.ToString("ddMMyy"),
                        pAddress = model.Address,
                        pUniqueID = model.UniqueID,
                        pRoleString = roleString
                    }, commandType : CommandType.StoredProcedure));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            // Return "Fail to Insert"
            return(0);
        }
Exemplo n.º 7
0
        public async Task <IActionResult> Register(RegisterViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                var user = new DapperIdentityUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await _signInManager.SignInAsync(user, isPersistent : false);

                    _logger.LogInformation(3, "User created a new account with password.");
                    return(RedirectToLocal(returnUrl));
                }
                AddErrors(result);
            }

            return(View(model));
        }
Exemplo n.º 8
0
        public async Task <IActionResult> Register(RegisterViewModel model, string returnUrl = null)
        {
            //     if not null, use this VV    if null use this VV
            ViewData["ReturnUrl"] = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                var user = new DapperIdentityUser {
                    UserName = model.Email, Email = model.Email
                };

                var result = await _userManager.CreateAsync(user, model.Password);

                if (!result.Succeeded)
                {
                    var exceptionText = string.Join(", ", result.Errors.Select(x => "Code " + x.Code + " Description" + x.Description));
                    throw new Exception(exceptionText);
                }
                //AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Exemplo n.º 9
0
 public void SetUser(DapperIdentityUser user)
 {
     _user = user;
 }