public void FillStandardUserFormBlock(AjaxFormFieldBlock block, User user, bool plainTextPassword, bool multilingual, bool requireFullName, bool allowUsernameEditing)
        {
            bool newUser = user == null;

            string labelUsername = multilingual ? "{?form-label-username?}" : "Username";
            string labelPassword = multilingual ? "{?form-label-password?}" : "Password";
            string labelFirstName = multilingual ? "{?form-label-firstname?}" : "FirstName";
            string labelSurname = multilingual ? "{?form-label-surname?}" : "Surname";
            string labelEmail = multilingual ? "{?form-label-email?}" : "Email";

            string errNoUsername = multilingual ? "{?form-error-require-username?}" : "Please enter a username";
            string errNoFirstName = multilingual ? "{?form-error-require-firstname?}" : "Please enter your first name";
            string errNoSurname = multilingual ? "{?form-error-require-surname?}" : "Please enter your surname";
            string errNoEmail = multilingual ? "{?form-error-require-email?}" : "Please enter your email address";
            string errNoPassword = multilingual ? "{?form-error-require-password?}" : "Please enter your email password";

            string fErr = "function(value){{if(value.length==0) return '{0}'; return null;}}";
            string pErr = !newUser ? null : string.Format(fErr, errNoPassword);
            string fnErr = !requireFullName ? null : string.Format(fErr, errNoFirstName);
            string snErr = !requireFullName ? null : string.Format(fErr, errNoSurname);

            if (newUser) user = new User();
            bool locked = user.Locked;
            if(allowUsernameEditing)
                block.Add(new AjaxFormInputField(labelUsername, "Username", 50, locked, null, "width:150px;", user.Username, null, string.Format(fErr, errNoUsername), true, 0));
            if (plainTextPassword)
                block.Add(new AjaxFormInputField(labelPassword, "Password", 50, false, null, "width:150px;", null, null, pErr, true, ObjectRank.Early));
            else
                block.Add(new AjaxFormPasswordField(labelPassword, 50, null, "width:73px", ObjectRank.Early, multilingual, newUser, !newUser));
            block.Add(new AjaxFormInputField(labelFirstName, "FirstName", 50, false, null, "width:150px;", user.FirstName, null, fnErr, true, ObjectRank.Normal));
            block.Add(new AjaxFormInputField(labelSurname, "Surname", 50, false, null, "width:150px;", user.Surname, null, snErr, true, ObjectRank.Normal));
            block.Add(new AjaxFormInputField(labelEmail, "Email", 100, false, null, "width:150px;", user.Email, null, string.Format(fErr, errNoEmail), true, ObjectRank.Normal));
        }
        public Result DeleteUser(User user)
        {
            if (OnBeforeUserDeleted != null)
            {
                StateChangingEventArgs args = new StateChangingEventArgs();
                OnBeforeUserDeleted(user, args);
                if (args.CancelStateChange)
                    return new Result(args.ReasonForCancellation);
            }

            IDbCommand cmd = Database.Main.CreateCommand("DeleteUser", CommandType.StoredProcedure);
            Database.Main.AddParameter(cmd, "@UserID", user.UserID);
            Database.Main.AddParameter(cmd, "@DeletePermanently", true);
            cmd.ExecuteNonQuery();

            if (OnUserDeleted != null)
                OnUserDeleted(user);

            return new Result();
        }
        public User SaveStandardUserFormDetails(AjaxFormSubmittedValues form, string blockName, bool? enabled)
        {
            AjaxFormSubmittedValues.Block block = form.Blocks[blockName];
            string pw;
            if (block.Fields.ContainsKey("Password1"))
                pw = block.Fields["Password1"].Value;
            else
                pw = block.Fields["Password"].Value;
            if (pw.Length == 0) pw = null;

            User user;
            if (form.RecordID == null)
            {
                user = new User(
                    SecurityProvider.ClientSpaceID,
                    block.Fields["Username"].Value,
                    pw,
                    block.Fields["FirstName"].Value,
                    block.Fields["Surname"].Value,
                    block.Fields["Email"].Value,
                    enabled == null ? (block.Fields["Enabled"].Value == "True") : enabled.Value,
                    false, false, 0);
                if (OnBeforeSaveUser != null)
                    OnBeforeSaveUser(form, user);
                SecurityProvider.DataLayer.Store(user);
                form.RecordID = user.UserID;
            }
            else
            {
                long myuserid = SecurityProvider.CurrentUser.UserID;
                // string myoldusername = CurrentUser.Username;
                user = User.Select(form.RecordID.Value);
                // user.Username = block.Fields["Username"].Value;
                if (pw != null) user.Password = pw;
                user.FirstName = block.Fields["FirstName"].Value;
                user.Surname = block.Fields["Surname"].Value;
                user.Email = block.Fields["Email"].Value;
                user.Enabled = enabled == null ? (block.Fields["Enabled"].Value == "True") : enabled.Value;
                if (OnBeforeSaveUser != null)
                    OnBeforeSaveUser(form, user);
                SecurityProvider.DataLayer.Store(user);

                /* we're not going to allow the user to change their username, so this code is commented out
                if (myuserid == user.UserID && (pw != null || user.Username != myoldusername)) // changing username or password causes login cookie to become invalid
                    WebAuthentication.Instance.WriteAuthenticationCookie(
                        user.Username,
                        pw != null ? Crypto.EncryptOneWay(pw) : user.PasswordHash,
                        WebAuthentication.Instance.StoreAjaxAuthKey(user.Username),
                        1440); */
            }
            return user;
        }
        void OnSaveForm(AjaxFormSubmittedValues form)
        {
            List<string> roleCodes = new List<string>(), permissionTypeCodes = new List<string>();
            switch (form.FormName)
            {
                case "UserEditForm":
                    if (!WebAuthentication.VerifyAccess(PermissionType.UserAdministrator))
                        return;
                    AjaxFormSubmittedValues.Block block = form.Blocks["MainUserFields"];
                    string pw = block.Fields["Password"].Value;
                    bool enabled = block.Fields["Enabled"].Value == "True";
                    if (pw.Length == 0) pw = null;
                    User user;

                    if (form.RecordID == null)
                    {
                        user = new User(
                            SecurityProvider.ClientSpaceID,
                            block.Fields["Username"].Value,
                            pw,
                            block.Fields["FirstName"].Value,
                            block.Fields["Surname"].Value,
                            block.Fields["Email"].Value,
                            enabled, false, false, 0);
                        Result result = SecurityProvider.DataLayer.Store(user);
                        if (!result.Succeeded)
                            throw new AjaxException(result.Message);
                        if (OnUserSaved != null)
                            OnUserSaved(form, user);

                        form.RecordID = user.UserID;
                    }
                    else
                    {
                        user = User.Select(form.RecordID.Value);
                        //if (!CurrentUser.CanModifyUser(user))
                        //    throw new AjaxException("You don't have access to modify that user.");
                        user.Username = block.Fields["Username"].Value;
                        if (pw != null) user.Password = pw;
                        user.FirstName = block.Fields["FirstName"].Value;
                        user.Surname = block.Fields["Surname"].Value;
                        user.Email = block.Fields["Email"].Value;
                        user.Enabled = enabled;
                        SecurityProvider.DataLayer.Store(user);
                        //user.Save();
                        if (OnUserSaved != null)
                            OnUserSaved(form, user);

                        if (user.Locked) return; // don't muck with permissions/roles
                    }

                    if (user.Username != SecurityProvider.CurrentUser.Username) // users can't alter their own permissions
                    {
                        if (form.Blocks.ContainsKey("Roles"))
                            foreach (KeyValuePair<string, AjaxFormSubmittedValues.Field> kvp in form.Blocks["Roles"].Fields)
                                if (SecurityProvider.CurrentUser.HasRole(kvp.Value.Name)) //make sure the logged in user has the right to assign this role
                                    if (kvp.Value.Value == "True")
                                        roleCodes.Add(kvp.Value.Name);
                                        //sql.AppendFormat("exec AssignUserToRole '{0}', '{1}'\r\n", user.UserID, kvp.Value.Name.Replace("'", "''"));
                        if (form.Blocks.ContainsKey("Permissions"))
                            foreach (KeyValuePair<string, AjaxFormSubmittedValues.Field> kvp in form.Blocks["Permissions"].Fields)
                                if (SecurityProvider.CurrentUser.HasRole(kvp.Value.Name)) //make sure the logged in user has the right to assign this role
                                    if (kvp.Value.Value == "True")
                                        permissionTypeCodes.Add(kvp.Value.Name);
                                        //sql.AppendFormat("exec AssignPermission '{0}', null, '{1}'\r\n", kvp.Value.Name.Replace("'", "''"), user.UserID);
                        //if (sql.Length == 0) return;

                        SecurityProvider.DataLayer.SetRolesAndPermissionsForUser(user.UserID, roleCodes, permissionTypeCodes);
                        //user.RevokeRolesAndPermissions(); // revoke any pre-existing permissions/roles before we assign the new ones
                        //Database.Main.CreateCommand(sql.ToString(), CommandType.Text).ExecuteNonQuery();
                    }
                    break;

                case "RoleEditForm":
                    if (!WebAuthentication.VerifyAccess(PermissionType.RoleAdministrator))
                        return;
                    block = form.Blocks["RoleDetails"];
                    string name = block.Fields["Name"].Value;
                    enabled = block.Fields["Enabled"].Value == "True";
                    Role role;
                    if (form.RecordID == null)
                    {
                        role = new Role();
                        role.RoleID = DatabaseManager.GetUniqueID();
                        role.RoleCode = role.RoleID.ToString(); // role codes are only used by system roles
                        role.ClientSpaceID = SecurityProvider.ClientSpaceID;
                    }
                    else
                    {
                        role = Role.Select(form.RecordID.Value);
                        if (role == null) return;
                        if (role.Locked) return; // locked roles aren't supposed to be edited by users
                    }
                    role.Name = name;
                    role.Enabled = enabled;
                    SecurityProvider.DataLayer.Store(role);
                    //((SecurityProvider)Core.Instance["SecurityProvider"]).SaveRole(role);

                    //sql = new StringBuilder();
                    if (form.Blocks.ContainsKey("Roles"))
                        foreach (KeyValuePair<string, AjaxFormSubmittedValues.Field> kvp in form.Blocks["Roles"].Fields)
                            if (SecurityProvider.CurrentUser.HasRole(kvp.Value.Name)) //make sure the logged in user has the right to assign this role
                                if (kvp.Value.Value == "True")
                                    roleCodes.Add(kvp.Value.Name);
                                    //sql.AppendFormat("exec InheritRoleFrom '{0}', '{1}'\r\n", role.RoleID, kvp.Value.Name.Replace("'", "''"));
                    if (form.Blocks.ContainsKey("Permissions"))
                        foreach (KeyValuePair<string, AjaxFormSubmittedValues.Field> kvp in form.Blocks["Permissions"].Fields)
                            if (SecurityProvider.CurrentUser.HasRole(kvp.Value.Name)) //make sure the logged in user has the right to assign this role
                                if (kvp.Value.Value == "True")
                                    permissionTypeCodes.Add(kvp.Value.Name);
                                    //sql.AppendFormat("exec AssignPermission '{0}', null, '{1}'\r\n", kvp.Value.Name.Replace("'", "''"), role.RoleID);

                    SecurityProvider.DataLayer.SetRolesAndPermissionsForRole(role.RoleID, roleCodes, permissionTypeCodes);
                    //role.RevokeRolesAndPermissions(); // revoke any pre-existing permissions/roles before we assign the new ones
                    //if (sql.Length == 0) return;
                    //Database.Main.CreateCommand(sql.ToString(), CommandType.Text).ExecuteNonQuery();
                    break;
            }
        }
Exemple #5
0
 public bool CanModifyUser(User targetUser)
 {
     foreach (KeyValuePair<string, Permission> p in targetUser.Permissions)
         if (!HasPermission(p.Key))
             return false;
     foreach (KeyValuePair<string, Permission> r in targetUser.Roles)
         if (!HasRole(r.Key))
             return false;
     return true;
 }
Exemple #6
0
 public static User LoadByEmail(Guid clientID, string emailAddress)
 {
     IDbCommand cmd = Database.Main.CreateCommand("ListUsers", CommandType.StoredProcedure);
     Database.Main.AddParameter(cmd, "@ClientID", clientID);
     Database.Main.AddParameter(cmd, "@Email", emailAddress);
     Database.Main.AddParameter(cmd, "@ExactMatches", true);
     DataSet ds = Database.Main.GetDataSet(cmd);
     if (ds.Tables[0].Rows.Count == 0)
         return null;
     User user = new User(ds.Tables[0].Rows[0]);
     return user;
 }
Exemple #7
0
 public static User Load(Guid userID)
 {
     IDbCommand cmd = Database.Main.CreateCommand("ListUsers", CommandType.StoredProcedure);
     Database.Main.AddParameter(cmd, "@UserID", userID);
     DataSet ds = Database.Main.GetDataSet(cmd);
     if (ds.Tables[0].Rows.Count == 0)
         return null;
     User user = new User(ds.Tables[0].Rows[0]);
     return user;
 }
Exemple #8
0
 public static User[] BasicSearch(string partUsername, string partFirstName, string partSurname, string partEmail, int? maxResults, Guid? editableByUserID, out int totalMatches, bool? activated)
 {
     if (maxResults == 0) maxResults = null;
     if (partUsername == "") partUsername = null;
     if (partFirstName == "") partFirstName = null;
     if (partSurname == "") partSurname = null;
     IDbCommand cmd = Database.Main.CreateCommand("ListUsers", CommandType.StoredProcedure);
     Database.Main.AddParameter(cmd, "@Username", partUsername);
     Database.Main.AddParameter(cmd, "@FirstName", partFirstName);
     Database.Main.AddParameter(cmd, "@Surname", partSurname);
     Database.Main.AddParameter(cmd, "@Email", partEmail);
     Database.Main.AddParameter(cmd, "@Activated", activated);
     Database.Main.AddParameter(cmd, "@EditableByUserID", editableByUserID);
     Database.Main.AddParameter(cmd, "@MaxRecords", maxResults);
     IDataParameter prm = Database.Main.AddOutputParameter(cmd, "@TotalMatches", DbType.Int32);
     DataSet ds = Database.Main.GetDataSet(cmd);
     if (prm.Value != DBNull.Value)
         totalMatches = (int)prm.Value;
     else
         totalMatches = ds.Tables[0].Rows.Count;
     User[] users = new User[ds.Tables[0].Rows.Count];
     for(int i=0; i<ds.Tables[0].Rows.Count; i++)
         users[i] = new User(ds.Tables[0].Rows[i]);
     return users;
 }
		public User SelectUser(long userID)
		{
			using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Suppress))
			{
				using (SqlConnection conn = new SqlConnection(DatabaseManager.DatabaseEngine.ConnectionString))
				{
					conn.Open();
					SqlCommand cmd = new SqlCommand("SelectUser", conn);
					cmd.CommandType = CommandType.StoredProcedure;
					cmd.Parameters.Add(new SqlParameter("@UserID", userID));
					SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
					User user;
					if (!reader.Read())
						user = null;
					else
						user = new User(reader);
					reader.Close();
					return user;
				}
			}
		}
		public Result Delete(User user)
		{
			Result result = new Result();
			if (OnBeforeDeleteUser != null)
				OnBeforeDeleteUser(user, result);
			SqlConnection conn = null;
			if (result.Succeeded)
			{
				try
				{
					using (TransactionScope scope = new TransactionScope())
					{
						conn = (SqlConnection)DatabaseManager.DatabaseEngine.GetConnection();
						try
						{
							SqlCommand cmd = new SqlCommand("DeleteUser", conn);
							cmd.CommandType = CommandType.StoredProcedure;
							cmd.Parameters.Add(new SqlParameter("@UserID", user.UserID));
							cmd.ExecuteNonQuery();
							scope.Complete();
						}
						catch (Exception ex)
						{
							return new Result(ex.Message);
						}
					}
				}
				finally
				{
					DatabaseManager.DatabaseEngine.ReleaseConnection(conn);
				}
				if (OnUserDeleted != null)
					OnUserDeleted(user);
			}
			return result;
		}
		public Result Store(User user)
		{
			SqlConnection conn = null;
			try
			{
				using (TransactionScope scope = new TransactionScope())
				{
					conn = (SqlConnection)DatabaseManager.DatabaseEngine.GetConnection();
					try
					{
						SqlCommand cmd = new SqlCommand("StoreUser", conn);
						cmd.CommandType = CommandType.StoredProcedure;
						SqlParameter prm = new SqlParameter("@UserID", user.UserID);
						prm.Direction = ParameterDirection.InputOutput;
						cmd.Parameters.Add(prm);
						cmd.Parameters.Add(new SqlParameter("@ClientSpaceID", user.ClientSpaceID));
						cmd.Parameters.Add(new SqlParameter("@Username", user.Username));
						cmd.Parameters.Add(new SqlParameter("@PasswordHash", user.PasswordHash));
						cmd.Parameters.Add(new SqlParameter("@FirstName", user.FirstName));
						cmd.Parameters.Add(new SqlParameter("@Surname", user.Surname));
						cmd.Parameters.Add(new SqlParameter("@Email", user.Email));
						cmd.Parameters.Add(new SqlParameter("@Enabled", user.Enabled));
						cmd.Parameters.Add(new SqlParameter("@Hidden", user.Hidden));
						cmd.Parameters.Add(new SqlParameter("@Locked", user.Locked));
						cmd.Parameters.Add(new SqlParameter("@Deleted", user.Deleted));
						cmd.Parameters.Add(new SqlParameter("@Activated", user.Activated));
						cmd.Parameters.Add(new SqlParameter("@ActivationReminderSent", user.Activated));
						cmd.Parameters.Add(new SqlParameter("@Created", user.Created));
						cmd.Parameters.Add(new SqlParameter("@LastAuthenticated", user.LastAuthenticated));
						cmd.Parameters.Add(new SqlParameter("@LocalTimeOffsetHours", user.LocalTimeOffsetHours));
						for (int i = 0; i < cmd.Parameters.Count; i++)
							if (cmd.Parameters[i].Value == null)
								cmd.Parameters[i].Value = DBNull.Value;
						cmd.ExecuteNonQuery();
						user.UserID = (long)prm.Value;
						scope.Complete();
					}
					catch (Exception ex)
					{
						return new Result(ex.Message);
					}
				}
			}
			finally
			{
				DatabaseManager.DatabaseEngine.ReleaseConnection(conn);
			}
			return new Result();
		}
        public Result SaveUser(User user)
        {
            if (OnBeforeUserSaved != null)
            {
                StateChangingEventArgs args = new StateChangingEventArgs();
                OnBeforeUserSaved(user, args);
                if (args.CancelStateChange)
                    return new Result(args.ReasonForCancellation);
            }

            IDbCommand cmd = Database.Main.CreateCommand(user.IsNew ? "CreateUser" : "UpdateUser", CommandType.StoredProcedure);
            Database.Main.AddParameter(cmd, "@UserID", user.UserID);
            Database.Main.AddParameter(cmd, "@ClientID", user.ClientID);
            Database.Main.AddParameter(cmd, "@Username", user.Username);
            Database.Main.AddParameter(cmd, "@PasswordHash", user.PasswordHash);
            Database.Main.AddParameter(cmd, "@FirstName", user.FirstName);
            Database.Main.AddParameter(cmd, "@Surname", user.Surname);
            Database.Main.AddParameter(cmd, "@Email", user.Email);
            Database.Main.AddParameter(cmd, "@Enabled", user.Enabled);
            Database.Main.AddParameter(cmd, "@Hidden", user.Hidden);
            Database.Main.AddParameter(cmd, "@Locked", user.Locked);
            cmd.ExecuteNonQuery();
            bool isNew = user.IsNew;
            user.SetSaved();

            if (OnUserSaved != null)
                OnUserSaved(user, isNew);

            return new Result();
        }