public GroupRepository(UserManager <GearUser> userManager, TContext context) { _emptyGroupNameResult = GroupResult.Failed(_emptyGroupError); _emptyUserResult = GroupResult.Failed(_emptyUserError); _userManager = userManager; _context = context; }
public GroupResult AddUserToGroup(GearUser user, string groupName) { var validationResult = ValidateUserAndGroupInput(user, groupName); if (!validationResult.Succeeded) { return(validationResult); } var group = _context.AuthGroups.FirstOrDefault(x => x.Name == groupName); if (group == null) { return(GroupResult.Failed(new GroupActionError { Code = "NullGroup", Description = $"The group {groupName} does not exist" })); } else { var alreadyExists = _context.UserGroups .Any(ug => ug.UserId == user.Id && ug.AuthGroupId == group.Id); if (alreadyExists) { return(GroupResult.Failed(new GroupActionError { Code = "AlreadyExists", Description = $"The user: {user.UserName} is already part of '{groupName}' group" })); } var groupUserPair = new UserGroup { UserId = user.Id, AuthGroupId = group.Id }; try { _context.UserGroups.Add(groupUserPair); _context.SaveChanges(); return(GroupResult.Success); } catch (Exception ex) { return(GroupResult.Failed(new GroupActionError { Code = "AddToGroupFail", Description = $"Adding user: {user.UserName} to group {groupName} failed: {ex.Message}" })); } } }
private GroupResult ValidateUserAndGroupInput(GearUser user, string groupName, bool isValidatedAlready = false) { Arg.NotNull(user, nameof(ValidateUserAndGroupInput)); if (isValidatedAlready) { return(GroupResult.Success); } var userProvided = user != null || !string.IsNullOrEmpty(user.Id); var groupNameProvided = !string.IsNullOrEmpty(groupName); if (!userProvided && !groupNameProvided) { return(GroupResult.Failed(_emptyUserError, _emptyGroupError)); } if (!userProvided) { return(_emptyUserResult); } return(!groupNameProvided ? _emptyGroupNameResult : GroupResult.Success); }