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);
        }
        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));
        }
        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));
        }
        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));
        }
示例#5
0
        public AspNetUserModel PostAddAspNetUserDB(AspNetUserModel aspNetUserModel, bool LoggedIn)
        {
            string retStr = AspNetUserModelOK(aspNetUserModel);

            if (!string.IsNullOrWhiteSpace(retStr))
            {
                return(ReturnError(retStr));
            }

            AspNetUser aspNetUserExist = GetAspNetUserWithEmailDB(aspNetUserModel.LoginEmail);

            if (aspNetUserExist != null)
            {
                return(ReturnError(string.Format(ServiceRes.UserWithLoginEmail_AlreadyExist, aspNetUserModel.LoginEmail)));
            }

            if (LoggedIn)
            {
                ContactOK contactOK = IsContactOK();
                if (!string.IsNullOrEmpty(contactOK.Error))
                {
                    return(ReturnError(contactOK.Error));
                }
            }

            string           LoginEmail      = aspNetUserModel.LoginEmail;
            ApplicationUser2 applicationUser = new ApplicationUser2()
            {
                UserName = LoginEmail
            };

            AspNetUser aspNetUserNew = new AspNetUser();

            using (TransactionScope ts = new TransactionScope())
            {
                try
                {
                    IdentityResult result = CreateUser(applicationUser, aspNetUserModel.Password);
                }
                catch (Exception)
                {
                    //return new AspNetUserModel() { Error = ex.Message };
                }

                aspNetUserModel.PasswordHash      = applicationUser.PasswordHash;
                aspNetUserModel.SecurityStamp     = applicationUser.SecurityStamp;
                aspNetUserModel.AccessFailedCount = applicationUser.AccessFailedCount;
                aspNetUserModel.Email             = aspNetUserModel.LoginEmail;
                aspNetUserModel.UserName          = aspNetUserModel.LoginEmail;
                aspNetUserModel.EmailConfirmed    = applicationUser.EmailConfirmed;
                aspNetUserModel.Id                   = applicationUser.Id;
                aspNetUserModel.LockoutEnabled       = applicationUser.LockoutEnabled;
                aspNetUserModel.LockoutEndDateUtc    = applicationUser.LockoutEndDateUtc;
                aspNetUserModel.PhoneNumber          = applicationUser.PhoneNumber;
                aspNetUserModel.PhoneNumberConfirmed = applicationUser.PhoneNumberConfirmed;
                aspNetUserModel.TwoFactorEnabled     = applicationUser.TwoFactorEnabled;

                retStr = FillAspNetUser(aspNetUserNew, aspNetUserModel);
                if (!string.IsNullOrWhiteSpace(retStr))
                {
                    return(ReturnError(retStr));
                }

                db.AspNetUsers.Add(aspNetUserNew);
                retStr = DoAddChanges();
                if (!string.IsNullOrWhiteSpace(retStr))
                {
                    return(ReturnError(retStr));
                }

                ts.Complete();
            }
            return(GetAspNetUserModelWithEmailDB(aspNetUserNew.Email));
        }
示例#6
0
        // Post
        public AspNetUserModel PostAddFirstAspNetUserDB(AspNetUserModel aspNetUserModel)
        {
            int Count = GetAspNetUserModelCountDB();

            if (Count > 0)
            {
                return(ReturnError(string.Format(ServiceRes.ToAddFirst_Requires_TableToBeEmpty, ServiceRes.AspNetUser)));
            }

            string retStr = AspNetUserModelOK(aspNetUserModel);

            if (!string.IsNullOrWhiteSpace(retStr))
            {
                return(ReturnError(retStr));
            }

            AspNetUser aspNetUserExist = GetAspNetUserWithEmailDB(aspNetUserModel.LoginEmail);

            if (aspNetUserExist != null)
            {
                return(ReturnError(string.Format(ServiceRes.UserWithLoginEmail_AlreadyExist, aspNetUserModel.LoginEmail)));
            }

            ApplicationUser2 applicationUser = new ApplicationUser2()
            {
                UserName = aspNetUserModel.LoginEmail
            };

            AspNetUser aspNetUserNew = new AspNetUser();

            using (TransactionScope ts = new TransactionScope())
            {
                try
                {
                    IdentityResult result = CreateUser(applicationUser, aspNetUserModel.Password);
                }
                catch (Exception)
                {
                    // nothing for now
                }

                aspNetUserModel.PasswordHash      = applicationUser.PasswordHash;
                aspNetUserModel.SecurityStamp     = applicationUser.SecurityStamp;
                aspNetUserModel.AccessFailedCount = applicationUser.AccessFailedCount;
                aspNetUserModel.Email             = aspNetUserModel.LoginEmail;
                aspNetUserModel.UserName          = aspNetUserModel.LoginEmail;
                aspNetUserModel.EmailConfirmed    = applicationUser.EmailConfirmed;
                aspNetUserModel.Id                   = applicationUser.Id;
                aspNetUserModel.LockoutEnabled       = applicationUser.LockoutEnabled;
                aspNetUserModel.LockoutEndDateUtc    = applicationUser.LockoutEndDateUtc;
                aspNetUserModel.PhoneNumber          = applicationUser.PhoneNumber;
                aspNetUserModel.PhoneNumberConfirmed = applicationUser.PhoneNumberConfirmed;
                aspNetUserModel.TwoFactorEnabled     = applicationUser.TwoFactorEnabled;

                retStr = FillAspNetUser(aspNetUserNew, aspNetUserModel);
                if (!string.IsNullOrWhiteSpace(retStr))
                {
                    return(ReturnError(retStr));
                }

                db.AspNetUsers.Add(aspNetUserNew);
                retStr = DoAddChanges();
                if (!string.IsNullOrWhiteSpace(retStr))
                {
                    return(ReturnError(retStr));
                }

                LogModel logModel = _LogService.PostAddLogForObj("AppNetUsers", -1, LogCommandEnum.Add, aspNetUserNew);
                if (!string.IsNullOrWhiteSpace(logModel.Error))
                {
                    return(ReturnError(logModel.Error));
                }

                ts.Complete();
            }
            return(GetAspNetUserModelWithEmailDB(aspNetUserNew.Email));
        }
示例#7
0
        // Helper
        public IdentityResult CreateUser(ApplicationUser2 applicationUser, string Password)
        {
            IdentityResult result = _UserManager.Create(applicationUser, Password);

            return(result);
        }