Esempio n. 1
0
        public async Task <IActionResult> ExternalLoginConfirmation(ExternalLoginViewModel 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)
                {
                    throw new ApplicationException("Error loading external login information during confirmation.");
                }
                var user = new Domain.AppUser {
                    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("User created an account using {Name} provider.", info.LoginProvider);
                        return(RedirectToLocal(returnUrl));
                    }
                }
                AddErrors(result);
            }

            ViewData["ReturnUrl"] = returnUrl;
            return(View(nameof(ExternalLogin), model));
        }
        public string CreateToken(Domain.AppUser user)
        {
            //claim is part of payload - here username
            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.NameId, user.UserName)
            };

            //generate signing credentials - creates unique signature so the server can validate a token is authentic
            var creds = new SigningCredentials(_key, SecurityAlgorithms.HmacSha512Signature);

            //describe data about token
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.UtcNow.AddMinutes(15),
                SigningCredentials = creds
            };

            //handler can create, validate, and write tokens
            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(token));
        }
Esempio n. 3
0
        public async Task <IActionResult> Register(RegisterViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                var user = new Domain.AppUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await _userManager.CreateAsync(user, model.Password);

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

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme);
                    await _emailSender.SendEmailConfirmationAsync(model.Email, callbackUrl);

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

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

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Esempio n. 4
0
            public async Task <UserDTO> Handle(Command request, CancellationToken cancellationToken)
            {
                //can't create user with existing email or username
                if (await _context.Users.Where(x => x.Email == request.Email).AnyAsync())
                {
                    throw new Application.Errors.RestException(HttpStatusCode.BadRequest, new { Email = "Email already exists." });
                }

                if (await _context.Users.Where(x => x.UserName == request.UserName).AnyAsync())
                {
                    throw new Application.Errors.RestException(HttpStatusCode.BadRequest, new { UserName = "******" });
                }

                //create new user
                var user = new Domain.AppUser
                {
                    DisplayName        = request.DisplayName,
                    UserName           = request.UserName,
                    Email              = request.Email,
                    RefreshToken       = _jwtGenerator.CreateRefreshToken(),
                    RefreshTokenExpiry = DateTime.Now.AddDays(30)
                };

                await _userManager.UpdateAsync(user);

                //user manager automatically salts and hashes password
                var result = await _userManager.CreateAsync(user, request.Password);

                if (result.Succeeded)
                {
                    return(new UserDTO
                    {
                        DisplayName = user.DisplayName,
                        Token = _jwtGenerator.CreateToken(user),
                        RefreshToken = _jwtGenerator.CreateRefreshToken(),
                        UserName = user.UserName,
                        Image = user.Photos.FirstOrDefault(x => x.IsMain)?.Url
                    });
                }
                else
                {
                    throw new Exception("Problem creating user.");
                }
            }