コード例 #1
0
        public async Task <object> Login(LoginBindingModel model)
        {
            if (ModelState.IsValid)
            {
                var result = SignInManager.PasswordSignIn(model.email, model.password, false, false);
                if (result == SignInStatus.Success)
                {
                    var user      = UserManager2.FindUser(model.email);
                    var usermodel = UserManager2.GetUserModel(user.Id);

                    ClaimsIdentity oAuthIdentity = await UserManager.CreateIdentityAsync(user, OAuthDefaults.AuthenticationType);

                    ClaimsIdentity cookiesIdentity = await UserManager.CreateIdentityAsync(user, CookieAuthenticationDefaults.AuthenticationType);

                    AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
                    Authentication.SignIn(properties, oAuthIdentity, cookiesIdentity);
                    var token = GetToken(model.email, model.password);

                    return(new
                    {
                        token = token,
                        user = usermodel
                    });
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            return(BadRequest(ModelState));
        }
コード例 #2
0
        public async Task <System.Web.Http.IHttpActionResult> UpdateAvatar()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            var user     = UserManager2.FindUser(User.Identity.Name);
            var provider = new MultipartMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(provider);

            var fileManager = new AzureFileManager();

            foreach (var file in provider.Contents)
            {
                var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
                var buffer   = await file.ReadAsByteArrayAsync();

                //Do whatever you want with filename and its binary data.

                var result = fileManager.UploadFileAsync(buffer, $"{user.Id}.png");//pass file stream

                if (string.IsNullOrEmpty(result.Result))
                {
                    return(BadRequest(result.Result));
                }


                var info = UserManager2.FindUserInfo(user.UserInfoId);
                info.PhotoUrl = result.Result;
                UserManager2.UpdateInfo(info);
            }

            return(Ok());
        }
コード例 #3
0
        public object Registration(User user)
        {
            logger.Log(LogLevel.Debug, $"UserController.Registration({Json(user)})");
            try
            {
                var result = UserManager2.Register(user);

                try
                {
                    GroupManager.CreateFavorites(result.Id);
                }
                catch (Exception e)
                {
                    logger.Log(LogLevel.Error, $"Не смог создать группу избранное." +
                               $"UserController.Registration({Json(user)}) - {e}");
                }

                return(new HttpStatusCodeResult(200));
            }
            catch (Exception ex)
            {
                logger.Log(LogLevel.Error, $"UserController.Registration({Json(user)}) - {ex}");
                //изменить http status code
                return(new Response(100, ex.Message));
            }
        }
コード例 #4
0
        public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                //var user = await UserManager.FindByNameAsync(model.Email);
                var user = await UserManager2.FindByEmailAsync(model.Email);

                if (user == null || !(await UserManager2.IsEmailConfirmedAsync(user.Id)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    ModelState.AddModelError("", "無效的帳號");
                    return(View());
                }

                var code = await UserManager2.GeneratePasswordResetTokenAsync(user.Id);

                var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                await UserManager2.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking here: <a href=\"" + callbackUrl + "\">link</a>");

                ViewBag.Link = callbackUrl;
                return(View("ForgotPasswordConfirmation"));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
コード例 #5
0
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                return(RedirectToAction("Login"));
            }

            if (loginInfo.Login.LoginProvider == "Facebook")
            {
                var     identity     = AuthenticationManager.GetExternalIdentity(DefaultAuthenticationTypes.ExternalCookie);
                var     access_token = identity.FindFirstValue("FacebookAccessToken");
                var     fb           = new FacebookClient(access_token);
                dynamic myInfo       = fb.Get("/me?fields=email"); // specify the email field
                loginInfo.Email = myInfo.email;
                //var fb =
            }

            if (loginInfo.Login.LoginProvider == "Google")
            {
                var identity     = AuthenticationManager.GetExternalIdentity(DefaultAuthenticationTypes.ExternalCookie);
                var access_token = identity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email);
                var email        = access_token.Value;
                loginInfo.Email = email;
                //var fb =
            }

            var user = UserManager2.FindByEmail(loginInfo.Email);

            if (user == null)
            {
                Session["SingInEmail"] = loginInfo.Email;
                return(RedirectToAction("Register"));
            }
            else
            {
                Session["SingInEmail"] = loginInfo.Email;
                return(RedirectToAction("Login"));
            }

            // Sign in the user with this external login provider if the user already has a login
            //var result = await SignInManager2.ExternalSignInAsync(loginInfo, isPersistent: false);
            //switch (result)
            //{
            //    case SignInStatus.Success:
            //        return RedirectToLocal(returnUrl);
            //    case SignInStatus.LockedOut:
            //        return View("Lockout");
            //    case SignInStatus.RequiresVerification:
            //        return RedirectToAction("SendCode", new { ReturnUrl = returnUrl });
            //    case SignInStatus.Failure:
            //    default:
            //        // If the user does not have an account, then prompt the user to create an account
            //        ViewBag.ReturnUrl = returnUrl;
            //        ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
            //        return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });
            //}
        }
コード例 #6
0
        public async Task <IHttpActionResult> ProcessExternalLogin()
        {
            ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);

            if (externalLogin == null)
            {
                return(InternalServerError());
            }

            var user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey));

            bool hasRegistered = user != null;

            if (!hasRegistered)
            {
                //зарегестрировать и авторизировать пользователя
                IEnumerable <Claim> claims   = externalLogin.GetClaims();
                ClaimsIdentity      identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);

                var userInfo = UserManager2.CreateUserInfo("", externalLogin.UserName, "", "", "");

                user = new User()
                {
                    UserName      = externalLogin.UserName,
                    PasswordHash  = null,
                    IsActive      = true,
                    UserType      = (int)UserTypeEnum.Client,
                    UserInfoId    = userInfo.Id,
                    AccountPlanId = (int)AccountPlanEnum.Start,
                    Registration  = DateTime.Now,
                    LastUpdate    = DateTime.Now
                };

                IdentityResult result = await UserManager.CreateAsync(user);

                IdentityResult loginResult = await UserManager.AddLoginAsync(user.Id, new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey));

                //SignInManager.SignIn(user, false, false);
                //Authentication.SignIn(identity);
            }

            //авторизировать пользователя
            SignInManager.SignOut();
            //Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

            ClaimsIdentity oAuthIdentity = await UserManager.CreateIdentityAsync(user, OAuthDefaults.AuthenticationType);

            ClaimsIdentity cookiesIdentity = await UserManager.CreateIdentityAsync(user, CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);

            SignInManager.SignIn(user, false, false);
            //Authentication.SignIn(properties, oAuthIdentity, cookiesIdentity);

            return(Ok());
        }
コード例 #7
0
        public async Task <ActionResult> ConfirmEmail(int userId, string code)
        {
            if (userId == 0 || code == null)
            {
                return(View("Error"));
            }
            var result = await UserManager2.ConfirmEmailAsync(userId, code);

            return(View(result.Succeeded ? "ConfirmEmail" : "Error"));
        }
コード例 #8
0
        private async Task SignInAsync(ApplicationUser2 user, bool isPersistent)
        {
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);

            var identity = await UserManager2.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

            AuthenticationManager.SignIn(new AuthenticationProperties()
            {
                IsPersistent = isPersistent
            }, identity);
        }
コード例 #9
0
        public async Task <ActionResult> ResetPassword(ResetPasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                TempData["ViewData"] = ViewData;
                if (!string.IsNullOrEmpty(model.ReturnUrl))
                {
                    return(Redirect(model.ReturnUrl));
                }
                return(View(model));
            }
            var user = await UserManager2.FindByEmailAsync(model.Email);

            if (user == null)
            {
                ModelState.AddModelError("", "使用者不存在");
                if (!string.IsNullOrEmpty(model.ReturnUrl))
                {
                    return(Redirect(model.ReturnUrl));
                }
                // Don't reveal that the user does not exist
                return(View());
            }

            //var code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

            //if (string.IsNullOrEmpty(model.Code) || !code.Equals(model.Code))
            //{
            //    TempData["SuccessMessage"] = "密碼已變更,下次請使用新密碼";
            //    return Redirect(model.ReturnUrl);
            //}

            var result = await UserManager2.ResetPasswordAsync(user.Id, model.Code, model.Password);

            if (result.Succeeded)
            {
                if (!string.IsNullOrEmpty(model.ReturnUrl))
                {
                    TempData["SuccessMessage"] = "密碼已變更,下次請使用新密碼";
                    return(Redirect(model.ReturnUrl));
                }
                return(RedirectToAction("ResetPasswordConfirmation", "Account"));
            }
            AddErrors(result);
            TempData["ViewData"] = ViewData;
            if (!string.IsNullOrEmpty(model.ReturnUrl))
            {
                return(Redirect(model.ReturnUrl));
            }
            return(View());
        }
コード例 #10
0
 public object Find(string login)
 {
     logger.Log(LogLevel.Debug, $"UserController.Find({login})");
     try
     {
         return(UserManager2.FindUser(login));
     }
     catch (Exception ex)
     {
         logger.Log(LogLevel.Error, $"UserController.Find({login}) - {ex}");
         //изменить http status code
         return(new Response(100, ex.Message));
     }
 }
コード例 #11
0
        public async Task <object> ChangeUsername(ChangeUsernameBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = UserManager2.GetUserModel(User.Identity.GetUserId <long>());

            user.username = model.username;
            user          = UserManager2.Update(user);

            return(user);
        }
コード例 #12
0
 public object Update(UserModel user)
 {
     logger.Log(LogLevel.Debug, $"UserController.Update({Json(user)})");
     try
     {
         return(UserManager2.Update(user));
     }
     catch (Exception ex)
     {
         logger.Log(LogLevel.Error, $"UserController.Update({Json(user)}) - {ex}");
         //изменить http status code
         return(new Response(100, ex.Message));
     }
 }
コード例 #13
0
        public async Task <ActionResult> Join(RegisterViewModel model)
        {
            var Recommend = Session["RecommendCode"] == null ? string.Empty : Session["RecommendCode"].ToString();

            ViewBag.Recommend = Recommend;
            //AddRoles();
            //var Recommend = string.Empty;
            if (string.IsNullOrEmpty(model.Recommend))
            {
                model.Recommend = OfficalRecommendCode;
            }
            else
            {
                model.Recommend = GetRecommendUserCode(model.Recommend);
            }
            //model.Recommend = Recommend;
            model.UserCode = new Anything.Helpers.BaseDLL().GetUserCode(model.UserName);
            model.UserType = "User";
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser2 {
                    UserName = model.UserName, Email = model.Email, UserType = model.UserType, UserCode = model.UserCode, Recommend = model.Recommend
                };
                var result = await UserManager2.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    var roleName = model.UserType;
                    if (!RoleManager2.RoleExists(roleName))
                    {
                        var role = new Role2(roleName);
                        await RoleManager2.CreateAsync(role);
                    }

                    UserManager2.AddToRole(user.Id, model.UserType);
                    var code = await UserManager2.GenerateEmailConfirmationTokenAsync(user.Id);

                    var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    await UserManager2.SendEmailAsync(user.Id, "MYAnything 信箱驗證", "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>");

                    ViewBag.Link = callbackUrl;
                    return(View("DisplayEmail"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
コード例 #14
0
        public async Task <IHttpActionResult> ResetPassword(ResetPasswordBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                var user = UserManager2.FindUser(model.email);
                if (user == null)
                {
                    return(BadRequest("email not found"));
                }

                var newPassword = NameGenerator.RandomString(7);
                var emailResult = EmailManager.SendNewPassword(model.email, newPassword);

                if (emailResult)
                {
                    //IdentityResult result = await .SetPasswordHashAsync(user, newPassword);

                    var provider = new DpapiDataProtectionProvider("Todo");
                    UserManager.UserTokenProvider = new DataProtectorTokenProvider <User, long>(provider.Create("ASP.NET Identity"))
                                                    as IUserTokenProvider <User, long>;

                    var            resetToken = UserManager.GeneratePasswordResetToken(user.Id);
                    IdentityResult result     = UserManager.ResetPassword(user.Id, resetToken, newPassword);

                    if (!result.Succeeded)
                    {
                        return(GetErrorResult(result));
                    }

                    user = await UserManager.FindByIdAsync(user.Id);

                    user = UserManager2.Update(user);

                    return(Ok());
                }
            }
            catch (Exception ex)
            {
                logger.Log(LogLevel.Error, $"ResetPassword error: {ex}");
                return(BadRequest(ex.Message));
            }

            return(BadRequest());
        }
コード例 #15
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            var Recommend = Session["RecommendCode"] == null ? string.Empty : Session["RecommendCode"].ToString();

            ViewBag.Recommend = Recommend;


            model.Recommend = Recommend;
            model.UserCode  = new Anything.Helpers.BaseDLL().GetUserCode(model.UserName);

            model.UserType = "User";

            if (ModelState.IsValid)
            {
                var user = new ApplicationUser2 {
                    UserName = model.UserName, Email = model.Email, UserType = model.UserType, UserCode = model.UserCode, Recommend = model.Recommend
                };
                var result = await UserManager2.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    var roleName = model.UserType;
                    if (!RoleManager2.RoleExists(roleName))
                    {
                        var role = new Role2(roleName);
                        await RoleManager2.CreateAsync(role);
                    }



                    UserManager2.AddToRole(user.Id, model.UserType);

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

                    var callbackUrl = Url.Action("ConfirmEmail", "AccountForUser", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);

                    var link = string.Format("信箱驗證連結網址<a href='{0}'>完成驗證</a>", callbackUrl);

                    await UserManager2.SendEmailAsync(user.Id, "MYAnything 信箱驗證", link);

                    ViewBag.Link = callbackUrl;
                    return(View("DisplayEmail"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
コード例 #16
0
        public async Task <IHttpActionResult> SetFavoriteNotification(SetPushBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user     = UserManager2.FindUser(User.Identity.Name);
            var userInfo = UserManager2.FindUserInfo(user.UserInfoId);

            userInfo.FavoritePushNotification = model.turnOn;
            UserManager2.UpdateInfo(userInfo);

            return(Ok());
        }
コード例 #17
0
        public async Task <ActionResult> VerifyCode(string provider, string returnUrl)
        {
            // Require that the user has already logged in via username/password or external login
            if (!await SignInManager2.HasBeenVerifiedAsync())
            {
                return(View("Error"));
            }
            var user = await UserManager2.FindByIdAsync(await SignInManager2.GetVerifiedUserIdAsync());

            if (user != null)
            {
                ViewBag.Status = "For DEMO purposes the current " + provider + " code is: " + await UserManager2.GenerateTwoFactorTokenAsync(user.Id, provider);
            }
            return(View(new VerifyCodeViewModel {
                Provider = provider, ReturnUrl = returnUrl
            }));
        }
コード例 #18
0
        public async Task <ActionResult> SendCode(string returnUrl)
        {
            var userId = await SignInManager2.GetVerifiedUserIdAsync();

            if (userId <= 0)
            {
                return(View("Error"));
            }
            var userFactors = await UserManager2.GetValidTwoFactorProvidersAsync(userId);

            var factorOptions = userFactors.Select(purpose => new SelectListItem {
                Text = purpose, Value = purpose
            }).ToList();

            return(View(new SendCodeViewModel {
                Providers = factorOptions, ReturnUrl = returnUrl
            }));
        }
コード例 #19
0
        public async Task <object> FindUser(FindUserBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = UserManager2.FindUser(User.Identity.Name);
            var info = UserManager2.FindUserInfo(user.UserInfoId);

            var result = new SimpleUserModel()
            {
                id       = user.Id,
                email    = user.UserName,
                username = info.Name,
                avatar   = info.PhotoUrl
            };

            return(result);
        }
コード例 #20
0
        public async Task <IHttpActionResult> ChangePassword(ChangePasswordBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            IdentityResult result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId <long>(),
                                                                          model.oldpassword,
                                                                          model.newpassword);

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }

            var user = await UserManager.FindByIdAsync(User.Identity.GetUserId <int>());

            user = UserManager2.Update(user);

            return(Ok());
        }
コード例 #21
0
        public async Task <ActionResult> ExternalLoginConfirmation(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 ApplicationUser2 {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager2.CreateAsync(user);

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

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

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

            ViewBag.ReturnUrl = returnUrl;
            return(View(model));
        }
コード例 #22
0
        public async Task <object> Register()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            var provider = new MultipartMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(provider);

            byte[] buffer = null;
            string filename;
            string email           = string.Empty;
            string username        = string.Empty;
            string password        = string.Empty;
            string confirmpassword = string.Empty;

            var fileManager = new AzureFileManager();

            foreach (var file in provider.Contents)
            {
                if (file.Headers.ContentDisposition.Name.Contains("email"))
                {
                    email = await file.ReadAsStringAsync();
                }
                else if (file.Headers.ContentDisposition.Name.Contains("username"))
                {
                    username = await file.ReadAsStringAsync();
                }
                else if (file.Headers.ContentDisposition.Name.Contains("password"))
                {
                    password = await file.ReadAsStringAsync();
                }
                else if (file.Headers.ContentDisposition.Name.Contains("confirmpassword"))
                {
                    confirmpassword = await file.ReadAsStringAsync();
                }
                else
                {
                    filename = file.Headers.ContentDisposition.FileName.Trim('\"');
                    buffer   = await file.ReadAsByteArrayAsync();
                }
            }

            var model = new RegisterBindingModel()
            {
                email           = email,
                username        = username,
                password        = password,
                confirmpassword = confirmpassword,
            };

            logger.Log(LogLevel.Info, $"Register({model.email})");
            if (!ModelState.IsValid)
            {
                logger.Log(LogLevel.Error, $"Register({model.email}). Error: model state is not invalid");
                return(BadRequest(ModelState));
            }

            //var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
            var userInfo = UserManager2.CreateUserInfo("", username, "", "", "");

            var user = new User()
            {
                UserName      = model.email,
                PasswordHash  = model.password,
                IsActive      = true,
                UserInfoId    = userInfo.Id,
                UserType      = (int)UserTypeEnum.Client,
                AccountPlanId = (int)AccountPlanEnum.Start,
                Registration  = DateTime.Now,
                LastUpdate    = DateTime.Now
            };

            IdentityResult result = await UserManager.CreateAsync(user, model.password);

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }
            user = UserManager2.Create(user);
            //SignInManager.SignIn(user, false, false);
            ClaimsIdentity oAuthIdentity = await UserManager.CreateIdentityAsync(user, OAuthDefaults.AuthenticationType);

            ClaimsIdentity cookiesIdentity = await UserManager.CreateIdentityAsync(user, CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);

            Authentication.SignIn(properties, oAuthIdentity, cookiesIdentity);

            var token = GetToken(model.email, model.password);

            //avatar
            var uploadResult = fileManager.UploadFileAsync(buffer, $"{user.Id}.png");//pass file stream

            if (string.IsNullOrEmpty(uploadResult.Result))
            {
                return(BadRequest(uploadResult.Result));
            }


            var info = UserManager2.FindUserInfo(user.UserInfoId);

            info.PhotoUrl = uploadResult.Result;
            UserManager2.UpdateInfo(info);
            try
            {
                GroupManager.CreateFavorites(user.Id);
            }
            catch (Exception ex)
            { }

            var usermodel = UserManager2.GetUserModel(user.UserName);

            return(new
            {
                token = token,
                user = usermodel
            });
        }
コード例 #23
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            FormsAuthentication.SignOut();
            AuthenticationManager.SignOut();
            if (!ModelState.IsValid)
            {
                return(View(model));
            }


            //比對驗證碼
            if (System.Configuration.ConfigurationManager.AppSettings["VerificationCode"] != null)
            {
                var VerificationText = System.Configuration.ConfigurationManager.AppSettings["VerificationCode"];
                var VerificationCode = Session[VerificationText].ToString();
                if (string.IsNullOrEmpty(model.VerificationCode) || VerificationCode.ToUpper() != model.VerificationCode.ToUpper())
                {
                    ModelState.AddModelError("", "無效的驗證碼");
                    return(View());
                }
            }

            //使用者是否存在
            var user = await UserManager2.FindByEmailAsync(model.Email);

            if (user == null)
            {
                ModelState.AddModelError("", "無效的帳號密碼");
                return(View(model));
            }

            //密碼檢查
            PasswordVerificationResult status = UserManager2.PasswordHasher.VerifyHashedPassword(user.PasswordHash, model.Password);

            if (user == null || !status.Equals(PasswordVerificationResult.Success))
            {
                ModelState.AddModelError("", "無效的帳號密碼");
                return(View(model));
            }

            if (!user.EmailConfirmed)
            {
                //return RedirectToAction("SendCode");
                ModelState.AddModelError("", "未完成信箱驗證");
                return(View(model));
            }



            if (user != null && status.Equals(PasswordVerificationResult.Success))
            {
                //SignIn(user,model.RememberMe);
                await SignInAsync(user, model.RememberMe);

                CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel();

                serializeModel.ID       = user.Id;
                serializeModel.Name     = user.UserName;
                serializeModel.Email    = user.Email;
                serializeModel.UserCode = user.UserCode;
                serializeModel.UserType = user.UserType;
                var UserRoles = (from rr in RoleManager2.Roles.ToList()
                                 join r1 in user.Roles on rr.Id equals r1.RoleId
                                 select rr.Name).ToList();

                //var r = (from uRoles in user.Roles
                //        join rr in RoleManager.Roles.ToList() on uRoles.RoleId == rr.RoleId).to


                serializeModel.roles = string.Join(",", UserRoles);
                // serializeModel.roles = "Admin";
                var ExpireDateTime = DateTime.Now.AddDays(3);
                if (model.RememberMe)
                {
                    ExpireDateTime = DateTime.Now.AddDays(15);
                }

                string userData = JsonConvert.SerializeObject(serializeModel);
                FormsAuthenticationTicket authTicket = null;
                authTicket = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now, DateTime.Now.AddDays(15), false, userData);

                string     encTicket = FormsAuthentication.Encrypt(authTicket);
                HttpCookie faCookie  = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)
                {
                    Expires = authTicket.Expiration, Path = "/"
                };
                System.Web.HttpContext.Current.Response.Cookies.Add(faCookie);

                _db.SystemLog.Add(new SystemLog
                {
                    Created        = DateTime.Now,
                    Creator        = model.Email,
                    IP             = IPaddress,
                    LogCode        = "Time",
                    LogType        = "SignIn",
                    LogDescription = "登入時間",
                    LogValue       = DateTime.Now.ToString()
                });
                _db.SaveChanges();

                return(RedirectToLocal(returnUrl));
            }


            return(View(model));
        }
コード例 #24
0
        public async Task <IHttpActionResult> GetExternalLogin(string provider, string error = null)
        {
            if (error != null)
            {
                return(Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error)));
            }

            if (!User.Identity.IsAuthenticated)
            {
                return(new ChallengeResult(provider, this));
            }

            ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);

            if (externalLogin == null)
            {
                return(InternalServerError());
            }

            if (externalLogin.LoginProvider != provider)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                return(new ChallengeResult(provider, this));
            }

            var user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey));

            bool hasRegistered = user != null;

            if (hasRegistered)
            {
                SignInManager.SignOut();
                //Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

                ClaimsIdentity oAuthIdentity = await UserManager.CreateIdentityAsync(user, OAuthDefaults.AuthenticationType);

                ClaimsIdentity cookiesIdentity = await UserManager.CreateIdentityAsync(user, CookieAuthenticationDefaults.AuthenticationType);

                AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
                SignInManager.SignIn(user, false, false);
                //Authentication.SignIn(properties, oAuthIdentity, cookiesIdentity);
            }
            else
            {
                IEnumerable <Claim> claims   = externalLogin.GetClaims();
                ClaimsIdentity      identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);

                var userInfo = UserManager2.CreateUserInfo("", externalLogin.UserName, "", "", "");

                user = new User()
                {
                    UserName      = externalLogin.UserName,
                    PasswordHash  = null,
                    IsActive      = true,
                    UserType      = (int)UserTypeEnum.Client,
                    UserInfoId    = userInfo.Id,
                    AccountPlanId = (int)AccountPlanEnum.Start,
                    Registration  = DateTime.Now,
                    LastUpdate    = DateTime.Now
                };

                IdentityResult result = await UserManager.CreateAsync(user);

                IdentityResult loginResult = await UserManager.AddLoginAsync(user.Id, new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey));

                SignInManager.SignIn(user, false, false);
                //Authentication.SignIn(identity);
            }

            return(Ok());
        }
コード例 #25
0
        public async Task <ActionResult> ChangePassword(ResetPasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                TempData["ViewData"] = ViewData;
                if (!string.IsNullOrEmpty(model.ReturnUrl))
                {
                    return(Redirect(model.ReturnUrl));
                }
                return(View(model));
            }


            var user = await UserManager2.FindByEmailAsync(model.Email);


            if (user == null)
            {
                TempData["ErrorMessage"] = "密碼變更,使用者不存在";
                ModelState.AddModelError("", "使用者不存在");
                if (!string.IsNullOrEmpty(model.ReturnUrl))
                {
                    return(Redirect(model.ReturnUrl));
                }
                // Don't reveal that the user does not exist
                FormsAuthentication.SignOut();
                AuthenticationManager.SignOut();
                return(Redirect("~/Home/AccountForUser"));
            }
            else
            {
                if (CurrentUser.Id != user.Id)
                {
                    TempData["ErrorMessage"] = "密碼變更,帳號不符";
                    ModelState.AddModelError("", "帳號不符");
                    FormsAuthentication.SignOut();
                    AuthenticationManager.SignOut();
                    return(Redirect("~/Home/AccountForUser"));
                }
            }

            var code = await UserManager2.GeneratePasswordResetTokenAsync(user.Id);


            var result = await UserManager2.ResetPasswordAsync(user.Id, code, model.Password);

            if (result.Succeeded)
            {
                if (!string.IsNullOrEmpty(model.ReturnUrl))
                {
                    TempData["SuccessMessage"] = "密碼已變更,下次請使用新密碼";
                    return(Redirect(model.ReturnUrl));
                }
                return(RedirectToAction("ResetPasswordConfirmation", "Account"));
            }
            AddErrors(result);
            TempData["ViewData"] = ViewData;
            if (!string.IsNullOrEmpty(model.ReturnUrl))
            {
                return(Redirect(model.ReturnUrl));
            }
            return(View());
        }