Beispiel #1
0
        protected void InitializeUserAndRoles()
        {
            SimpleRoleProvider       roles      = (SimpleRoleProvider)Roles.Provider;
            SimpleMembershipProvider membership = (SimpleMembershipProvider)Membership.Provider;

            if (!roles.RoleExists("Admin"))
            {
                roles.CreateRole("Admin");
            }
            if (!roles.RoleExists("Manager"))
            {
                roles.CreateRole("Manager");
            }
            if (!roles.RoleExists("User"))
            {
                roles.CreateRole("User");
            }
            if (membership.GetUser("*****@*****.**", false) == null)
            {
                WebSecurity.CreateUserAndAccount("*****@*****.**", "123456", new { IsBlocked = false });
                roles.AddUsersToRoles(new[] { "*****@*****.**" }, new[] { "Admin" });
            }
            if (membership.GetUser("*****@*****.**", false) == null)
            {
                WebSecurity.CreateUserAndAccount("*****@*****.**", "123456", new { IsBlocked = false });
                roles.AddUsersToRoles(new[] { "*****@*****.**" }, new[] { "User" });
            }
        }
Beispiel #2
0
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer <UsersContext>(null);

                try
                {
                    using (var context = new UsersContext())
                    {
                        if (!context.Database.Exists())
                        {
                            // Создание базы данных SimpleMembership без применения миграции Entity Framework
                            ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                        }
                    }
                    // Настройка  ASP.NET Simple Membership
                    // 1 параметр - имя строки подключения к базе данных.
                    // 2 параметр - таблица, которая содержит информацию о пользователях
                    // 3 параметр - имя колонки в таблице, которая отвечает за хранение логина
                    // 4 параметр - autoCreateTables автоматическое создание таблиц если они не существуют в базе
                    WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);

                    SimpleRoleProvider       roles      = (SimpleRoleProvider)Roles.Provider;
                    SimpleMembershipProvider membership = (SimpleMembershipProvider)Membership.Provider;

                    // Проверка наличия роли Moderator
                    if (!roles.RoleExists("Moderator"))
                    {
                        roles.CreateRole("Moderator");
                    }
                    // Проверка наличия роли Admin
                    if (!roles.RoleExists("Admin"))
                    {
                        roles.CreateRole("Admin");
                    }
                    if (membership.GetUser("OverLord56_1", false) == null)
                    {
                        membership.CreateUserAndAccount("OverLord56_1", "89Zxcv");          // создание пользователя
                        roles.AddUsersToRoles(new[] { "OverLord56_1" }, new[] { "Admin" }); // установка роли для пользователя
                    }

                    // Поиск пользователя с логином admin
                    if (membership.GetUser("admin", false) == null)
                    {
                        membership.CreateUserAndAccount("admin", "qwe123");          // создание пользователя
                        roles.AddUsersToRoles(new[] { "admin" }, new[] { "Admin" }); // установка роли для пользователя
                    }
                    if (membership.GetUser("user1", false) == null)
                    {
                        membership.CreateUserAndAccount("user1", "qwe123");
                        roles.AddUsersToRoles(new[] { "user1" }, new[] { "Moderator" });
                    }
                }
                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);
                }
            }
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer <UsersContext>(null);

                try
                {
                    using (var context = new UsersContext())
                    {
                        if (!context.Database.Exists())
                        {
                            // Создание базы данных SimpleMembership без схемы миграции Entity Framework
                            ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                        }
                    }

                    //   WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);



                    SimpleRoleProvider       roles      = (SimpleRoleProvider)Roles.Provider;
                    SimpleMembershipProvider membership = (SimpleMembershipProvider)Membership.Provider;



                    // Проверка наличия роли Moderator
                    if (!roles.RoleExists("Moderator"))
                    {
                        roles.CreateRole("Moderator");
                    }
                    // Проверка наличия роли Admin
                    if (!roles.RoleExists("Admin"))
                    {
                        roles.CreateRole("Admin");
                    }
                    if (!roles.RoleExists("User"))
                    {
                        roles.CreateRole("User");
                    }

                    // Поиск пользователя с логином admin
                    if (membership.GetUser("admin", false) == null)
                    {
                        membership.CreateUserAndAccount("admin", "qwe123");          // создание пользователя
                        roles.AddUsersToRoles(new[] { "admin" }, new[] { "Admin" }); // установка роли для пользователя
                    }
                    if (membership.GetUser("user1", false) == null)
                    {
                        membership.CreateUserAndAccount("user1", "qwe123");
                        roles.AddUsersToRoles(new[] { "user1" }, new[] { "Moderator" });
                    }
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("Не удалось инициализировать базу данных ASP.NET Simple Membership. Чтобы получить дополнительные сведения, перейдите по адресу: http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
Beispiel #4
0
 private void AddUserToRoles(string userName, string[] roles)
 {
     foreach (string role in roles)
     {
         if (!string.IsNullOrEmpty(role))
         {
             rolesProvider.AddUsersToRoles(new[] { userName }, new[] { role });
         }
     }
 }
Beispiel #5
0
        public ActionResult RegisterReader(RegisterReaderModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    if (membership.GetUser(model.User.Login, false) == null)
                    {
                        membership.CreateUserAndAccount(model.User.Login, model.User.Password);
                        if (!roles.IsUserInRole(model.User.Login, "reader"))
                        {
                            roles.AddUsersToRoles(new[] { model.User.Login }, new[] { "reader" });
                        }

                        Registration registration = new Registration();
                        model.Reader.UserId = WebSecurity.GetUserId(model.User.Login);

                        var result = registration.RegisterReader((ReaderDataDTO)model.Reader);


                        if (result.Code == BusinessLayer.OperationStatusEnum.Success)
                        {
                            TempData["OperationStatus"] = true;
                            TempData["OpearionMessage"] = "Регистрация успешно завершена";

                            return(RedirectToAction("Index", "Login"));
                        }
                        else
                        {
                            TempData["OperationStatus"] = false;
                            TempData["OpearionMessage"] = result.Message;
                        }
                    }
                    else
                    {
                        TempData["OperationStatus"] = false;
                        TempData["OpearionMessage"] = "Пользователь с таким логином уже существует";
                    }
                }
                catch (Exception ex)
                {
                    TempData["OperationStatus"] = false;
                    TempData["OpearionMessage"] = ex.StackTrace;
                }
            }

            return(View(model));
        }
        public JsonResult CreateAccount(string Address, string Code, string Discount, string Name, string UserName, string Password, string ConfirmPassword)
        {
            try
            {
                SimpleRoleProvider roles = (SimpleRoleProvider)Roles.Provider;
                RegisterModel      model = new RegisterModel();
                model.UserName        = UserName;
                model.Password        = Password;
                model.ConfirmPassword = ConfirmPassword;
                WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
                roles.AddUsersToRoles(new[] { model.UserName }, new[] { "Customer" });

                Customer customer = new Customer();
                customer.Address    = Address;
                customer.Code       = Code;
                customer.Discount   = Int32.Parse(Discount);
                customer.Name       = Name;
                customer.CustomerId = Guid.NewGuid();
                customer.UserId     = WebSecurity.GetUserId(model.UserName);
                unitOfWork.CustomerRepository().Insert(customer);
                unitOfWork.Save();

                return(this.Json(new { success = true }));
            }
            catch (Exception e)
            {
                List <string> ErrorList = new List <string>();
                ErrorList.Add(e.Message);
                return(this.Json(new { success = false, errors = ErrorList }));
            }
        }
        public void Initialize()
        {
            Database.SetInitializer <ShopDBContext>(null);

            try
            {
                using (var context = new ShopDBContext())
                {
                    if (!context.Database.Exists())
                    {
                        ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                    }
                }

                WebSecurity.InitializeDatabaseConnection("ShopDB", "Users", "UserId", "Email", autoCreateTables: true);
                SimpleRoleProvider       roles       = (SimpleRoleProvider)Roles.Provider;
                SimpleMembershipProvider memberships = (SimpleMembershipProvider)Membership.Provider;

                if (!roles.RoleExists("Admin"))
                {
                    roles.CreateRole("Admin");
                }

                if (memberships.GetUser("*****@*****.**", false) == null)
                {
                    memberships.CreateUserAndAccount("*****@*****.**", "qwerty1234");
                    roles.AddUsersToRoles(new[] { "*****@*****.**" }, new[] { "Admin" });
                }
            }
            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);
            }
        }
Beispiel #8
0
        protected override void Seed(FCIH_OJ.Models.UsersContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data. E.g.
            //

            //////////////////////////////////////////////////////
            // user module

            WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);

            SimpleRoleProvider       roles      = new SimpleRoleProvider(Roles.Provider);
            SimpleMembershipProvider membership = new SimpleMembershipProvider(Membership.Provider);

            if (!roles.RoleExists("admin"))
            {
                roles.CreateRole("admin");
            }
            if (!WebSecurity.UserExists("admin"))
            {
                WebSecurity.CreateUserAndAccount("admin", "admin", new {
                    Email    = "*****@*****.**",
                    Password = "******"
                });
            }
            if (!roles.GetRolesForUser("admin").Contains("admin"))
            {
                roles.AddUsersToRoles(new[] { "admin" }, new[] { "admin" });
            }
            //end of user module
            //////////////////////////////////////////////////////
            //other modules
        }
Beispiel #9
0
 public static void AddUserToRole(string userName, string role)
 {
     if (!_rolesProvider.GetRolesForUser(userName).Contains(role))
     {
         _rolesProvider.AddUsersToRoles(new[] { userName }, new[] { role });
     }
 }
Beispiel #10
0
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer <ExperienceContext>(null);

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

                    //WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
                    WebSecurity.InitializeDatabaseConnection("ExperienceContext", "User", "UserId", "UserName", autoCreateTables: true);


                    if (!roles.RoleExists("Admin"))
                    {
                        roles.CreateRole("Admin");/*илиRoles.CreateRole("Admin"); */
                    }
                    if (!roles.RoleExists("User"))
                    {
                        roles.CreateRole("User");
                    }
                    if (!roles.RoleExists("Customer"))
                    {
                        roles.CreateRole("Customer");
                    }
                    if (!roles.RoleExists("Perfomer"))
                    {
                        roles.CreateRole("Perfomer");
                    }


                    if (membership.GetUser("admin1", false) == null)
                    {
                        WebSecurity.CreateUserAndAccount("admin1", "admin1admin1",
                                                         new
                        {
                            Surname     = "admin",
                            PhoneNumber = "11111",
                            Email       = "admin",
                            isReady     = false

                                          //Type = new Type()
                        });
                        roles.AddUsersToRoles(new[] { "admin1" }, new[] { "Admin" });
                    }
                }

                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);
                }
            }
        public ActionResult RoleAddUser(string id, string selectedUserNameFromList)
        {
            SimpleRoleProvider simpleRoles = Roles.Provider as SimpleRoleProvider;

            if (!simpleRoles.IsUserInRole(selectedUserNameFromList, id))
            {
                simpleRoles.AddUsersToRoles(new string[] { selectedUserNameFromList }, new string[] { id });
            }
            return(PartialView("RoleUserList", simpleRoles.GetUsersInRole(id)));
        }
Beispiel #12
0
        protected override void Seed(PortalContext context)
        {
            WebSecurity.InitializeDatabaseConnection("PortalContext",
                                                     "UserProfile", "UserId", "UserName", autoCreateTables: true);
            roles      = (SimpleRoleProvider)Roles.Provider;
            membership = (SimpleMembershipProvider)Membership.Provider;

            if (!roles.RoleExists("Admin"))
            {
                roles.CreateRole("Admin");
            }
            if (!roles.RoleExists("Member"))
            {
                roles.CreateRole("Member");
            }
            if (!roles.RoleExists("RefundVisualizator"))
            {
                roles.CreateRole("RefundVisualizator");
            }
            if (!roles.RoleExists("RefundAdministrator"))
            {
                roles.CreateRole("RefundAdministrator");
            }
            if (!roles.RoleExists("Manager"))
            {
                roles.CreateRole("Manager");
            }
            if (!roles.RoleExists("Freelancer"))
            {
                roles.CreateRole("Freelancer");
            }

            if (membership.GetUser("admin", false) == null)
            {
                membership.CreateUserAndAccount("admin", "pesca160064");
            }
            if (!roles.GetRolesForUser("admin").Contains("Admin"))
            {
                roles.AddUsersToRoles(new[] { "admin" }, new[] { "Admin" });
            }

            var currentCpf = "38287346851";

            CheckUser(currentCpf, "Bruno Tachinardi Andrade Silva", "*****@*****.**");
            CheckRefund(currentCpf);
            CheckRefundAdministrator(currentCpf);
            CheckManager(currentCpf, "BRUNO");
            CheckFreelancer(currentCpf, "BRUNO", 8, 1200, 128, 50, FreelancerType.EDUCATOR);

            currentCpf = "17858466801";
            CheckUser(currentCpf, "Pedro de Almeida Pereira", "*****@*****.**");
            CheckRefund(currentCpf);
            CheckFreelancer(currentCpf, "BRUNO", 8, 1200, 128, 50, FreelancerType.EDUCATOR);
        }
        public ActionResult RoleEdit(RoleModel model)
        {
            SimpleRoleProvider simpleRoles = Roles.Provider as SimpleRoleProvider;
            var users = simpleRoles.GetUsersInRole(model.PrevName);

            simpleRoles.RemoveUsersFromRoles(users, new string[] { model.PrevName });
            simpleRoles.DeleteRole(model.PrevName, false);
            simpleRoles.CreateRole(model.Name);
            simpleRoles.AddUsersToRoles(users, new string[] { model.Name });

            return(RedirectToAction("RoleList"));
        }
Beispiel #14
0
 public void CheckUser(string cpf, string name, string email)
 {
     if (membership.GetUser(cpf, false) == null)
     {
         membership.CreateUserAndAccount(cpf, cpf);
         var user = db.UserProfiles.First(up => up.UserName == cpf);
         user.PersonalInfo.CPF  = cpf;
         user.PersonalInfo.Name = name;
         user.ContactInfo.Email = email;
         db.SaveChanges();
     }
     if (!roles.GetRolesForUser(cpf).Contains("Member"))
     {
         roles.AddUsersToRoles(new[] { cpf }, new[] { "Member" });
     }
 }
        /// <summary>
        /// Refactor user creation and add email id to user profile
        /// </summary>
        /// <param name="roles"></param>
        /// <param name="membership"></param>
        /// <param name="context"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="email"></param>
        /// <param name="role"></param>
        private void CreateAccountAndRole(SimpleRoleProvider roles, SimpleMembershipProvider membership, UsersContext context, string username, string password, string email, string role)
        {
            if (membership.GetUser(username, false) == null)
            {
                membership.CreateUserAndAccount(username, password);
            }

            if (!roles.GetRolesForUser(username).Contains(role))
            {
                roles.AddUsersToRoles(new[] { username }, new[] { role });
            }

            var user = context.UserProfiles.FirstOrDefault(u => u.UserName == username);

            if (user != null && string.IsNullOrEmpty(user.EmailId))
            {
                user.EmailId = email;
            }
        }
Beispiel #16
0
        private UserProfile CreateUser(string email,
                                       string fullName,
                                       SimpleMembershipProvider membership,
                                       SimpleRoleProvider roles,
                                       SweatyTShirtContext context)
        {
            string userName = Guid.NewGuid().ToString();
            Dictionary <string, object> values = new Dictionary <string, object>();

            values.Add("Email", email);
            values.Add("LastEmailSent", DateTime.Now.AddDays(-365));
            membership.CreateUserAndAccount(userName, AccountRepository.AllUsersPassword, values);
            roles.AddUsersToRoles(new[] { userName }, new[] { AccountRepository.UserRole });
            UserProfile userProfile = context.UserProfiles.FirstOrDefault(o => o.Email == email);

            userProfile.FullName = fullName;
            context.SaveChanges();
            return(userProfile);
        }
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer <DatabaseContext>(null);
                using (var context = new DatabaseContext())
                {
                    if (!context.Database.Exists())
                    {
                        // Создание базы данных SimpleMembership без применения миграции Entity Framework
                        ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                    }


                    WebSecurity.InitializeDatabaseConnection("DatabaseContext", "User", "UserId", "Email", true);

                    SimpleRoleProvider       roles      = Roles.Provider as SimpleRoleProvider;
                    SimpleMembershipProvider membership = Membership.Provider as SimpleMembershipProvider;

                    string admin = "Admin";
                    string user  = "******";
                    if (!roles.RoleExists(admin))
                    {
                        roles.CreateRole(admin);
                    }

                    if (!roles.RoleExists(user))
                    {
                        roles.CreateRole(user);
                    }



                    // Поиск пользователя с логином admin
                    if (membership.GetUser("*****@*****.**", false) == null)
                    {
                        IDictionary <string, object> values = new Dictionary <string, object>();
                        values["FirstName"]        = "Maxim";
                        values["LastName"]         = "Bartosh";
                        values["RegistrationDate"] = DateTime.Now;
                        membership.CreateUserAndAccount("*****@*****.**", "qwe123", values);  // создание пользователя
                        roles.AddUsersToRoles(new[] { "*****@*****.**" }, new[] { "Admin" }); // установка роли для пользователя
                    }
                }
            }
Beispiel #18
0
        public ActionResult CreateUser(string NameOfUser, string ListOfUser, string PasOfUser)
        {
            SimpleRoleProvider       roles      = (SimpleRoleProvider)Roles.Provider;
            SimpleMembershipProvider membership = (SimpleMembershipProvider)Membership.Provider;



            if (membership.GetUser(NameOfUser, false) != null)
            {
                return(Content("Такий користувач уже існує"));
            }

            else
            {
                membership.CreateUserAndAccount(NameOfUser, PasOfUser);            // создание пользователя
                roles.AddUsersToRoles(new[] { NameOfUser }, new[] { ListOfUser }); // установка роли для пользователя
            }

            return(RedirectToAction("Index", "Home"));
        }
Beispiel #19
0
            public void CreateAdmin()
            {
                if (membership.GetUser("admin1", false) == null)
                {
                    WebSecurity.CreateUserAndAccount("admin1", "admin1admin1",
                                                     new
                    {
                        UserName           = "******",
                        UserSurname        = "admin1",
                        UserMidName        = "admin1",
                        UserEmail          = "*****@*****.**",
                        UserComment        = "admin1",
                        UserPhoneNumber    = "777",
                        UserPassword       = "******",
                        UserLogin          = "******",
                        UserConfirmedEmail = true
                    });

                    roles.AddUsersToRoles(new[] { "admin1" }, new[] { "Admin" });
                }
            }
Beispiel #20
0
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Попытка зарегистрировать пользователя
                try
                {
                    WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
                    SimpleRoleProvider role = (SimpleRoleProvider)Roles.Provider;
                    role.AddUsersToRoles(new[] { model.UserName }, new[] { "User" });
                    WebSecurity.Login(model.UserName, model.Password);
                    return(RedirectToAction("Index", "Home"));
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }

            // Появление этого сообщения означает наличие ошибки; повторное отображение формы
            return(View(model));
        }
Beispiel #21
0
        public ActionResult JsonRegister(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Регистрация пользователя
                try
                {
                    SimpleRoleProvider roles = (SimpleRoleProvider)Roles.Provider;

                    WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
                    roles.AddUsersToRoles(new[] { model.UserName }, new[] { "Customer" });
                    WebSecurity.Login(model.UserName, model.Password);

                    // Добавление пользователя в таблицу заказчиков
                    Customer customer = new Customer();

                    customer.UserId     = WebSecurity.GetUserId(model.UserName);
                    customer.CustomerId = Guid.NewGuid();
                    customer.Name       = "Александр Анатольевич Лось";
                    customer.Code       = "0007-2016";
                    customer.Address    = "Ленинская ул., д. 25, корп. 3, кв. 21";
                    customer.Discount   = 20;

                    unitOfWork.CustomerRepository().Insert(customer);
                    unitOfWork.Save();

                    InitiateDatabaseForNewUser(model.UserName);

                    FormsAuthentication.SetAuthCookie(model.UserName, createPersistentCookie: false);
                    return(Json(new { success = true }));
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }

            return(Json(new { success = false, errors = GetErrorsFromModelState() }));
        }
Beispiel #22
0
        public static void Up()
        {
            const string adminRole     = "admin";
            const string readerRole    = "reader";
            const string librarianRole = "librarian";
            const string providerRole  = "provider";

            if (!roles.RoleExists(adminRole))
            {
                roles.CreateRole(adminRole);
            }

            if (!roles.RoleExists(readerRole))
            {
                roles.CreateRole(readerRole);
            }

            if (!roles.RoleExists(librarianRole))
            {
                roles.CreateRole(librarianRole);
            }

            if (!roles.RoleExists(providerRole))
            {
                roles.CreateRole(providerRole);
            }

            //Создание аккаунта администратора
            const string admin         = "admin";
            const string adminPassword = "******";


            if (membership.GetUser(admin, false) == null)
            {
                membership.CreateUserAndAccount(admin, adminPassword);
                if (!roles.IsUserInRole(admin, adminRole))
                {
                    roles.AddUsersToRoles(new[] { admin }, new[] { adminRole });
                }
            }

            const string reader         = "reader";
            const string readerPassword = "******";


            if (membership.GetUser(reader, false) == null)
            {
                membership.CreateUserAndAccount(reader, readerPassword);
                if (!roles.IsUserInRole(reader, readerRole))
                {
                    roles.AddUsersToRoles(new[] { reader }, new[] { readerRole });
                }
            }


            const string librarian         = "librarian";
            const string librarianPassword = "******";


            if (membership.GetUser(librarian, false) == null)
            {
                membership.CreateUserAndAccount(librarian, librarianPassword);
                if (!roles.IsUserInRole(librarian, librarianRole))
                {
                    roles.AddUsersToRoles(new[] { librarian }, new[] { librarianRole });
                }
            }

            const string provider         = "provider";
            const string providerPassword = "******";


            if (membership.GetUser(provider, false) == null)
            {
                membership.CreateUserAndAccount(provider, providerPassword);
                if (!roles.IsUserInRole(provider, providerRole))
                {
                    roles.AddUsersToRoles(new[] { provider }, new[] { providerRole });
                }
            }
        }
Beispiel #23
0
        public JsonResult FillDatabase()
        {
            try
            {
                SimpleRoleProvider roles = (SimpleRoleProvider)Roles.Provider;

                unitOfWork.ItemRepository().Insert(new Item()
                {
                    ItemId = new Guid("64b53092-00ae-44ec-bd48-08684bff00c5"), Code = "07-2016-AA14", Name = "Бананы", Price = 7350, Category = "Фрукты"
                });
                unitOfWork.ItemRepository().Insert(new Item()
                {
                    ItemId = new Guid("cf54cca2-2c07-42fc-89b8-48d32fd4d3aa"), Code = "07-2016-AB14", Name = "Томаты", Price = 8900, Category = "Фрукты"
                });
                unitOfWork.ItemRepository().Insert(new Item()
                {
                    ItemId = new Guid("9f48e3f1-e711-43c1-bd43-d2c05b171bb9"), Code = "07-2016-AC14", Name = "Персики", Price = 11590, Category = "Фрукты"
                });
                unitOfWork.ItemRepository().Insert(new Item()
                {
                    ItemId = new Guid("dcc7f386-9230-4c7d-a284-f51727a593ef"), Code = "07-2016-AD14", Name = "Груши", Price = 18900, Category = "Фрукты"
                });

                unitOfWork.ItemRepository().Insert(new Item()
                {
                    ItemId = new Guid("a015c172-041d-4b95-b3e6-888f408853b1"), Code = "07-2016-AE14", Name = "Салат", Price = 5550, Category = "Овощи"
                });
                unitOfWork.ItemRepository().Insert(new Item()
                {
                    ItemId = new Guid("dd100111-1378-45ef-be2e-b664e35bb24f"), Code = "07-2016-AF14", Name = "Зелень", Price = 7900, Category = "Овощи"
                });
                unitOfWork.ItemRepository().Insert(new Item()
                {
                    ItemId = new Guid("975521f1-e643-466b-88f8-d8c481bf663b"), Code = "07-2016-AG14", Name = "Кинза", Price = 3900, Category = "Овощи"
                });
                unitOfWork.ItemRepository().Insert(new Item()
                {
                    ItemId = new Guid("00e405a3-3b28-4f59-9aef-ba00cb229d51"), Code = "07-2016-AH14", Name = "Лук", Price = 6500, Category = "Овощи"
                });

                unitOfWork.ItemRepository().Insert(new Item()
                {
                    ItemId = new Guid("24c1c7f2-0b3b-4343-8524-43e2cd89146f"), Code = "07-2016-AI14", Name = "Сливки", Price = 5020, Category = "Молочные продукты"
                });
                unitOfWork.ItemRepository().Insert(new Item()
                {
                    ItemId = new Guid("5c3b2308-9851-4dd8-9cdd-d510ecaa3a23"), Code = "07-2016-AJ14", Name = "Молоко", Price = 7460, Category = "Молочные продукты"
                });
                unitOfWork.ItemRepository().Insert(new Item()
                {
                    ItemId = new Guid("88250daa-2a4b-486c-8e6b-e018bfefc705"), Code = "07-2016-AK14", Name = "Сметана", Price = 7640, Category = "Молочные продукты"
                });
                unitOfWork.ItemRepository().Insert(new Item()
                {
                    ItemId = new Guid("a47bef53-e9e4-4a1b-9ae6-1ba6e469efe0"), Code = "07-2016-AL14", Name = "Йогурт", Price = 3530, Category = "Молочные продукты"
                });

                // Добавление пользователя user1
                RegisterModel modelUser1 = new RegisterModel();
                modelUser1.UserName        = "******";
                modelUser1.Password        = "******";
                modelUser1.ConfirmPassword = "******";
                WebSecurity.CreateUserAndAccount(modelUser1.UserName, modelUser1.Password);
                roles.AddUsersToRoles(new[] { modelUser1.UserName }, new[] { "Customer" });
                int IdUser1 = WebSecurity.GetUserId(modelUser1.UserName);
                unitOfWork.CustomerRepository().Insert(new Customer()
                {
                    CustomerId = new Guid("74b8c8d2-601b-42f4-9755-4362a6259771"), UserId = IdUser1, Name = "Владимир", Code = "0001-2016", Address = "Москва, ул. Двинцев, 8", Discount = 15
                });

                // Добавление пользователя user2
                RegisterModel modelUser2 = new RegisterModel();
                modelUser2.UserName        = "******";
                modelUser2.Password        = "******";
                modelUser2.ConfirmPassword = "******";
                WebSecurity.CreateUserAndAccount(modelUser2.UserName, modelUser2.Password);
                roles.AddUsersToRoles(new[] { modelUser2.UserName }, new[] { "Customer" });
                int IdUser2 = WebSecurity.GetUserId(modelUser2.UserName);
                unitOfWork.CustomerRepository().Insert(new Customer()
                {
                    CustomerId = new Guid("e1fe51b4-2bb2-4852-8a6a-49ddb6c6ed0a"), UserId = IdUser2, Name = "Александр", Code = "0002-2016", Address = "Москва, ул. Летниковская, 7", Discount = 0
                });

                // Добавление пользователя user3
                RegisterModel modelUser3 = new RegisterModel();
                modelUser3.UserName        = "******";
                modelUser3.Password        = "******";
                modelUser3.ConfirmPassword = "******";
                WebSecurity.CreateUserAndAccount(modelUser3.UserName, modelUser3.Password);
                roles.AddUsersToRoles(new[] { modelUser3.UserName }, new[] { "Customer" });
                int IdUser3 = WebSecurity.GetUserId(modelUser3.UserName);
                unitOfWork.CustomerRepository().Insert(new Customer()
                {
                    CustomerId = new Guid("701ac7ce-8c18-43d4-9b95-4377c7997bc4"), UserId = IdUser3, Name = "Василий", Code = "0003-2016", Address = "Москва, ул. Кожевническая, 18", Discount = 10
                });

                unitOfWork.OrderRepository().Insert(new Order()
                {
                    OrderId = new Guid("6cd1ec27-54b8-4393-9f8c-fb8a3447205d"), CustomerId = new Guid("74b8c8d2-601b-42f4-9755-4362a6259771"), OrderDate = new DateTime(2016, 8, 3), ShipmentDate = null, OrderNumber = 482791, Status = "Новый"
                });
                unitOfWork.OrderRepository().Insert(new Order()
                {
                    OrderId = new Guid("833f3f05-dda0-4b1f-b894-7242c6c69377"), CustomerId = new Guid("74b8c8d2-601b-42f4-9755-4362a6259771"), OrderDate = new DateTime(2015, 5, 13), ShipmentDate = new DateTime(2015, 5, 21), OrderNumber = 736019, Status = "Выполнен"
                });
                unitOfWork.OrderRepository().Insert(new Order()
                {
                    OrderId = new Guid("10cca820-bfa3-4926-932d-cb3e923a5bcc"), CustomerId = new Guid("e1fe51b4-2bb2-4852-8a6a-49ddb6c6ed0a"), OrderDate = new DateTime(2016, 8, 26), ShipmentDate = new DateTime(2016, 9, 9), OrderNumber = 778130, Status = "Выполняется"
                });
                unitOfWork.OrderRepository().Insert(new Order()
                {
                    OrderId = new Guid("8f2cc9f4-c2f8-4b43-8ceb-5bc1489f6544"), CustomerId = new Guid("e1fe51b4-2bb2-4852-8a6a-49ddb6c6ed0a"), OrderDate = new DateTime(2016, 8, 24), ShipmentDate = new DateTime(2016, 9, 12), OrderNumber = 661031, Status = "Выполняется"
                });
                unitOfWork.OrderRepository().Insert(new Order()
                {
                    OrderId = new Guid("7c85d7f5-0743-4e2f-a0d3-b28f3c3f83f8"), CustomerId = new Guid("701ac7ce-8c18-43d4-9b95-4377c7997bc4"), OrderDate = new DateTime(2016, 8, 20), ShipmentDate = new DateTime(2016, 9, 10), OrderNumber = 675107, Status = "Выполняется"
                });

                unitOfWork.PositionRepository().Insert(new Position()
                {
                    PositionId = new Guid("ce5b2e51-0b44-41d8-9060-c130b7a8308f"), OrderId = new Guid("6cd1ec27-54b8-4393-9f8c-fb8a3447205d"), ItemId = new Guid("64b53092-00ae-44ec-bd48-08684bff00c5"), ItemsCount = 1
                });
                unitOfWork.PositionRepository().Insert(new Position()
                {
                    PositionId = new Guid("f954a161-7300-4309-be99-0190cfb32ce5"), OrderId = new Guid("6cd1ec27-54b8-4393-9f8c-fb8a3447205d"), ItemId = new Guid("9f48e3f1-e711-43c1-bd43-d2c05b171bb9"), ItemsCount = 3
                });
                unitOfWork.PositionRepository().Insert(new Position()
                {
                    PositionId = new Guid("ee5eec2e-5376-4189-b3e0-69bf1ca92a81"), OrderId = new Guid("6cd1ec27-54b8-4393-9f8c-fb8a3447205d"), ItemId = new Guid("dd100111-1378-45ef-be2e-b664e35bb24f"), ItemsCount = 1
                });

                unitOfWork.PositionRepository().Insert(new Position()
                {
                    PositionId = new Guid("a401b440-02eb-4bdb-b1db-8a6a5f8ae319"), OrderId = new Guid("833f3f05-dda0-4b1f-b894-7242c6c69377"), ItemId = new Guid("64b53092-00ae-44ec-bd48-08684bff00c5"), ItemsCount = 5
                });
                unitOfWork.PositionRepository().Insert(new Position()
                {
                    PositionId = new Guid("5411d6bf-4456-4df1-983e-5943c07603ee"), OrderId = new Guid("833f3f05-dda0-4b1f-b894-7242c6c69377"), ItemId = new Guid("975521f1-e643-466b-88f8-d8c481bf663b"), ItemsCount = 1
                });

                unitOfWork.PositionRepository().Insert(new Position()
                {
                    PositionId = new Guid("3e5e9923-e465-45aa-bbb0-462d48f56372"), OrderId = new Guid("10cca820-bfa3-4926-932d-cb3e923a5bcc"), ItemId = new Guid("dcc7f386-9230-4c7d-a284-f51727a593ef"), ItemsCount = 12
                });

                unitOfWork.PositionRepository().Insert(new Position()
                {
                    PositionId = new Guid("d3fafd97-f0e3-4932-b2b9-6e1a737b0e89"), OrderId = new Guid("8f2cc9f4-c2f8-4b43-8ceb-5bc1489f6544"), ItemId = new Guid("dd100111-1378-45ef-be2e-b664e35bb24f"), ItemsCount = 3
                });

                unitOfWork.PositionRepository().Insert(new Position()
                {
                    PositionId = new Guid("00655330-dd4b-4ceb-bbda-aaf840647162"), OrderId = new Guid("7c85d7f5-0743-4e2f-a0d3-b28f3c3f83f8"), ItemId = new Guid("00e405a3-3b28-4f59-9aef-ba00cb229d51"), ItemsCount = 1
                });
                unitOfWork.PositionRepository().Insert(new Position()
                {
                    PositionId = new Guid("29301d99-c12a-4b00-8f3d-cce5020d2343"), OrderId = new Guid("7c85d7f5-0743-4e2f-a0d3-b28f3c3f83f8"), ItemId = new Guid("975521f1-e643-466b-88f8-d8c481bf663b"), ItemsCount = 2
                });

                // Корзина пользователя user2
                unitOfWork.PositionRepository().Insert(new Position()
                {
                    PositionId = new Guid("88506a4a-380b-4e6d-adc9-f2b45f6f191b"), OrderId = new Guid("73cf5c49-58f6-4148-8ecb-696e90864295"), ItemId = new Guid("64b53092-00ae-44ec-bd48-08684bff00c5"), ItemsCount = 1
                });
                unitOfWork.PositionRepository().Insert(new Position()
                {
                    PositionId = new Guid("48c13fd4-1d8b-4dc4-b19c-fe4c587bc136"), OrderId = new Guid("73cf5c49-58f6-4148-8ecb-696e90864295"), ItemId = new Guid("dcc7f386-9230-4c7d-a284-f51727a593ef"), ItemsCount = 4
                });
                unitOfWork.PositionRepository().Insert(new Position()
                {
                    PositionId = new Guid("aa9dd034-8697-49f9-a94f-549808c6b874"), OrderId = new Guid("73cf5c49-58f6-4148-8ecb-696e90864295"), ItemId = new Guid("cf54cca2-2c07-42fc-89b8-48d32fd4d3aa"), ItemsCount = 2
                });

                unitOfWork.Save();

                return(Json(new { success = true }, JsonRequestBehavior.AllowGet));
            }
            catch
            {
                return(Json(new { success = false }, JsonRequestBehavior.AllowGet));
            }
        }
Beispiel #24
0
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer <DBStoreMVC>(null);

                try
                {
                    using (var context = new DBStoreMVC())
                    {
                        if (!context.Database.Exists())
                        {
                            // Создание базы данных SimpleMembership без применения миграции Entity Framework
                            ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                        }
                    }
                    // Настройка  ASP.NET Simple Membership
                    // 1 параметр - имя строки подключения к базе данных.
                    // 2 параметр - таблица, которая содержит информацию о пользователях
                    // 3 параметр - имя колонки в таблице, которая отвечает за хранение логина
                    // 4 параметр - autoCreateTables автоматическое создание таблиц если они не существуют в базе
                    WebSecurity.InitializeDatabaseConnection("DBStoreMVC", "UserProfiles", "UserId", "UserName", autoCreateTables: true);

                    SimpleRoleProvider       roles      = (SimpleRoleProvider)Roles.Provider;
                    SimpleMembershipProvider membership = (SimpleMembershipProvider)Membership.Provider;

                    // Проверка наличия роли Admin
                    if (!roles.RoleExists("Admin"))
                    {
                        roles.CreateRole("Admin");
                    }
                    // Проверка наличия роли Moderator
                    if (!roles.RoleExists("Moderator"))
                    {
                        roles.CreateRole("Moderator");
                    }
                    // Проверка наличия роли User
                    if (!roles.RoleExists("User"))
                    {
                        roles.CreateRole("User");
                    }

                    IDictionary <string, object> deFaultEmail = new Dictionary <string, object>();
                    deFaultEmail.Add("Email", "*****@*****.**");
                    // Поиск пользователя с логином admin
                    if (membership.GetUser("admin", false) == null)
                    {
                        /*WebSecurity.CreateUserAndAccount("admin", "qwerty", new { FirstName = "Main", LastName = "Admin", Patronymic = "", Email = "*****@*****.**" });*/
                        membership.CreateUserAndAccount("admin", "qwerty", false, deFaultEmail);             // создание пользователя
                        roles.AddUsersToRoles(new[] { "admin" }, new[] { "Admin" });                         // установка роли для пользователя
                    }
                    if (membership.GetUser("moder", false) == null)
                    {
                        membership.CreateUserAndAccount("moder", "qwerty", false, deFaultEmail);                 // создание пользователя
                        roles.AddUsersToRoles(new[] { "moder" }, new[] { "Moderator" });                         // установка роли для пользователя
                    }
                    //if (membership.GetUser("user", false) == null)
                    //{
                    //	membership.CreateUserAndAccount("user", "qwerty", false, deFaultEmail);
                    //	roles.AddUsersToRoles(new[] { "user" }, new[] { "User" });
                    //}
                }
                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);
                }
            }
Beispiel #25
0
 public void CreateNewUser(string username, string password, string role = "Member")
 {
     memberships.CreateUserAndAccount(username, password);
     roles.AddUsersToRoles(new[] { username }, new[] { role });
 }