public JsonResult ImpersonateUser(string username)
        {
            var success = false;
            var user    = _userManager.FindByEmail(username);

            if (user != null)
            {
                _cookieService.Set(B2B.Constants.Cookies.B2BImpersonatingAdmin, User.Identity.GetUserName(), true);
                _signInManager.SignIn(user, false, false);
                success = true;
            }
            return(Json(new { success }));
        }
Пример #2
0
        public IHttpActionResult CreateUser()
        {
            try
            {
                // do an async version
                var data = Request.Content.ReadAsFormDataAsync();
                data.Wait();
                var result = data.Result;

                string username = result["newuser-username"];
                string password = result["newuser-password"];
                string email    = result["newuser-email"];

                ApplicationUser newUser = new ApplicationUser()
                {
                    UserName = username,
                    Email    = email
                };

                IdentityResult identity = ApplicationUserManager.Create(newUser, password);

                if (identity.Succeeded == false)
                {
                    return(new AuthenticationFailureResult(identity.Errors.First(), Request));
                }

                ApplicationSignInManager.SignIn(newUser, isPersistent: false, rememberBrowser: false);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.TraceError("CreateUser: " + ex);
                return(InternalServerError(ex));
            }
            return(Ok());
        }
Пример #3
0
        private void View_OnRegistering(object sender, RegisterEventArgs e)
        {
            ApplicationUserManager   manager       = e.HttpContext.GetOwinContext().GetUserManager <ApplicationUserManager>();
            ApplicationSignInManager signInManager = e.HttpContext.GetOwinContext().Get <ApplicationSignInManager>();
            User user = new User()
            {
                UserName   = e.Username,
                Email      = e.Email,
                FirstName  = e.FirstName,
                LastName   = e.LastName,
                AvatarPath = e.AvatarFilePath
            };

            IdentityResult result = manager.Create(user, e.Password);

            if (result.Succeeded)
            {
                signInManager.SignIn(user, isPersistent: false, rememberBrowser: false);
            }

            HttpPostedFileBase uploadedFile = e.AvatarFileBase;

            if (uploadedFile != null && uploadedFile.ContentLength <= MaxAvatarSizeInBytes)
            {
                uploadedFile.SaveAs(e.AvatarStorageLocation);
                this.userAvatarService.UploadAvatar(user.Id, e.AvatarFilePath);
            }

            this.View.Model.IdentityResult = result;
        }
        public ActionResult Register(RegisterViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            ApplicationUserManager userManager = Request.GetOwinContext().Get <ApplicationUserManager>();
            ApplicationUser        user        = new ApplicationUser()
            {
                Email        = model.Email,
                PasswordHash = new PasswordHasher().HashPassword(model.Password),
                UserName     = model.Email
            };

            userManager.Create(user);

            IdentityResult result = userManager.Create(user);

            if (result.Succeeded)
            {
                ApplicationSignInManager signInManager = Request.GetOwinContext().Get <ApplicationSignInManager>();
                signInManager.SignIn(user, false, false);
                return(RedirectToAction("Index", "Home"));
            }
            return(View(model));
        }
Пример #5
0
    public static bool VerifyOTP4Email(int _userId, string _token, ApplicationUserManager userMngr, ApplicationSignInManager signInMngr, out IEnumerable <string> _errors)
    {
        bool _retVal = false;

        _errors = new List <string>();
        try
        {
            ApplicationUser user = userMngr.FindById(_userId);
            if (userMngr.VerifyTwoFactorToken(user.Id, c_EmailCode, _token))
            {
                signInMngr.SignIn(user, isPersistent: false, rememberBrowser: false);
                return(true);
            }
            else
            {
                _errors = _errors = new List <string> {
                    "Invalid code..."
                };
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return(_retVal);
    }
Пример #6
0
        protected void CreateUser_Click(object sender, EventArgs e)
        {
            ApplicationUserManager   manager       = Context.GetOwinContext().GetUserManager <ApplicationUserManager>();
            ApplicationSignInManager signInManager = Context.GetOwinContext().Get <ApplicationSignInManager>();
            ApplicationUser          user          = new ApplicationUser()
            {
                UserName = Username.Text, Email = Email.Text
            };

            IdentityResult result = manager.Create(user, Password.Text);

            if (result.Succeeded)
            {
                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                string code        = manager.GenerateEmailConfirmationToken(user.Id);
                string callbackUrl = IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id, Request);
                manager.SendEmail(user.Id, "Confirm your account", "Please confirm your account by clicking this link: " + callbackUrl);

                signInManager.SignIn(user, isPersistent: false, rememberBrowser: false);
                IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
            }
            else
            {
                ErrorMessage.Text = result.Errors.FirstOrDefault();
            }
        }
Пример #7
0
        public ActionResult ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Index", "Home"));
            }

            if (ModelState.IsValid)
            {
                ExternalLoginInfo info = AuthenticationManager.GetExternalLoginInfo();
                if (info == null)
                {
                    return(View("ExternalLoginFailure"));
                }
                var user = new ApplicationUser {
                    UserName = info.DefaultUserName, Email = model.Email
                };
                IdentityResult result = UserManager.Create(user);
                if (result.Succeeded)
                {
                    result = UserManager.AddLogin(user.Id, info.Login);
                    if (result.Succeeded)
                    {
                        SignInManager.SignIn(user, false, false);
                        return(RedirectToLocal(returnUrl));
                    }
                }
                AddErrors(result);
            }

            ViewBag.ReturnUrl = returnUrl;
            return(View("AskForEmail", model));
        }
Пример #8
0
        public StatusAccountViewModel CreateLogin(string email, string name, string surName)
        {
            var info = authenticationManager.GetExternalLoginInfo();
            var user = new AppUser
            {
                UserName = email,
                Email    = email
            };

            var result = userManager.Create(user);

            if (result.Succeeded)
            {
                result = userManager.AddLogin(user.Id, info.Login);

                if (result.Succeeded)
                {
                    UserProfile userProfile = new UserProfile();
                    userProfile.Name    = name;
                    userProfile.SurName = surName;
                    userProfile.Id      = user.Id;
                    userProfileRepository.Create(userProfile);
                    userProfileRepository.SaveChanges();
                    userManager.AddToRole(user.Id, "User");
                    signInManager.SignIn(user, isPersistent: false, rememberBrowser: false);
                    return(StatusAccountViewModel.Success);
                }
            }

            return(StatusAccountViewModel.Error);
        }
Пример #9
0
 protected void Page_Load()
 {
     this.ProviderName = IdentityHelper.GetProviderNameFromRequest(this.Request);
     if (string.IsNullOrEmpty(this.ProviderName))
     {
         this.RedirectOnFail();
     }
     else
     {
         if (this.IsPostBack)
         {
             return;
         }
         ApplicationUserManager   userManager        = this.Context.GetOwinContext().GetUserManager <ApplicationUserManager>();
         ApplicationSignInManager manager            = this.Context.GetOwinContext().Get <ApplicationSignInManager>();
         ExternalLoginInfo        externalLoginInfo1 = this.Context.GetOwinContext().Authentication.GetExternalLoginInfo();
         if (externalLoginInfo1 == null)
         {
             this.RedirectOnFail();
         }
         else
         {
             ApplicationUser user = userManager.Find <ApplicationUser, string>(externalLoginInfo1.Login);
             if (user != null)
             {
                 manager.SignIn <ApplicationUser, string>(user, false, false);
                 IdentityHelper.RedirectToReturnUrl(this.Request.QueryString["ReturnUrl"], this.Response);
             }
             else if (this.User.Identity.IsAuthenticated)
             {
                 ExternalLoginInfo externalLoginInfo2 = this.Context.GetOwinContext().Authentication.GetExternalLoginInfo("XsrfId", this.User.Identity.GetUserId());
                 if (externalLoginInfo2 == null)
                 {
                     this.RedirectOnFail();
                 }
                 else
                 {
                     IdentityResult result = userManager.AddLogin <ApplicationUser, string>(this.User.Identity.GetUserId(), externalLoginInfo2.Login);
                     if (result.Succeeded)
                     {
                         IdentityHelper.RedirectToReturnUrl(this.Request.QueryString["ReturnUrl"], this.Response);
                     }
                     else
                     {
                         this.AddErrors(result);
                     }
                 }
             }
             else
             {
                 this.email.Text = externalLoginInfo1.Email;
             }
         }
     }
 }
        public async Task <ActionResult> Login(LoginUser model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                HomeFoodiesEntities _entity             = new HomeFoodiesEntities();
                ObjectResult <LoginUserGetLogin> result = _entity.SP_LoginUserGetLogin(model.UserEmail);

                if (result != null)
                {
                    LoginUserGetLogin currentUser = result.First();
                    model.UserID = currentUser.UserID;

                    if (model.UserID > 0)
                    {
                        if (model.UserPassword == currentUser.UserPassword)
                        {
                            var identity = await AppUserManager.FindByIdAsync(model.UserEmail);

                            if (identity != null)
                            {
                                AppSignInManager.SignIn(identity, isPersistent: true, rememberBrowser: true);
                                identity.LoggedInUser           = new LoginUser();
                                identity.LoggedInUser.UserID    = currentUser.UserID;
                                identity.LoggedInUser.UserEmail = currentUser.UserEmail;
                            }
                            if (!string.IsNullOrEmpty(returnUrl))
                            {
                                return(RedirectToLocal(returnUrl));
                            }
                            else
                            {
                                return(RedirectToAction("Index", "Home"));
                            }
                        }
                        else
                        {
                            ViewBag.LoggedInUserType = model.CurrentStatusID;
                            ViewBag.ValidLogin       = false;
                            ModelState.AddModelError("", "Password is wrong");
                            return(View(model));
                        }
                    }
                    else
                    {
                        ViewBag.ValidLogin = false;
                        ModelState.AddModelError("", "Invalid User ID");
                        return(View(model));
                    }
                }
            }
            return(View(model));
        }
        public ActionResult ImpersonateUser(string email)
        {
            var success = false;
            var user    = _userManager.FindByEmail(email);

            if (user != null)
            {
                _cookieService.Set(Constant.Cookies.B2BImpersonatingAdmin, User.Identity.GetUserName(), true);
                _signInManager.SignIn(user, false, false);
                success = true;
            }

            if (success)
            {
                return(Redirect("/"));
            }
            else
            {
                TempData["ImpersonateFail"] = false;
                return(RedirectToAction("Index"));
            }
        }
Пример #12
0
        public virtual ActionResult Register(RegisterModel model)
        {
            if (FeatureContext.IsEnabled <UseCaptcha>())
            {
                var recaptchaHelper = this.GetRecaptchaVerificationHelper();
                if (String.IsNullOrEmpty(recaptchaHelper.Response))
                {
                    ModelState.AddModelError("", "Captcha answer cannot be empty.");
                    return(View(MVC.Account.Views.Register, model));
                }
                var recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();
                if (recaptchaResult != RecaptchaVerificationResult.Success)
                {
                    ModelState.AddModelError("", "Incorrect captcha answer.");
                }
            }


            if (ModelState.IsValid)
            {
                var user = new User {
                    UserName = model.UserName?.Trim(), Email = model.Email?.Trim(), CreateDate = DateTime.Now
                };
                var result = userManager.Create(user, model.Password);
                if (result.Succeeded)
                {
                    signInManager.SignIn(user, isPersistent: false, rememberBrowser: false);
                    return(RedirectToAction(MVC.PvP.Play()));
                }
                else
                {
                    AddErrors(result);
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(MVC.Account.Views.Register, model));
        }
        public IdentityResult CreateUser(ApplicationUserManager manager, ApplicationSignInManager signInManager, AddUserViewModel viewModel)
        {
            var user = _userMapper.MapAddUserToModel(viewModel);

            IdentityResult result = manager.Create(user, viewModel.Password);

            if (result.Succeeded)
            {
                manager.AddToRole(user.Id, viewModel.Role);
                signInManager.SignIn(user, false, false);
            }

            return(result);
        }
Пример #14
0
        public void RemoveLogin(string loginProvider, string providerKey)
        {
            ApplicationUserManager   userManager    = this.Context.GetOwinContext().GetUserManager <ApplicationUserManager>();
            ApplicationSignInManager manager        = this.Context.GetOwinContext().Get <ApplicationSignInManager>();
            IdentityResult           identityResult = userManager.RemoveLogin <ApplicationUser, string>(this.User.Identity.GetUserId(), new UserLoginInfo(loginProvider, providerKey));
            string str = string.Empty;

            if (identityResult.Succeeded)
            {
                ApplicationUser byId = userManager.FindById <ApplicationUser, string>(this.User.Identity.GetUserId());
                manager.SignIn <ApplicationUser, string>(byId, false, false);
                str = "?m=RemoveLoginSuccess";
            }
            this.Response.Redirect("~/Account/ManageLogins" + str);
        }
        private bool setSession(vmLogin model)
        {
            try
            {
                this.isModelValid();

                model = model.getData();

                dynamic data = null;
                var     sc   = new StringContent(JsonConvert.SerializeObject(new { username = model.username, password = model.password }), Encoding.UTF8, "application/json");

                using (HttpClient hc = new HttpClient())
                {
                    hc.BaseAddress = new Uri(Config.getValue("webapi"));
                    HttpResponseMessage hrm = hc.PostAsync("api/login", sc).Result;

                    if (hrm.IsSuccessStatusCode)
                    {
                        data = JObject.Parse(hrm.Content.ReadAsStringAsync().Result);
                    }
                    else
                    {
                        throw new Exception("Error Code: " + hrm.StatusCode + "|Message: " + hrm.ReasonPhrase);
                    }
                }

                ApplicationUser appUser = new ApplicationUser()
                {
                    Id       = Assess.setString((string)data.user.id).ToLower(),
                    UserName = Assess.setString((string)data.user.name),
                    Token    = Assess.setString((string)data.token),
                };

                ApplicationSignInManager signInManager = this.HttpContext.GetOwinContext().Get <ApplicationSignInManager>();
                signInManager.SignIn(appUser, isPersistent: model.rememberme, rememberBrowser: false);

                return(true);
            }
            catch (Exception ex)
            {
                this.addModelError(ex);
            }

            return(false);
        }
Пример #16
0
        protected void RemovePhone_Click(object sender, EventArgs e)
        {
            ApplicationUserManager   userManager = this.Context.GetOwinContext().GetUserManager <ApplicationUserManager>();
            ApplicationSignInManager manager     = this.Context.GetOwinContext().Get <ApplicationSignInManager>();

            if (!userManager.SetPhoneNumber <ApplicationUser, string>(this.User.Identity.GetUserId(), (string)null).Succeeded)
            {
                return;
            }
            ApplicationUser byId = userManager.FindById <ApplicationUser, string>(this.User.Identity.GetUserId());

            if (byId == null)
            {
                return;
            }
            manager.SignIn <ApplicationUser, string>(byId, false, false);
            this.Response.Redirect("/Account/Manage?m=RemovePhoneNumberSuccess");
        }
Пример #17
0
        public IdentityResult Register(RegistrationRequest model)
        {
            ApplicationUser user = new ApplicationUser {
                UserName = model.Email, Email = model.Email
            };
            IdentityResult result = _userManager.Create(user, model.Password);

            if (result.Succeeded)
            {
                _signInManager.SignIn(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(result);
        }
Пример #18
0
        protected void ChangePassword_Click(object sender, EventArgs e)
        {
            if (!this.IsValid)
            {
                return;
            }
            ApplicationUserManager   userManager = this.Context.GetOwinContext().GetUserManager <ApplicationUserManager>();
            ApplicationSignInManager manager     = this.Context.GetOwinContext().Get <ApplicationSignInManager>();
            IdentityResult           result      = userManager.ChangePassword <ApplicationUser, string>(this.User.Identity.GetUserId(), this.CurrentPassword.Text, this.NewPassword.Text);

            if (result.Succeeded)
            {
                ApplicationUser byId = userManager.FindById <ApplicationUser, string>(this.User.Identity.GetUserId());
                manager.SignIn <ApplicationUser, string>(byId, false, false);
                this.Response.Redirect("~/Account/Manage?m=ChangePwdSuccess");
            }
            else
            {
                this.AddErrors(result);
            }
        }
Пример #19
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                ApplicationUserManager usermanager = Request.GetOwinContext().Get <ApplicationUserManager>();

                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email, PasswordHash = new PasswordHasher().HashPassword(model.Password)
                };
                var result = usermanager.Create(user);
                if (result.Succeeded)
                {
                    ApplicationSignInManager signinManager = Request.GetOwinContext().Get <ApplicationSignInManager>();
                    signinManager.SignIn(user, false, false);

                    return(RedirectToAction("Index", "Home"));
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Пример #20
0
 protected void Code_Click(object sender, EventArgs e)
 {
     if (!this.ModelState.IsValid)
     {
         this.ModelState.AddModelError("", "Invalid code");
     }
     else
     {
         ApplicationUserManager   userManager = this.Context.GetOwinContext().GetUserManager <ApplicationUserManager>();
         ApplicationSignInManager manager     = this.Context.GetOwinContext().Get <ApplicationSignInManager>();
         if (userManager.ChangePhoneNumber <ApplicationUser, string>(this.User.Identity.GetUserId(), this.PhoneNumber.Value, this.Code.Text).Succeeded)
         {
             ApplicationUser byId = userManager.FindById <ApplicationUser, string>(this.User.Identity.GetUserId());
             if (byId != null)
             {
                 manager.SignIn <ApplicationUser, string>(byId, false, false);
                 this.Response.Redirect("/Account/Manage?m=AddPhoneNumberSuccess");
             }
         }
         this.ModelState.AddModelError("", "Failed to verify phone");
     }
 }
Пример #21
0
        public virtual ActionResult ZmienHaslo(ChangePasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(PartialView("_ChangePassword", model));
            }
            var result = _userManager.ChangePassword(int.Parse(User.Identity.GetUserId()), model.OldPassword,
                                                     model.NewPassword);

            if (result.Succeeded)
            {
                var user = _userManager.FindById(int.Parse(User.Identity.GetUserId()));
                if (user != null)
                {
                    _signInManager.SignIn(user, false, false);
                }
                model.Success = true;
                return(PartialView("_ChangePassword", model));
            }
            ModelState.AddModelError("OldPassword", "Nieprawidłowe hasło.");
            return(PartialView("_ChangePassword", model));
        }
Пример #22
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    UserDetail newUserDetail = new UserDetail();
                    newUserDetail.UserId    = user.Id;
                    newUserDetail.FirstName = model.FirstName;
                    newUserDetail.LastName  = model.LastName;
                    LMSEntities db = new LMSEntities();
                    db.UserDetails.Add(newUserDetail);
                    db.SaveChanges();

                    var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                    var defaultRole = await UserManager.AddToRoleAsync(user.Id, "Employee");

                    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 this link: <a href=\"" + callbackUrl + "\">link</a>");

                    ViewBag.Link = callbackUrl;
                    //return View("DisplayEmail");

                    SignInManager.SignIn(user, isPersistent: false, rememberBrowser: false);
                    return(RedirectToAction("../Home/Index"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Пример #23
0
        public ActionResult Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            var user = UserManager.FindByName(model.Username.Trim());

            if (model.Password == user.PasswordHash && user.UserActive)
            {
                SignInManager.SignIn(user, model.RememberMe, false);
                if (string.IsNullOrEmpty(returnUrl))
                {
                    returnUrl = "/Home/Index";
                }
                return(RedirectToAction("FilterUserType", "Home", new { username = model.Username }));
                //return RedirectToLocal(returnUrl);
            }
            else
            {
                ModelState.AddModelError("", "Invalid login attempt.");
                return(View(model));
            }
        }
Пример #24
0
        public ActionResult Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    UserName       = model.Email,
                    Email          = model.Email,
                    EmailConfirmed = true
                };
                var result = _userManager.Create(user, model.Password);
                if (result.Succeeded)
                {
                    _signInManager.SignIn(user, false, false);

                    return(RedirectToAction("Index", "Home"));
                }

                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Пример #25
0
        private void CreateAndLoginUser()
        {
            if (!this.IsValid)
            {
                return;
            }
            ApplicationUserManager   userManager1    = this.Context.GetOwinContext().GetUserManager <ApplicationUserManager>();
            ApplicationSignInManager userManager2    = this.Context.GetOwinContext().GetUserManager <ApplicationSignInManager>();
            ApplicationUser          applicationUser = new ApplicationUser();
            string text1 = this.email.Text;

            applicationUser.UserName = text1;
            string text2 = this.email.Text;

            applicationUser.Email = text2;
            ApplicationUser user   = applicationUser;
            IdentityResult  result = userManager1.Create <ApplicationUser, string>(user);

            if (result.Succeeded)
            {
                ExternalLoginInfo externalLoginInfo = this.Context.GetOwinContext().Authentication.GetExternalLoginInfo();
                if (externalLoginInfo == null)
                {
                    this.RedirectOnFail();
                    return;
                }
                result = userManager1.AddLogin <ApplicationUser, string>(user.Id, externalLoginInfo.Login);
                if (result.Succeeded)
                {
                    userManager2.SignIn <ApplicationUser, string>(user, false, false);
                    IdentityHelper.RedirectToReturnUrl(this.Request.QueryString["ReturnUrl"], this.Response);
                    return;
                }
            }
            this.AddErrors(result);
        }
Пример #26
0
    public static RBACStatus VerifyOTP4Phone(int _userId, string _phoneNumber, string _token, ApplicationUserManager userMngr, ApplicationSignInManager signInMngr, out IEnumerable <string> _errors)
    {
        RBACStatus _retVal = RBACStatus.Failure;

        try
        {
            IdentityResult result = userMngr.ChangePhoneNumber(_userId, _phoneNumber, _token);
            if (result == IdentityResult.Success)
            {
                ApplicationUser user = userMngr.FindById(_userId);
                if (user != null)
                {
                    signInMngr.SignIn(user, isPersistent: false, rememberBrowser: false);
                }
                _retVal = RBACStatus.Success;
            }
            _errors = result.Errors;
        }
        catch (Exception)
        {
            throw;
        }
        return(_retVal);
    }
Пример #27
0
        public ActionResult ChangePassword(ChangePasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var result = _userManager.ChangePassword(User.Identity.GetUserId(), model.OldPassword, model.NewPassword);

            if (result.Succeeded)
            {
                var user = _userManager.FindById(User.Identity.GetUserId());

                if (user != null)
                {
                    _signInManager.SignIn(user, false, false);
                }

                return(RedirectToAction("Index", new { Message = ManageMessageId.ChangePasswordSuccess }));
            }
            AddErrors(result);

            return(View(model));
        }
Пример #28
0
        public ActionResult ReturnFrom(RedSocial tipo, string code)
        {
            var goTo = CacheHelper.GetKey(CacheHelper.GetNotLoggedUserKey());

            try
            {
                using (WebClient client = new WebClient())
                {
                    ISocialUser user;
                    byte[]      response;
                    switch (tipo)
                    {
                    case RedSocial.Google:
                        throw new Exception("Loggeo incorrecto con Google");
                        break;

                    case RedSocial.Instagram:
                        response =
                            client.UploadValues("https://api.instagram.com/oauth/access_token", new NameValueCollection()
                        {
                            { "client_id", SocialIds.InstagramClientId },
                            { "client_secret", SocialIds.InstagramClientSecret },
                            { "grant_type", SocialIds.InstagramGrantType },
                            { "redirect_uri", (WebConfigurationManager.AppSettings["Core"] + WebConfigurationManager.AppSettings["urlInstagramRedirect"]) },
                            { "code", code },
                        });

                        InstagramResponseValidationCode responseI = JsonConvert.DeserializeObject <InstagramResponseValidationCode>(System.Text.Encoding.UTF8.GetString(response));
                        user = responseI.user;
                        ((InstagramUser)user).Token = responseI.access_token;

                        break;

                    case RedSocial.FaceBook:
                        response = client.UploadValues("https://graph.facebook.com/v2.9/oauth/access_token", new NameValueCollection()
                        {
                            { "client_id", SocialIds.FacebookAppId },
                            { "redirect_uri", WebConfigurationManager.AppSettings["Core"] + WebConfigurationManager.AppSettings["urlFacebookRedirect"] },
                            { "client_secret", SocialIds.FacebookSecret },
                            { "code", code }
                        });

                        FacebookResponseValidationCode obj = JsonConvert.DeserializeObject <FacebookResponseValidationCode>(System.Text.Encoding.UTF8.GetString(response));

                        //No se por que no anda de esta forma
                        //byte[] userResponse = client.UploadValues("https://graph.facebook.com/v2.9/me", new NameValueCollection()
                        //{
                        //    { "fields", "email,id,first_name,last_name,name,picture.type(large)" },
                        //    { "access_token", obj.access_token }
                        //});

                        //FacebookUser fbUser = JsonConvert.DeserializeObject<FacebookUser>(System.Text.Encoding.UTF8.GetString(response));
                        //user = fbUser;
                        using (HttpClient cliente = new HttpClient())
                        {
                            var mess = cliente.GetStringAsync("https://graph.facebook.com/me?fields=email,name,picture.type(large),id&access_token=" + obj.access_token);
                            user = JsonConvert.DeserializeObject <FacebookUser>(mess.Result);
                            ((FacebookUser)user).Token = obj.access_token;
                        }
                        break;

                    case RedSocial.Spotify:
                        SpotifyResponseValidationCode responseS;
                        using (HttpClient cliente = new HttpClient())
                        {
                            Dictionary <string, string> postData = new Dictionary <string, string>();
                            postData.Add("grant_type", "authorization_code");
                            postData.Add("code", code);
                            postData.Add("redirect_uri", WebConfigurationManager.AppSettings["Core"] + WebConfigurationManager.AppSettings["urlSpotifyRedirect"]);
                            postData.Add("client_id", SocialIds.SpotifyClientId);
                            postData.Add("client_secret", SocialIds.SpotifySecret);
                            var content      = new FormUrlEncodedContent(postData);
                            var httpResponse = cliente.PostAsync("https://accounts.spotify.com/api/token", content).Result.Content.ReadAsStringAsync().Result;
                            responseS = JsonConvert.DeserializeObject <SpotifyResponseValidationCode>(httpResponse);
                        }
                        using (HttpClient cliente = new HttpClient())
                        {
                            cliente.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", responseS.access_token);

                            var mess = cliente.GetAsync("https://api.spotify.com/v1/me").Result.Content.ReadAsStringAsync();
                            user = JsonConvert.DeserializeObject <SpotifyUser>(mess.Result);
                            ((SpotifyUser)user).accessToken = responseS.access_token;
                        }
                        break;

                    case RedSocial.SoundCloud:
                        throw new Exception("Loggeo incorrecto con SoundCloud");
                        break;

                    default:
                        throw new Exception("Loggeo incorrecto con Random");
                        break;
                    }


                    if (ExisteUsuarioSocial(user.GetId()))
                    {
                        //existe el user, loguearlo
                        var id         = user.GetId();
                        var userSocial = new Repositorio <UsuarioSocial>(new ApplicationDbContext()).TraerTodos().Single(u => u.IdSocial == id);
                        var usuarios   = new Repositorio <Clubber>(db).TraerTodos()
                                         .Where(r => r.CredencialesSociales.Any(c => c.IdSocial == userSocial.IdSocial));

                        SignInManager.SignIn(usuarios.First().UsuarioApplicacion, true, true);

                        if (string.IsNullOrEmpty(goTo))
                        {
                            return(RedirectToAction("Index", "Frontend"));
                        }
                        else
                        {
                            return(RedirectToLocal(goTo.ToString()));
                        }
                    }
                    else
                    {
                        //no existe el user -> crearlo
                        var nuevo = new RegisterFrontViewModel();
                        nuevo.Name     = user.GetName();
                        nuevo.IdSocial = user.GetId();
                        nuevo.Email    = string.IsNullOrWhiteSpace(user.GetEmail()) ? user.GetName().Replace(" ", "") + "@danzfloor.com.ar" : user.GetEmail();

                        var clubberRepo = new Repositorio <Clubber>(db);
                        if (clubberRepo.TraerTodos().Any(u => u.UsuarioApplicacion.UserName == nuevo.Email))
                        {
                            var clubber    = clubberRepo.TraerTodos().First(u => u.UsuarioApplicacion.UserName == nuevo.Email);
                            var userSocial = new UsuarioSocial
                            {
                                AccessToken = user.GetAccessToken(),
                                Apellido    = "",
                                Email       = user.GetEmail(),
                                Nombre      = user.GetName(),
                                IdSocial    = user.GetId(),
                                RedSocial   = user is FacebookUser ? RedSocial.FaceBook : user is SpotifyUser ? RedSocial.Spotify : RedSocial.Instagram,
                            };

                            clubber.CredencialesSociales = new List <Models.Dominio.UsuarioSocial>();
                            clubber.CredencialesSociales.Add(userSocial);
                            clubberRepo.GuardarCambios();



                            SignInManager.SignIn(clubber.UsuarioApplicacion, true, true);

                            return(RedirectToAction("Index", "Frontend"));
                        }

                        var appUser = new ApplicationUser
                        {
                            UserName = nuevo.Email,
                            Email    = nuevo.Email,
                            Name     = nuevo.Name,
                            Lastname = "",
                            TokenFechaVencimiento = DateTime.Now.AddDays(7),
                        };


                        var usuario = new Clubber();
                        usuario.UsuarioApplicacion = appUser;
                        usuario.Nombre             = nuevo.Name;
                        usuario.Apellido           = "";
                        usuario.Email           = nuevo.Email;
                        usuario.FechaNacimiento = DateTime.Now;
                        usuario.Sexo            = new Repositorio <Sexo>(db).TraerTodos().First();

                        if (!string.IsNullOrWhiteSpace(user.GetId()))
                        {
                            var userSocial = new UsuarioSocial
                            {
                                Apellido  = "",
                                Email     = nuevo.Email,
                                Nombre    = nuevo.Name,
                                IdSocial  = nuevo.IdSocial,
                                RedSocial = RedSocial.Instagram,
                            };

                            usuario.CredencialesSociales = new List <Models.Dominio.UsuarioSocial>();
                            usuario.CredencialesSociales.Add(userSocial);
                        }
                        new Repositorio <Usuario>(db).Crear(usuario);
                        UserManager.AddPassword(usuario.UsuarioApplicacion.Id, "qweQWE123!#");

                        UserManager.AddToRole(appUser.Id, RoleConst.Clubber);

                        SignInManager.SignIn(appUser, true, true);

                        return(RedirectToAction("Index", "Frontend"));
                    }
                }
            }
            catch (Exception ex)
            {
                return(null);
            }
        }