Esempio n. 1
0
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                try
                {
                    IDictionary <string, object> properties = new Dictionary <string, object>();

                    // NOTICE: To use this property columns. Add "MySql.Data.Extension" project partial "UserProfile" class and add property columns.
                    // by KIM-KIWON\xyz37(Kim Ki Won) in Thursday, April 18, 2013 5:02 PM
                    //properties.Add("Email", model.Email);
                    //properties.Add("Facebook", model.Facebook);
                    //properties.Add("Age", model.Age);
                    //properties.Add("Rate", model.Rate);

                    using (TransactionScope scope = new TransactionScope())
                    {
                        MySqlWebSecurity.CreateUserAndAccount(model.UserName, model.Password, properties);
                        MySqlWebSecurity.Login(model.UserName, model.Password);

                        var userId = MySqlWebSecurity.GetUserId(model.UserName);

                        using (var db = SimpleMembershipTestDbContext.CreateContext())
                        {
                            db.UserProperties.Add(new UserProperty
                            {
                                UserId    = userId,
                                UserName  = model.UserName,
                                Age       = model.Age,
                                Email     = model.Email,
                                Facebook  = model.Facebook,
                                Rate      = model.Rate,
                                LastName  = model.LastName,
                                FirstName = model.FirstName,
                            });
                            db.SaveChanges();
                        }

                        scope.Complete();
                    }


                    return(RedirectToAction("Index", "Home"));
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Esempio n. 2
0
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider       = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return(RedirectToAction("Manage"));
            }

            if (ModelState.IsValid)
            {
                // Insert a new user into the database
                using (var db = SimpleMembershipTestDbContext.CreateContext())
                {
                    UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                    // Check if user already exists
                    if (user == null)
                    {
                        // Insert name into the profile table
                        db.UserProfiles.Add(new UserProfile
                        {
                            UserName = model.UserName
                        });
                        db.SaveChanges();

                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                        return(RedirectToLocal(returnUrl));
                    }
                    else
                    {
                        ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name.");
                    }
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl           = returnUrl;
            return(View(model));
        }
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer <SimpleMembershipTestDbContext>(null);

                try
                {
                    using (var context = SimpleMembershipTestDbContext.CreateContext())
                    {
                        if (context.Database.Exists() == false)
                        {
                            // Create the SimpleMembership database without Entity Framework migration schema
                            ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                        }
                    }

                    MySqlWebSecurity.InitializeDatabaseConnection("SimpleMembershipTestDbContext");

                    const string ADMIN_ROLES = "Administrators";
                    const string ADMIN_USER  = "******";

                    if (System.Web.Security.Roles.RoleExists(ADMIN_ROLES) == false)
                    {
                        System.Web.Security.Roles.CreateRole(ADMIN_ROLES);

                        if (WebSecurity.UserExists(ADMIN_USER) == false)
                        {
                            WebSecurity.CreateUserAndAccount(ADMIN_USER, "password");
                        }

                        if (System.Web.Security.Roles.GetRolesForUser(ADMIN_USER).Contains(ADMIN_ROLES) == false)
                        {
                            System.Web.Security.Roles.AddUserToRole(ADMIN_USER, ADMIN_ROLES);
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
Esempio n. 4
0
        //
        // GET: /Account/Manage

        public ActionResult Manage(ManageMessageId?message)
        {
            ViewBag.StatusMessage =
                message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
                                : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
                                : message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
                                : message == ManageMessageId.RequestOneExternalLogin ? "You must one external login or local account."
                                : "";
            ViewBag.HasLocalPassword = OAuthWebSecurity.HasLocalAccount(MySqlWebSecurity.GetUserId(User.Identity.Name));
            ViewBag.ReturnUrl        = Url.Action("Manage");
            var model = new ChangePropertyModel
            {
                LocalPasswordModel = new LocalPasswordModel(),
                PropertyModel      = new PropertyModel(),
            };

            using (var db = SimpleMembershipTestDbContext.CreateContext())
            {
                var userProperties = db.UserProperties.SingleOrDefault(x => x.UserName == User.Identity.Name);

                if (userProperties != null)
                {
                    model.PropertyModel = new PropertyModel
                    {
                        Age       = userProperties.Age,
                        Email     = userProperties.Email,
                        Facebook  = userProperties.Facebook,
                        FirstName = userProperties.FirstName,
                        LastName  = userProperties.LastName,
                        Rate      = userProperties.Rate,
                    };
                }
            }

            return(View(model));
        }
Esempio n. 5
0
        //[ValidateAntiForgeryToken]
        public ActionResult Manage(ChangePropertyModel model)
        {
            bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(MySqlWebSecurity.GetUserId(User.Identity.Name));

            ViewBag.HasLocalPassword = hasLocalAccount;
            ViewBag.ReturnUrl        = Url.Action("Manage");
            if (hasLocalAccount)
            {
                if (ModelState.IsValid)
                {
                    // ChangePassword will throw an exception rather than return false in certain failure scenarios.
                    bool changePasswordSucceeded = false;

                    if (string.IsNullOrEmpty(model.LocalPasswordModel.ConfirmPassword) == true)
                    {
                        using (var db = SimpleMembershipTestDbContext.CreateContext())
                        {
                            var userProperty = db.UserProperties.SingleOrDefault(x => x.UserName == User.Identity.Name);

                            if (userProperty == null)
                            {
                                var userId = MySqlWebSecurity.GetUserId(User.Identity.Name);

                                userProperty = new UserProperty
                                {
                                    UserId   = userId,
                                    UserName = User.Identity.Name,
                                };
                                db.UserProperties.Add(userProperty);
                            }

                            userProperty.Age       = model.PropertyModel.Age;
                            userProperty.Email     = model.PropertyModel.Email;
                            userProperty.Facebook  = model.PropertyModel.Facebook;
                            userProperty.FirstName = model.PropertyModel.FirstName;
                            userProperty.LastName  = model.PropertyModel.LastName;
                            userProperty.Rate      = model.PropertyModel.Rate;

                            changePasswordSucceeded = db.SaveChanges() > 0;
                        }
                    }
                    else
                    {
                        try
                        {
                            changePasswordSucceeded = MySqlWebSecurity.ChangePassword(User.Identity.Name, model.LocalPasswordModel.OldPassword, model.LocalPasswordModel.NewPassword);
                        }
                        catch (Exception)
                        {
                            changePasswordSucceeded = false;
                        }
                    }

                    if (changePasswordSucceeded == true)
                    {
                        return(RedirectToAction("Manage", new
                        {
                            Message = ManageMessageId.ChangePasswordSuccess
                        }));
                    }
                    else
                    {
                        ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                    }
                }
            }
            else
            {
                // User does not have a local password so remove any validation errors caused by a missing
                // OldPassword field
                ModelState state = ModelState["OldPassword"];
                if (state != null)
                {
                    state.Errors.Clear();
                }

                if (ModelState.IsValid)
                {
                    try
                    {
                        MySqlWebSecurity.CreateAccount(User.Identity.Name, model.LocalPasswordModel.NewPassword);
                        return(RedirectToAction("Manage", new
                        {
                            Message = ManageMessageId.SetPasswordSuccess
                        }));
                    }
                    catch (Exception e)
                    {
                        ModelState.AddModelError("", e);
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }