Esempio n. 1
0
        private List <int> GetUserIdsFromNames(IDatabase db, string[] usernames)
        {
            List <int> userIds = new List <int>(usernames.Length);

            foreach (string username in usernames)
            {
                int id = SimpleMembershipProvider.GetUserId(
                    db,
                    SafeUserTableName,
                    SafeUserNameColumn,
                    SafeUserIdColumn,
                    CasingBehavior,
                    username
                    );
                if (id == -1)
                {
                    throw new InvalidOperationException(
                              String.Format(
                                  CultureInfo.CurrentCulture,
                                  WebDataResources.Security_NoUserFound,
                                  username
                                  )
                              );
                }
                userIds.Add(id);
            }
            return(userIds);
        }
Esempio n. 2
0
        internal void CreateTablesIfNeeded()
        {
            using (var db = ConnectToDatabase())
            {
                if (!SimpleMembershipProvider.CheckTableExists(db, RoleTableName))
                {
                    db.Execute(
                        @"CREATE TABLE "
                        + RoleTableName
                        + @" (
                        RoleId                                  int                 NOT NULL PRIMARY KEY IDENTITY,
                        RoleName                                nvarchar(256)       NOT NULL UNIQUE)"
                        );

                    db.Execute(
                        @"CREATE TABLE "
                        + UsersInRoleTableName
                        + @" (
                        UserId                                  int                 NOT NULL,
                        RoleId                                  int                 NOT NULL,
                        PRIMARY KEY (UserId, RoleId),
                        CONSTRAINT fk_UserId FOREIGN KEY (UserId) REFERENCES "
                        + SafeUserTableName
                        + "("
                        + SafeUserIdColumn
                        + @"),
                        CONSTRAINT fk_RoleId FOREIGN KEY (RoleId) REFERENCES "
                        + RoleTableName
                        + "(RoleId) )"
                        );
                }
            }
        }
Esempio n. 3
0
        internal static void InitializeMembershipProvider(
            SimpleMembershipProvider simpleMembership,
            DatabaseConnectionInfo connect,
            string userTableName,
            string userIdColumn,
            string userNameColumn,
            bool createTables,
            SimpleMembershipProviderCasingBehavior casingBehavior
            )
        {
            if (simpleMembership.InitializeCalled)
            {
                throw new InvalidOperationException(
                          WebDataResources.Security_InitializeAlreadyCalled
                          );
            }

            simpleMembership.CasingBehavior = casingBehavior;
            simpleMembership.ConnectionInfo = connect;
            simpleMembership.UserIdColumn   = userIdColumn;
            simpleMembership.UserNameColumn = userNameColumn;
            simpleMembership.UserTableName  = userTableName;
            if (createTables)
            {
                simpleMembership.CreateTablesIfNeeded();
            }
            else
            {
                // We want to validate the user table if we aren't creating them
                simpleMembership.ValidateUserTable();
            }
            simpleMembership.InitializeCalled = true;
        }
        /// <summary>
        /// Iterates through a list of students, sets up the default password then
        /// assigns the student to the relevant role
        /// </summary>
        /// <param name="membership">instance of the simplemembership provider</param>
        /// <param name="roleProvider">instance of the simpleroleprovider</param>
        private static void SetUpStudents(SimpleMembershipProvider membership, SimpleRoleProvider roleProvider)
        {
            new List<string> {"Andrew", "Tim", "Bartoz", "Narelle", "Robert"}
                .ForEach(u =>

                        SetUpUserInRole(membership,roleProvider,"Student",u)
                    );
        }
        /// <summary>
        /// Iterates through a list of Instructors, sets up the default password then
        /// assigns the instructor to the relevant role
        /// </summary>
        /// <param name="membership">instance of the simplemembership provider</param>
        /// <param name="roles">instance of the simpleroleprovider</param>
        private static void SetUpInstructors(SimpleMembershipProvider membership, SimpleRoleProvider roles)
        {
            new List<string> {"JPaterson", "BMacDonald"}
                .ForEach(u =>

                        SetUpUserInRole(membership, roles, "Instructor", u)
                    );
        }
Esempio n. 6
0
        private static SimpleMembershipProvider CreateDefaultSimpleMembershipProvider(string name, MembershipProvider currentDefault)
        {
            var membership             = new SimpleMembershipProvider(previousProvider: currentDefault);
            NameValueCollection config = new NameValueCollection();

            membership.Initialize(name, config);
            return(membership);
        }
 private static SimpleMembershipProvider CreateDefaultSimpleMembershipProvider(string name, MembershipProvider currentDefault)
 {
     MembershipProvider previousProvider = currentDefault;
     SimpleMembershipProvider provider = new SimpleMembershipProvider(previousProvider);
     NameValueCollection config = new NameValueCollection();
     provider.Initialize(name, config);
     return provider;
 }
Esempio n. 8
0
        private static void InitializeProviders(DatabaseConnectionInfo connect, string userTableName, string userIdColumn, string userNameColumn, bool autoCreateTables)
        {
            SimpleMembershipProvider sMembership = Membership.Provider as SimpleMembershipProvider;

            if (sMembership != null)
            {
                InitializeMembershipProvider(sMembership, connect, userTableName, userIdColumn, userNameColumn, autoCreateTables);
            }

            SimpleRoleProvider sRoles = Roles.Provider as SimpleRoleProvider;

            if (sRoles != null)
            {
                InitializeRoleProvider(sRoles, connect, userTableName, userIdColumn, userNameColumn, autoCreateTables);
            }
        }
Esempio n. 9
0
        // Inherited from RoleProvider ==> Forwarded to previous provider if this provider hasn't been initialized
        public override string[] GetRolesForUser(string username)
        {
            if (!InitializeCalled)
            {
                return(PreviousProvider.GetRolesForUser(username));
            }
            using (var db = ConnectToDatabase()) {
                int userId = SimpleMembershipProvider.GetUserId(db, SafeUserTableName, SafeUserNameColumn, SafeUserIdColumn, username);
                if (userId == -1)
                {
                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, WebDataResources.Security_NoUserFound, username));
                }

                string query = @"SELECT r.RoleName FROM " + UsersInRoleTableName + " u, " + RoleTableName + " r Where (u.UserId = @0 and u.RoleId = r.RoleId) GROUP BY RoleName";
                return(db.Query(query, new object[] { userId }).Select <dynamic, string>(d => (string)d[0]).ToArray());
            }
        }
Esempio n. 10
0
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // 尝试注册用户
                try
                {
                    //首先注册用户
                    WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
                    Email.RegisterReminder("新用户注册提醒!注册ID:" + model.UserName + ",姓名:" + model.Name +
                                      ",移动电话:" + model.MobilePhone + ",注册时间:" + DateTime.Now
                                      );
                    #region 附加用户Profile信息
                    UserProfile adduser = UsersDB.UserProfiles.Where(i => i.UserName == model.UserName).Single();

                    adduser.Name = model.Name; //用户名 必填
                    adduser.MobilePhone = model.MobilePhone;//移动电话 必填

                    adduser.Phone = model.Phone;
                    adduser.Birth = model.Birth;
                    adduser.Country = model.Country;
                    adduser.Place = model.Place;
                    adduser.Address = model.Address;
                    adduser.ZipCode = model.ZipCode;
                    adduser.WantGet = model.WantGet;
                    adduser.HasGlucometer = model.HasGlucometer;
                    adduser.GlucometerType = model.GlucometerType;
                    adduser.GlucometerId = model.GlucometerId;
                    adduser.IsWantGetInformation = model.IsWantGetInformation;

                    adduser.Gender = model.Gender;
                    adduser.DateOfDiagnosis = model.DateOfDiagnosis;
                    adduser.DiabetesType = model.DiabetesType;
                    //adduser.DiseaseControl = model.DiseaseControl;
                    adduser.DiseaseControl = Request.Form["DiseaseControl"];
                    // adduser.HasRecommend = model.HasRecommend;
                    adduser.HasRecommend = Request.Form["HasRecommend"];
                    adduser.TestFrequency = model.TestFrequency;
                    #endregion

                    try
                    {
                        UsersDB.SaveChanges();
                    }
                    catch
                    {
                        //删除用户
                        if (WebSecurity.UserExists(model.UserName))
                        {
                            SimpleMembershipProvider smp = new SimpleMembershipProvider();
                            smp.DeleteAccount(model.UserName);

                        }
                    }

                    WebSecurity.Login(model.UserName, model.Password);
                    return RedirectToAction("RegisterSuccess", "Account");
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }

            // 如果我们进行到这一步时某个地方出错,则重新显示表单
            return View(model);
        }
Esempio n. 11
0
 private static SimpleMembershipProvider CreateDefaultSimpleMembershipProvider(string name, MembershipProvider currentDefault)
 {
     var membership = new SimpleMembershipProvider(previousProvider: currentDefault);
     NameValueCollection config = new NameValueCollection();
     membership.Initialize(name, config);
     return membership;
 }
Esempio n. 12
0
 internal static void InitializeMembershipProvider(SimpleMembershipProvider simpleMembership, DatabaseConnectionInfo connect, string userTableName, string userIdColumn, string userNameColumn, bool createTables)
 {
     if (simpleMembership.InitializeCalled)
     {
         throw new InvalidOperationException(WebDataResources.Security_InitializeAlreadyCalled);
     }
     simpleMembership.ConnectionInfo = connect;
     simpleMembership.UserIdColumn = userIdColumn;
     simpleMembership.UserNameColumn = userNameColumn;
     simpleMembership.UserTableName = userTableName;
     if (createTables)
     {
         simpleMembership.CreateTablesIfNeeded();
     }
     else
     {
         // We want to validate the user table if we aren't creating them
         simpleMembership.ValidateUserTable();
     }
     simpleMembership.InitializeCalled = true;
 }
 private static bool IsMembershipProviderInitialized(SimpleMembershipProvider provider) {
     return provider.UserTableName.IsEmpty() || provider.UserIdColumn.IsEmpty() || provider.UserNameColumn.IsEmpty();
 }
Esempio n. 14
0
            public void CanDeleteAccount()
            {
                var simpleMembershipProvider = new SimpleMembershipProvider();

                simpleMembershipProvider.DeleteAccount("Test1");
            }
Esempio n. 15
0
            public void CanCreateAccount()
            {
                var simpleMembershipProvider = new SimpleMembershipProvider();

                simpleMembershipProvider.CreateAccount("Test1", "notAPassword1");
            }
        /// <summary>
        /// Sets up the account of the provided username in the role provided
        /// </summary>
        /// <param name="membership">instance of the simple membership provider</param>
        /// <param name="roleProvider">instance of the simple roleprovider</param>
        /// <param name="role">Role type to be assigned</param>
        /// <param name="userName">Username</param>
        private static void SetUpUserInRole(SimpleMembershipProvider membership,SimpleRoleProvider roleProvider,string role,string userName)
        {
            var user = membership.GetUser(userName, false);

            // test if user exists and if the membership details also exist.  If not the date returned is 01/01/0001
            if (user != null && membership.GetCreateDate(userName) == default(DateTime))
            {
                membership.CreateAccount(userName, "password");

            }

            IList rolesforuser = roleProvider.GetRolesForUser(userName);

            if (!rolesforuser.Contains(role))
            {
                roleProvider.AddUsersToRoles(new[] { userName }, new[] { role });
            }
        }
        /// <summary>
        /// Checks if account and role of super user needs to be setup
        /// </summary>
        /// <param name="membershipProvider">instance of the simplemembership provider</param>
        /// <param name="roleProvider">instance of the simpleroleprovider</param>
        private static void SetUpSuperUser(SimpleMembershipProvider membershipProvider, SimpleRoleProvider roleProvider)
        {
            if (membershipProvider.GetUser("admin", false) == null)
            {
                membershipProvider.CreateUserAndAccount("admin", "password");
            }

            IList rolesforuser = roleProvider.GetRolesForUser("admin");

            if (!rolesforuser.Contains("Admin"))
            {
                roleProvider.AddUsersToRoles(new[] {"admin"}, new[] {"Admin"});
            }
        }
Esempio n. 18
0
		public MembershipUser InsertNewUser(String UserName, String Passwort, String eMail)
			{
			MembershipCreateStatus Status;
			SimpleMembershipProvider Provider = new SimpleMembershipProvider();
			MembershipUser NewUser = Provider.CreateUser(UserName, Passwort, eMail, "", "", true, null, out Status);
			return NewUser;
		    }