Esempio n. 1
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);
                }
            }
Esempio n. 3
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 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);
            }
        }
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer <UsersContext>(null);

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

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

                    SimpleMembershipProvider provider = (SimpleMembershipProvider)Membership.Provider;
                    if (provider.GetUser("user", false) == null)
                    {
                        provider.CreateUserAndAccount("user", "user1111");
                    }

                    //WebSecurity.CreateUserAndAccount("user1", "user1111");
                }
                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. 6
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);
        }
Esempio n. 7
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;
            }
        }
            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" }); // установка роли для пользователя
                    }
                }
            }
Esempio n. 10
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);
        }
Esempio n. 11
0
        private UserProfile GetUserProfile(string CPF)
        {
            var currentUser = currentDb.UserProfiles.FirstOrDefault(e => e.UserName == CPF);

            if (currentUser == null)
            {
                if (membership.GetUser(CPF, false) != null)
                {
                    throw new Exception("User '" + CPF + "' was not found under UserProfiles but is already registered as a membership user.");
                }
                membership.CreateUserAndAccount(CPF, CPF);
                currentUser = currentDb.UserProfiles.First(e => e.UserName == CPF);
            }
            currentUser.PersonalInfo.CPF  = CPF;
            currentUser.PersonalInfo.Name = GetValue("NOME");
            currentUser.ContactInfo.Email = GetValue("Email");
            currentUser.Active            = GetBoolValue("Ativo");
            currentDb.Entry(currentUser).CurrentValues.SetValues(currentUser);
            return(currentUser);
        }
Esempio n. 12
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"));
        }
Esempio n. 13
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);
                }
            }
Esempio n. 14
0
 public void CreateNewUser(string username, string password, string role = "Member")
 {
     memberships.CreateUserAndAccount(username, password);
     roles.AddUsersToRoles(new[] { username }, new[] { role });
 }
Esempio n. 15
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 });
                }
            }
        }