Example #1
0
        public async Task <IActionResult> Register(RegisterInputModel model, string button)
        {
            var returnUrl = Url.Content("~/");

            if (button != "register")
            {
                // Todo add some special page.
                return(LocalRedirect(returnUrl));
            }

            if (ModelState.IsValid)
            {
                var user = new IdUser {
                    UserName = model.Username
                };
                var result = await _userManager.CreateAsync(user, model.Password);

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


                    return(LocalRedirect(returnUrl));
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }
            // something went wrong.
            return(View(new RegisterViewModel(model)));
        }
Example #2
0
        public async Task <IActionResult> Register(RegisterInputModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Username,
                };
                var result = await _userManager.CreateAsync(user, model.Password);

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

                    //TODO: Fix issue here
                    return(View("Redirect", new RedirectViewModel {
                        RedirectUrl = model.ReturnUrl
                    }));
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError("", error.Description);
                    }
                }
            }
            return(View());
        }
        private async Task <RegisterViewModel> BuildRegisterViewModelAsync(RegisterInputModel model)
        {
            var vm = await BuildRegisterViewModelAsync(model.ReturnUrl);

            vm.Email         = model.Email;
            vm.RememberLogin = model.RememberLogin;
            return(vm);
        }
Example #4
0
        public ViewResult Register(string returnUrl)
        {
            var vm = new RegisterInputModel
            {
                ReturnUrl = returnUrl,
            };

            return(View(vm));
        }
        public async Task <IActionResult> Register(RegisterInputModel model, string button)
        {
            if (button != "register")
            {
                //o usuário clicou no botão "cancelar"
                var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

                if (context != null)
                {
                    //se um usuário cancela, enviamos o resultado de volta para o IdentityServer como acesso negado
                    await _interaction.GrantConsentAsync(context, ConsentResponse.Denied);

                    return(Redirect(model.ReturnUrl));
                }
                else
                {
                    //já que não temos um contexto válido, voltamos para a página inicial
                    return(Redirect("~/"));
                }
            }
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Username, Email = model.Email
                };
                var result = await _userManager.CreateAsync(user, model.Password);

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

                    var claimsResult = _userManager.AddClaimsAsync(user, new Claim[] {
                        new Claim("name", user.UserName),
                        new Claim(JwtClaimTypes.GivenName, ""),
                        new Claim(JwtClaimTypes.FamilyName, ""),
                        new Claim("email", user.Email),
                        new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),
                    }).Result;
                    if (!claimsResult.Succeeded)
                    {
                        throw new Exception(result.Errors.First().Description);
                    }
                    return(Redirect(model.ReturnUrl));
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(error.Code, error.Description);
                }
            }
            //algo deu errado, vamos mostrar a view com o erro
            var vm = await BuildRegisterViewModelAsync(model);

            return(View(vm));
        }
Example #6
0
        public RegisterViewModel BuildRegisterViewModel(RegisterInputModel model, bool success)
        {
            RegisterViewModel newModel = new RegisterViewModel
            {
                IsSuccess       = success,
                Username        = model.Username,
                Password        = model.Password,
                ConfirmPassword = model.ConfirmPassword
            };

            return(newModel);
        }
        public async Task <IActionResult> Register([FromBody] RegisterInputModel model)
        {
            // check if we are in the context of an authorization request

            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email, EmailConfirmed = true
                };
                var password = model.Password;
                var result   = await _userManager.CreateAsync(user, password);

                var errors = new List <IdentityError>();

                if (result.Succeeded)
                {
                    var resultClaims = await _userManager.AddClaimsAsync(user, new Claim[] {
                        new Claim(JwtClaimTypes.Name, string.Join(' ', new[] { model.FirstName, model.LastName })),
                        new Claim(JwtClaimTypes.GivenName, model.FirstName),
                        new Claim(JwtClaimTypes.FamilyName, model.LastName),
                        new Claim(JwtClaimTypes.Email, model.Email),
                        new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),
                    });

                    if (resultClaims.Succeeded)
                    {
                        if (errors.Count == 0)
                        {
                            return(Ok(password));
                        }
                    }

                    else
                    {
                        errors.AddRange(resultClaims.Errors);
                    }

                    // user created but errors in claims or roles, rolling back
                    await _userManager.DeleteAsync(user);
                }
                //somethinng bad happened
                else
                {
                    errors.AddRange(result.Errors);
                }
                return(BadRequest(errors));
            }
            return(BadRequest());
        }
        public async Task <IActionResult> Register(string returnUrl)
        {
            RegisterInputModel regModel = new RegisterInputModel()
            {
                ReturnUrl      = returnUrl,
                ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList()
            };

            UserRegisterViewModel model = new UserRegisterViewModel()
            {
                RegisterInputModel = regModel
            };

            return(View(model));
        }
        public async Task <IActionResult> Register([FromBody] RegisterInputModel registerInputModel)
        {
            //var externalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    Role      = registerInputModel.Role,
                    UserName  = $"{registerInputModel.FirstName}{registerInputModel.LastName}".Split(" ").Aggregate("", (current, next) => current + next),
                    Email     = registerInputModel.Email,
                    FirstName = registerInputModel.FirstName,
                    LastName  = registerInputModel.LastName
                };
                var result = await _userManager.CreateAsync(user, registerInputModel.Password);

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

                    result = await _userManager.AddClaimsAsync(user, new Claim[] {
                        new Claim(JwtClaimTypes.Name, user.UserName),
                        new Claim(JwtClaimTypes.GivenName, user.FirstName),
                        new Claim(JwtClaimTypes.FamilyName, user.LastName),
                        new Claim(JwtClaimTypes.Email, user.Email),
                        new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),
                        new Claim(JwtClaimTypes.Role, user.Role.ToString(), ClaimValueTypes.Integer)
                    });

                    if (result.Succeeded)
                    {
                        await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id, user.UserName));

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

            // If we got this far, something failed, redisplay form
            return(BadRequest());
        }
        public async Task <IActionResult> Register(RegisterInputModel model, string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Action("Home");
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Username, Email = model.Email
                };
                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    var callbackUrl = Url.Action(
                        action: "ConfirmEmail",
                        controller: "Account",
                        values: new { user = user, code = code },
                        protocol: Request.Scheme);

                    var htmlTemplate = await _botMongoDal.GetTemplateByIdNameAsync("email_confirm_template");

                    var formatHtmlTemplate = htmlTemplate.data.Replace("{0}", model.Username);

                    formatHtmlTemplate = formatHtmlTemplate.Replace("{1}", HtmlEncoder.Default.Encode(callbackUrl));

                    await _emailSender.SendEmailAsync(model.Email, "FlowGraph Confirmation your email", formatHtmlTemplate);

                    return(View("SuccessRegister"));

                    //await _signInManager.SignInAsync(user, isPersistent: false);
                    //return View(returnUrl);
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            var vm = BuildRegisterViewModelAsync(returnUrl);

            return(View(vm));
        }
Example #11
0
        public async Task <IActionResult> Register([FromBody] RegisterInputModel model)
        {
            if (model == null || !ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var exists = _repository.GetUserByUsername(model.Email);

            if (exists != null)
            {
                ModelState.AddModelError("username", "Usuário já registrado");
                return(BadRequest(ModelState));
            }

            if (model.Password != model.ConfirmPassword)
            {
                ModelState.AddModelError("password", "As senhas não combinam");
                return(BadRequest(ModelState));
            }

            if (model.InvitationCode != "mednuvemapp")
            {
                ModelState.AddModelError("invitationCode", "Código de convite inválido");
                return(BadRequest(ModelState));
            }

            var user = new User()
            {
                Username = model.Email,
                Name     = model.Name,
                Email    = model.Email,
                Company  = model.Company,
                IsActive = true,
            };

            await _repository.CreateUser(user, model.Password);

            return(Ok());
        }
        public async Task <IActionResult> Register([FromForm] RegisterInputModel model)
        {
            var vm = _account.BuildRegisterViewModel(model, false);

            if (!ModelState.IsValid)
            {
                return(View(vm));
            }

            var user = await _userManager.FindByNameAsync(model.Username);

            if (user == null)
            {
                ModelState.AddModelError("", AccountOptions.InvalidUsernameErrorMessage);
                vm = _account.BuildRegisterViewModel(model, false);
                return(View(vm));
            }



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

            if (result.Succeeded)
            {
                result = await _userManager.UpdateAsync(user);
            }

            if (!result.Succeeded)
            {
                foreach (var item in result.Errors)
                {
                    ModelState.AddModelError("", item.Description);
                }
            }

            vm = _account.BuildRegisterViewModel(model, result.Succeeded);

            return(View(vm));
        }
Example #13
0
        public async Task <IActionResult> Register(RegisterInputModel registerInputModel)
        {
            var returnUrl = registerInputModel.ReturnUrl ?? Url.Content("~/");

            if (ModelState.IsValid)
            {
                var(result, user) = await _registrationService.Register(registerInputModel);

                if (result.Succeeded)
                {
                    await _signInManager.SignInAsync(user, isPersistent : 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(View());
        }
Example #14
0
        public async Task <IActionResult> Register(RegisterInputModel model, string button)
        {
            if (button != "register")
            {
                // the user clicked the "cancel" button
                var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

                if (context != null)
                {
                    // if the user cancels, send a result back into IdentityServer as if they
                    // denied the consent (even if this client does not require consent).
                    // this will send back an access denied OIDC error response to the client.
                    await _interaction.GrantConsentAsync(context, ConsentResponse.Denied);

                    // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                    return(Redirect(model.ReturnUrl));
                }
                else
                {
                    // since we don't have a valid context, then we just go back to the home page
                    return(Redirect("~/"));
                }
            }

            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Username, Email = model.Email
                };
                var result = await _userManager.CreateAsync(user, model.Password);

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

                    var claimsResult = _userManager.AddClaimsAsync(user, new Claim[] {
                        new Claim("name", user.UserName),
                        new Claim(JwtClaimTypes.GivenName, ""),
                        new Claim(JwtClaimTypes.FamilyName, ""),
                        new Claim("email", user.Email),
                        new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),
                    }).Result;
                    if (!claimsResult.Succeeded)
                    {
                        throw new Exception(result.Errors.First().Description);
                    }

                    return(Redirect(model.ReturnUrl));
                }

                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(error.Code, error.Description);
                }
            }

            // something went wrong, show form with error
            var vm = await BuildRegisterViewModelAsync(model);

            return(View(vm));
        }
Example #15
0
        public async Task <IActionResult> Register(RegisterInputModel model, string button)
        {
            if (button != "register")
            {
                // the user clicked the "cancel" button
                var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

                if (context != null)
                {
                    // if the user cancels, send a result back into IdentityServer as if they
                    // denied the consent (even if this client does not require consent).
                    // this will send back an access denied OIDC error response to the client.
                    await _interaction.GrantConsentAsync(context, ConsentResponse.Denied);

                    // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                    return(Redirect(model.ReturnUrl));
                }
                else
                {
                    // since we don't have a valid context, then we just go back to the home page
                    return(Redirect("~/"));
                }
            }

            if (ModelState.IsValid)
            {
                //var result = await _signInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberLogin, lockoutOnFailure: true);
                //if (result.Succeeded)
                //{
                //    var user = await _userManager.FindByNameAsync(model.Username);
                //    await _events.RaiseAsync(new UserRegisterSuccessEvent(user.UserName, user.Id, user.UserName));

                //    // make sure the returnUrl is still valid, and if so redirect back to authorize endpoint or a local page
                //    // the IsLocalUrl check is only necessary if you want to support additional local pages, otherwise IsValidReturnUrl is more strict
                //    if (_interaction.IsValidReturnUrl(model.ReturnUrl) || Url.IsLocalUrl(model.ReturnUrl))
                //    {
                //        return Redirect(model.ReturnUrl);
                //    }

                //    return Redirect("~/");
                //}

                //await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials"));

                //ModelState.AddModelError("", AccountOptions.InvalidCredentialsErrorMessage);
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await _userManager.CreateAsync(user, model.Password);

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

                    // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    var claimsResult = _userManager.AddClaimsAsync(user, new Claim[] {
                        new Claim("name", user.Email),
                        new Claim(JwtClaimTypes.GivenName, ""),
                        new Claim(JwtClaimTypes.FamilyName, ""),
                        new Claim("email", user.Email),
                        new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),
                    }).Result;
                    if (!claimsResult.Succeeded)
                    {
                        throw new Exception(result.Errors.First().Description);
                    }

                    return(Redirect(model.ReturnUrl));
                }

                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(error.Code, error.Description);
                }
            }

            // something went wrong, show form with error
            var vm = await BuildRegisterViewModelAsync(model);

            return(View(vm));
        }
        public async Task <IActionResult> Register(RegisterInputModel model, string button)
        {
            if (button == "login")
            {
                return(RedirectToAction("Login", model));
            }

            if (button != "register")
            {
                return(Redirect(model.ReturnUrl));
            }

            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(model.Email);

                if (user == null)
                {
                    var newUser = new ApplicationUser()
                    {
                        UserName = model.UserName,
                        Email    = model.Email
                    };

                    var status = await _userManager.CreateAsync(newUser, model.Password);

                    if (!status.Succeeded)
                    {
                        ModelState.AddModelError(string.Empty, AccountOptions.UsernameAlreadyInUseMessage);
                        return(View(await BuildRegisterViewModelAsync(model)));
                    }
                    else
                    {
                        status = await _userManager.AddClaimsAsync(newUser, new Claim[]
                        {
                            new Claim(JwtClaimTypes.Name, model.UserName),
                            new Claim(JwtClaimTypes.Email, model.Email)
                        });

                        if (!status.Succeeded)
                        {
                            throw new Exception(status.Errors.First().Description);
                        }

                        //sending email
                        var confirmationCode = await _userManager.GenerateEmailConfirmationTokenAsync(newUser);

                        var callbackUrl = Url.Action(
                            "ConfirmEmail",
                            "Account",
                            new { userId = newUser.Id, code = confirmationCode },
                            protocol: HttpContext.Request.Scheme);
                        var emailService = new EmailService();

                        await emailService.SendEmailAsync(model.Email, "Confirm your account in 15Puzzle game",
                                                          $"To activate account follow to link: <a href='{callbackUrl}'>link</a>");


                        return(View("Redirect", new RedirectViewModel {
                            RedirectUrl = model.ReturnUrl
                        }));
                    }
                }

                ModelState.AddModelError(string.Empty, AccountOptions.EmailAlreadyInUseMessage);
                var vm = await BuildRegisterViewModelAsync(model);

                return(View(vm));
            }
            else
            {
                ModelState.AddModelError(string.Empty, AccountOptions.InvalidCredentialsErrorMessage);
                var vm = await BuildRegisterViewModelAsync(model);

                return(View(vm));
            }
        }
 public LoginInputModel(RegisterInputModel model)
 {
     Email         = model.Email;
     RememberLogin = model.RememberLogin;
     ReturnUrl     = model.ReturnUrl;
 }