Exemplo n.º 1
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new MyApplicationUser {
                    UserName = model.Email, Email = model.Email, DataUrodzenia = model.DataUrodzenia
                };
                var result = await userManager.CreateAsync(user, model.Password);

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

                    // For more information on how to enable account confirmation and password reset please visit http://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>");
                    return(RedirectToAction("Index", "Home"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Exemplo n.º 2
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            var appUser = new MyApplicationUser {
                UserName = model.Email, Email = model.Email
            };
            var result = await MyUserManager.CreateAsync(appUser, model.Password);

            /*UsersModel user = new UsersModel();
             * //user.Id = Guid.NewGuid().ToString();
             * user.UserName = model.Username;
             * user.Password = model.Password;
             * user.Email = model.Email;
             * user.EmailConfirmed = false;
             * user.PhoneNumberConfirmed = false;
             * user.TwoFactorEnabled = false;
             * user.LockoutEnabled = false;
             * user.AccessFailedCount = 0;
             *
             * CommonBLL bll = new CommonBLL();
             *
             * object result = bll.Add(user, true);*/

            if (result.Succeeded)
            {
                await MySignInManager.SignInAsync(appUser, isPersistent : false, rememberBrowser : false);

                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                return(View(model));
            }
        }
Exemplo n.º 3
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 MyApplicationUser {
                    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));
        }
Exemplo n.º 4
0
        public async Task <IActionResult> Register(RegisterViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                var user = new MyApplicationUser {
                    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.ToString(), 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));
        }
        private void GetUserViewModel(RegisterViewModel regModel, MyApplicationUser myAppUser, DateTime fecha)
        {
            if (regModel != null)
            {
                myAppUser.UserProfileInfo.UserNames = regModel.Names;

                //myAppUser.Email = regModel.Email;

                //myAppUser.CardUser = regModel.Card;

                myAppUser.TypeUser = "******";

                //myAppUser.UserProfileInfo.CreationDate = regModel.CreationDate;

                myAppUser.UserProfileInfo.UserLastName1 = regModel.LastName1;

                myAppUser.UserProfileInfo.UserLastName2 = regModel.LastName2;

                myAppUser.UserProfileInfo.UserFemale = regModel.CGenre == Genre.Female;

                myAppUser.UserProfileInfo.UserBirthDate = fecha;

                myAppUser.UserProfileInfo.UserCodePostal = regModel.CodePostal;

                myAppUser.UserProfileInfo.UserCity = regModel.City;

                //myAppUser.UserProfileInfo.UserImagePerfil = regModel.UserImage;

                myAppUser.PhoneNumber = regModel.PhoneNumber;
            }
        }
        public async Task <ActionResult> DeleteContactUserConfirmed(int id)
        {
            MyApplicationUser user = await db.Users.FirstAsync(x => x.Id == id);

            db.Users.Remove(user);
            await db.SaveChangesAsync();

            return(RedirectToAction("UserReg"));
        }
Exemplo n.º 7
0
        private async Task LoadAsync(MyApplicationUser user)
        {
            var userName = await _userManager.GetUserNameAsync(user);

            var phoneNumber = await _userManager.GetPhoneNumberAsync(user);

            var currentUser = await _userManager.GetUserAsync(User);

            Username = userName;

            Input = new InputModel
            {
                PhoneNumber = phoneNumber,
                RecommendTravelDestination = currentUser.RecommendTravelDestination
            };
        }
        private RegisterViewModel GetRegisterViewModel(MyApplicationUser user)
        {
            RegisterViewModel regModel = new RegisterViewModel();

            if (user != null)
            {
                var perfil = user.UserProfileInfo;

                regModel.Names = perfil.UserNames;

                regModel.Email = user.Email;

                regModel.Card = user.CardUser;

                regModel.CreationDate = perfil.UserCreationDate;

                regModel.LastName1 = perfil.UserLastName1;

                regModel.LastName2 = perfil.UserLastName2;

                regModel.LastNames = $"{perfil.UserLastName1} {perfil.UserLastName2}";

                regModel.CGenre = perfil.UserFemale ? Genre.Female : Genre.Male;

                //regModel.BirthDate = perfil.UserBirthDate != null ?
                //    $"{perfil.UserBirthDate.Value.Month}/{perfil.UserBirthDate.Value.Day}/{perfil.UserBirthDate.Value.Year}"
                //    : null;
                regModel.BirthDate = perfil.UserBirthDate != null?
                                     convertToDate(perfil.UserBirthDate)
                                         : null;

                regModel.CodePostal = perfil.UserCodePostal;

                regModel.City = perfil.UserCity;

                regModel.UserImage = perfil.UserImagePerfil;

                regModel.PhoneNumber = user.PhoneNumber;

                regModel.UserId = user.Id;
            }
            regModel.ConditionsTermsPage = db.ConditionsTermsPages.FirstOrDefault(x => x.ConditionsTermsPageActive);
            return(regModel);
        }
Exemplo n.º 9
0
        /// <summary>
        /// akcja dodania usera
        /// </summary>
        /// <returns></returns>
        public async Task <string> AddUser()
        {
            MyApplicationUser        user;
            MyApplicationUserStore   Store       = new MyApplicationUserStore(new MyApplicationDbContext()); //(MyApplicationUserStore)(new UserStore<MyApplicationUser>(new MyApplicationDbContext()));  //-to samo robi
            MyApplicationUserManager userManager = new MyApplicationUserManager(Store);

            user = new MyApplicationUser
            {
                UserName      = "******",
                Email         = "*****@*****.**",
                DataUrodzenia = DateTime.Parse("1990-05-25")
            };

            var result = await userManager.CreateAsync(user);

            if (!result.Succeeded)
            {
                return(result.Errors.First());
            }
            return("User Added");
        }
Exemplo n.º 10
0
        public async Task <ActionResult> ExternalLoginConfirmation(Models.ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Index", "Manage"));
            }

            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await AuthenticationManager.GetExternalLoginInfoAsync();

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

                if (result.Succeeded)
                {
                    result = await UserManager.AddLoginAsync(user.Id, info.Login);

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

                        return(RedirectToLocal(returnUrl));
                    }
                }
                AddErrors(result);
            }

            ViewBag.ReturnUrl = returnUrl;
            return(View(model));
        }
        public async Task <ActionResult> Create(RegisterViewModel model)
        {
            var response = new AjaxResponse {
                Success = false
            };

            try
            {
                if (ModelState.IsValid)
                {
                    var user = UserManager.FindByName(model.Email);
                    if (user == null)
                    {
                        const string   roleName   = "Admin";
                        IdentityResult resultRole = IdentityResult.Success;
                        var            role       = RoleManager.FindByName(roleName);
                        if (role == null)
                        {
                            role       = new MyApplicationRole(roleName, "Role Admin");
                            resultRole = RoleManager.Create(role);
                        }

                        DateTime?fecha = null;
                        if (!string.IsNullOrEmpty(model.BirthDate))
                        {
                            try
                            {
                                fecha = DateTime.ParseExact(model.BirthDate, "dd/MM/yyyy", null);
                            }catch
                            {
                                response.Message = "La fecha no es válida.";
                                return(Json(response, JsonRequestBehavior.AllowGet));
                            }
                        }

                        DateTime dateC = DateTime.Now;
                        user = new MyApplicationUser
                        {
                            UserName        = model.Email,
                            Email           = model.Email,
                            CardUser        = Guid.NewGuid().ToString(),
                            PhoneNumber     = model.PhoneNumber,
                            TypeUser        = "******",
                            UserProfileInfo = new UserProfileInfo
                            {
                                UserNames                  = model.Names,
                                UserLastName1              = model.LastName1,
                                UserLastName2              = model.LastName2,
                                UserBirthDate              = fecha.Value,
                                UserFemale                 = model.CGenre == Genre.Female,
                                UserHasChildren            = model.HasChildren == YesNo.Sí,
                                UserClubPeques             = model.ClubPeques == YesNo.Sí,
                                UserMount                  = model.Mount,
                                UserCreationDate           = dateC,
                                UserUpdateDate             = dateC,
                                UserCreationDateClubPeques = dateC,
                                UserCity       = model.City,
                                UserCodePostal = model.CodePostal,
                            }
                        };

                        IdentityResult resultUser = await UserManager.CreateAsync(user, model.Password);

                        if (resultUser == IdentityResult.Success && resultRole == IdentityResult.Success)
                        {
                            UserManager.SetLockoutEnabled(user.Id, false);

                            // Add user admin to Role Admin if not already added
                            var rolesForUser = UserManager.GetRoles(user.Id);
                            if (!rolesForUser.Contains(role.Name))
                            {
                                UserManager.AddToRole(user.Id, role.Name);
                                response.Success = true;
                                response.Message = "La cuenta de usuario se creó satisfactoriamente.";
                                return(Json(response, JsonRequestBehavior.AllowGet));
                            }
                        }
                    }
                    else
                    {
                        response.Message = "Ya existe la dirección de correo, introduzca otra.";
                        return(Json(response, JsonRequestBehavior.AllowGet));
                    }
                }
                response.Message = "Los datos no son válidos";
                return(Json(response, JsonRequestBehavior.AllowGet));
            }
            catch (Exception)
            {
                response.Message = "Ha ocurrido un error al intentar crear la cuenta de usuario.";
                return(Json(response, JsonRequestBehavior.AllowGet));
            }
        }