예제 #1
0
        public ActionResult AddGroupInvite(GroupItem groupItem, int userID)
        {
            ModelState["Name"].Errors.Clear();
            Group outGroup = GroupManager.GetGroupByID(groupItem.ID, GroupManager.GroupRelatedData.UsersAndGroupInvite);

            if (ModelState.IsValid && !UsersToGroupManager.IsMember(groupItem.GroupInviteUserMail, groupItem.ID))
            {
                GroupInvite groupInvite = new GroupInvite();
                groupInvite.GroupID  = groupItem.ID;
                groupInvite.UserMail = groupItem.GroupInviteUserMail;

                string url = Utils.AppUtils.AppDomainPath + ((UserManager.GetByUsername(groupItem.GroupInviteUserMail) != null) ? "User/Login" : "User/Register");

                GroupInviteManager.Add(groupInvite);
                Utils.NotificationManager.SendEmail(//string.Format("{0} {1}", outGroup.User.FirstName, outGroup.User.LastName),
                    Core.SessionManager.UserFullName,
                    //outGroup.User.UserName,
                    User.Identity.Name,
                    groupInvite.UserMail,
                    App_GlobalResources.Mail.Subject,
                    string.Format(App_GlobalResources.Mail.Body, outGroup.User.FirstName, url));

                return(RedirectToAction("GroupDetails", new { id = groupItem.ID }));
            }

            GroupItem outGroupitem = outGroup.ToGroupItem();

            outGroupitem.GroupInviteUserMail = groupItem.GroupInviteUserMail;
            ModelState.AddModelError("GroupInviteUserMail", App_GlobalResources.Common.UserIsInviteGroup);
            return(View("GroupDetails", outGroupitem));
        }
        public async Task Invalidate_when_invite_is_for_other_user()
        {
            var sut = new AcceptGroupInviteValidator(_dbContext);

            // Arrange
            string userSub = Guid.NewGuid().ToString();
            var    user    = new DeUrgenta.Domain.Entities.User
            {
                FirstName = "user",
                LastName  = "user",
                Sub       = userSub
            };

            string otherUserSub = Guid.NewGuid().ToString();
            var    otherUser    = new DeUrgenta.Domain.Entities.User
            {
                FirstName = "other",
                LastName  = "user",
                Sub       = otherUserSub
            };

            string adminSub = Guid.NewGuid().ToString();
            var    admin    = new DeUrgenta.Domain.Entities.User
            {
                FirstName = "Admin",
                LastName  = "Test",
                Sub       = adminSub
            };

            await _dbContext.Users.AddAsync(user);

            await _dbContext.Users.AddAsync(admin);

            await _dbContext.Users.AddAsync(otherUser);

            var group = new Group
            {
                Admin = admin,
                Name  = "group"
            };

            await _dbContext.Groups.AddAsync(group);

            var groupInvite = new GroupInvite
            {
                InvitationReceiver = user,
                InvitationSender   = admin,
                Group = group
            };

            await _dbContext.GroupInvites.AddAsync(groupInvite);

            await _dbContext.SaveChangesAsync();

            // Act
            bool isValid = await sut.IsValidAsync(new AcceptGroupInvite(userSub, Guid.NewGuid()));

            // Assert
            isValid.ShouldBeFalse();
        }
        public async Task <RepositoryActionResult <GroupInvite> > AddInviteAsync(GroupInvite invite)
        {
            var sender = await _context.Users.FirstOrDefaultAsync(u => u.Id == invite.SenderId);

            var invited = await _context.Users.FirstOrDefaultAsync(u => u.Id == invite.InvitedId);

            var group = await _context.Groups.FirstOrDefaultAsync(e => e.GroupId == invite.GroupId);

            if (sender == null || invited == null || group == null)
            {
                return(new RepositoryActionResult <GroupInvite>(invite, RepositoryStatus.NotFound));
            }

            var existingInvite = await _context.GroupInvites.FirstOrDefaultAsync(
                i => i.GroupId == invite.GroupId && i.InvitedId == invite.InvitedId);

            if (existingInvite != null)
            {
                return(new RepositoryActionResult <GroupInvite>(existingInvite, RepositoryStatus.BadRequest));
            }

            try
            {
                var result = _context.GroupInvites.Add(invite);
                await _context.SaveChangesAsync();

                return(new RepositoryActionResult <GroupInvite>(result, RepositoryStatus.Created));
            }
            catch (Exception e)
            {
                return(new RepositoryActionResult <GroupInvite>(invite, RepositoryStatus.Error));
            }
        }
        public async Task <IActionResult> InviteToGroup(string email)
        {
            var validemail = validUser(email);


            if (validemail == true)
            {
                AspNetUsers found  = _context.AspNetUsers.Where(x => x.Email == email).First();
                bool        member = inGroup(found.Id, (Guid)TempData["groupId"]);
                if (member == false)
                {
                    GroupInvite newinvite = new GroupInvite();
                    var         tempUser  = await _context.AspNetUsers.Where(x => x.Email == email).FirstAsync();

                    newinvite.UserId  = tempUser.Id;
                    newinvite.GroupId = (Guid)TempData["groupId"];
                    await _context.GroupInvite.AddAsync(newinvite);

                    await _context.SaveChangesAsync();

                    return(RedirectToAction("ListGroups"));
                }
                else
                {
                    TempData["inGroup"] = true;
                    return(RedirectToAction("InviteToGroup", TempData["groupId"]));
                }
            }
            else
            {
                TempData["exists"] = true;
                return(RedirectToAction("InviteToGroup", TempData["groupId"]));
            }
        }
예제 #5
0
        private String checkValid(GroupInvite gi, String code)
        {
            if (gi == null)
            {
                return("邀请不存在");
            }

            if (gi.Code.Equals(code) == false)
            {
                return("邀请不存在");
            }

            if (ctx.viewer.Id != gi.Receiver.Id)
            {
                return("邀请不存在");
            }

            Group group = Group.findById(gi.OwnerId);

            if (group == null)
            {
                return("邀请不存在");
            }

            if (gi.Status == 1)
            {
                return("邀请不存在");                // 邀请只能用一次。比如:受邀用户捣乱,管理员将其删除。此用户不能再利用旧的邀请码直接进入。
            }
            if (mgrService.IsGroupMember(ctx.viewer.Id, group.Id))
            {
                return("您已经是成员");
            }

            return(null);
        }
예제 #6
0
        public void Invite(int id)
        {
            String code = ctx.Get("code");

            GroupInvite gi = GroupInvite.findById(id);

            String errorInfo = checkValid(gi, code);

            if (strUtil.HasText(errorInfo))
            {
                echoError(errorInfo);
                return;
            }

            // 创建用户成员
            Group  group  = Group.findById(gi.OwnerId);
            Result result = mgrService.JoinGroupDone((User)ctx.viewer.obj, group, "接受" + gi.Inviter.Name + "邀请加入", ctx.Ip);

            if (result.IsValid)
            {
                // 修改邀请码状态
                gi.Status = 1;
                gi.update();

                echoRedirect(lang("opok"), Link.ToMember(group));
            }
            else
            {
                echoError(result);
            }
        }
 List <GroupInvite> IGroupInvitesInterface.this[UGUI requestingAgent, UGI group, UUID roleID, UGUI principal]
 {
     get
     {
         using (var conn = new SqlConnection(m_ConnectionString))
         {
             conn.Open();
             using (var cmd = new SqlCommand("SELECT * from groupinvites WHERE PrincipalID = @principalid AND GroupID = @groupid AND RoleID = @roleid", conn))
             {
                 cmd.Parameters.AddParameter("@principalid", principal.ID);
                 cmd.Parameters.AddParameter("@roleid", roleID);
                 cmd.Parameters.AddParameter("@groupid", group.ID);
                 using (SqlDataReader reader = cmd.ExecuteReader())
                 {
                     var invites = new List <GroupInvite>();
                     while (reader.Read())
                     {
                         GroupInvite invite = reader.ToGroupInvite();
                         invite.Principal = ResolveName(invite.Principal);
                         invite.Group     = ResolveName(requestingAgent, invite.Group);
                         invites.Add(invite);
                     }
                     return(invites);
                 }
             }
         }
     }
 }
예제 #8
0
        public static string buildGroupInviteMessage(Group group, GroupInvite invite, GXUser user, string url)
        {
            if (group == null)
            {
                return("");
            }
            if (invite == null)
            {
                return("");
            }
            if (user == null)
            {
                return("");
            }

            var sb = new StringBuilder();

            sb.AppendFormat("<p>{0}</p>", buildGroupInviteSubject(group, invite, user));

            sb.Append("<hr />");

            sb.AppendFormat("<div>{0}</div>", invite.message);

            var acceptUrl = url + "/acceptinvite/" + invite.guid.ToString();

            sb.AppendFormat("<p><a href=\"{0}\">{1}</a></p>", acceptUrl, "Click here to join this group");

            return(sb.ToString());
        }
예제 #9
0
        public async Task <GroupInviteId> Handle(AddGroupInviteCommand request,
                                                 CancellationToken cancellationToken)
        {
            var group = await _groupRepository.GetByIdAsNoTrackingAsync(request.GroupId, cancellationToken);

            if (group.OwnerId != request.InviterId)
            {
                throw new ApiException("Only owner can invite users to a group.", StatusCodes.Status403Forbidden);
            }

            if (group.UserGroups.Any(x => x.AppUserId == request.InvitedAppUserId))
            {
                throw new ApiException("User is already in a group", StatusCodes.Status409Conflict);
            }

            IdGenerator idGenerator = new IdGenerator(IdGeneratorType.GroupInvite);
            var         groupInvite = new GroupInvite
            {
                Id = new GroupInviteId(idGenerator.CreateId()),
                InvitingAppUserId = request.InviterId,
                InvitedAppUserId  = request.InvitedAppUserId,
                IsAccepted        = false,
                IsPending         = true,
                DateAdded         = DateTimeOffset.Now,
                GroupId           = request.GroupId
            };

            await _groupInviteRepository.AddAsync(groupInvite, cancellationToken);

            await _unitOfWork.SaveAsync(cancellationToken);

            return(groupInvite.Id);
        }
예제 #10
0
        public async Task AcceptInviteAsync_ShouldDeleteInvitesFromDatabase_AndChangeCharacterGroupId()
        {
            const int groupId          = 42;
            const int characterId      = 24;
            var       character        = new Character();
            var       executionContext = new NaheulbookExecutionContext();
            var       groupInvite      = new GroupInvite {
                GroupId = groupId, Character = character
            };
            var otherGroupInvite = new GroupInvite {
                GroupId = groupId, Character = character
            };
            var groupInvites = new List <GroupInvite> {
                groupInvite, otherGroupInvite
            };

            _unitOfWorkFactory.GetUnitOfWork().GroupInvites.GetByCharacterIdAndGroupIdWithGroupWithCharacterAsync(groupId, characterId)
            .Returns(groupInvite);
            _unitOfWorkFactory.GetUnitOfWork().GroupInvites.GetInvitesByCharacterIdAsync(characterId)
            .Returns(groupInvites);
            _unitOfWorkFactory.GetUnitOfWork().When(x => x.SaveChangesAsync())
            .Do(_ => character.GroupId.Should().Be(groupId));

            await _service.AcceptInviteAsync(executionContext, groupId, characterId);

            Received.InOrder(() =>
            {
                _unitOfWorkFactory.GetUnitOfWork().GroupInvites.RemoveRange(groupInvites);
                _unitOfWorkFactory.GetUnitOfWork().SaveChangesAsync();
            });
        }
예제 #11
0
 public GroupInvite(GroupInvite src)
 {
     ID        = src.ID;
     Group     = new UGI(src.Group);
     RoleID    = src.RoleID;
     Principal = new UGUI(src.Principal);
     Timestamp = new Date(src.Timestamp);
 }
예제 #12
0
 public async Task <bool> CreateInvite(GroupInvite invite)
 {
     using (var conn = await _db.GetSqlConnection())
     {
         return(await conn.ExecuteAsync(@"
             INSERT INTO `UserGroupRequests`(User_Id, Group_Id, Inviter_Id) VALUES(@User_Id, @Group_Id, @Inviter_Id);",
                                        invite) > 0);
     }
 }
예제 #13
0
        public async Task <BaseResponse> Invite([FromBody] GroupInviteRequest request)
        {
            var currentUserId = HttpContext.User.GetUserId();
            var response      = new BaseResponse();

            if (request == null || !ModelState.IsValid)
            {
                HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
                response.Message = "Invalid input(s).";
                return(response);
            }

            try
            {
                if (!await _groupsRepository.UserInGroup(currentUserId, request.Group_Id))
                {
                    HttpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
                    response.Message = "User is not authorized to invite to this group.";
                    return(response);
                }
            }
            catch
            {
                HttpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
                response.Message = "Failed to authorize invite rights.";
                return(response);
            }

            var invite = new GroupInvite
            {
                Group_Id   = request.Group_Id,
                User_Id    = currentUserId,
                Inviter_Id = request.Inviter_Id
            };

            try
            {
                if (await _groupsRepository.CreateInvite(invite))
                {
                    response.Success = true;
                    response.Message = "User successfully invited to group!";
                }
                else
                {
                    throw new Exception();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                HttpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
                response.Message = "Failed to create invite.";
            }

            return(response);
        }
예제 #14
0
        public async Task Invalidate_when_user_is_already_invited()
        {
            // Arrange
            var sut = new InviteToGroupValidator(_dbContext);

            string userSub         = Guid.NewGuid().ToString();
            string nonGroupUserSub = Guid.NewGuid().ToString();

            var admin = new User
            {
                FirstName = "Integration",
                LastName  = "Test",
                Sub       = userSub
            };

            var invitedGroupUser = new User
            {
                FirstName = "Integration2",
                LastName  = "Test2",
                Sub       = nonGroupUserSub
            };

            var group = new Domain.Entities.Group
            {
                Admin = admin,
                Name  = "my group"
            };

            var userToGroups = new UserToGroup {
                Group = group, User = admin
            };
            var groupInvite = new GroupInvite
            {
                Group = group,
                InvitationReceiver = invitedGroupUser,
                InvitationSender   = admin
            };

            await _dbContext.Users.AddAsync(admin);

            await _dbContext.Users.AddAsync(invitedGroupUser);

            await _dbContext.Groups.AddAsync(group);

            await _dbContext.UsersToGroups.AddAsync(userToGroups);

            await _dbContext.GroupInvites.AddAsync(groupInvite);

            await _dbContext.SaveChangesAsync();

            // Act
            bool isValid = await sut.IsValidAsync(new InviteToGroup(userSub, group.Id, invitedGroupUser.Id));

            // Assert
            isValid.ShouldBeFalse();
        }
예제 #15
0
 public static bool ValidateGroupInvite(GroupInvite groupInvite)
 {
     if (groupInvite.ExpiryDate < DateTime.Now)
     {
         return(false);
     }
     else
     {
         return(true);
     }
 }
        public TestDataUtil AddGroupInvite(Character character, Group group, bool fromGroup)
        {
            var groupInvite = new GroupInvite
            {
                FromGroup   = fromGroup,
                Character   = character,
                CharacterId = character.Id,
                Group       = group,
                GroupId     = group.Id
            };

            return(SaveEntity(groupInvite, null));
        }
예제 #17
0
 void IGroupInvitesInterface.Add(UGUI requestingAgent, GroupInvite invite)
 {
     m_GroupInvitesToGroup.Add(invite.ID, invite.Group.ID);
     try
     {
         m_Groups[invite.Group.ID].Invites.Add(invite.ID, new GroupInvite(invite));
     }
     catch
     {
         m_GroupInvitesToGroup.Remove(invite.ID);
         throw;
     }
 }
예제 #18
0
        public async Task <GroupInvite> CreateInviteAsync(NaheulbookExecutionContext executionContext, int groupId, CreateInviteRequest request)
        {
            using (var uow = _unitOfWorkFactory.CreateUnitOfWork())
            {
                var group = await uow.Groups.GetAsync(groupId);

                if (group == null)
                {
                    throw new GroupNotFoundException(groupId);
                }

                var character = await uow.Characters.GetWithOriginWithJobsAsync(request.CharacterId);

                if (character == null)
                {
                    throw new CharacterNotFoundException(request.CharacterId);
                }

                if (character.GroupId != null)
                {
                    throw new CharacterAlreadyInAGroupException(request.CharacterId);
                }

                if (request.FromGroup)
                {
                    _authorizationUtil.EnsureIsGroupOwner(executionContext, group);
                }
                else
                {
                    _authorizationUtil.EnsureIsCharacterOwner(executionContext, character);
                }

                var groupInvite = new GroupInvite
                {
                    Character = character,
                    Group     = group,
                    FromGroup = request.FromGroup,
                };

                uow.GroupInvites.Add(groupInvite);

                await uow.SaveChangesAsync();

                var session = _notificationSessionFactory.CreateSession();
                session.NotifyCharacterGroupInvite(request.CharacterId, groupInvite);
                session.NotifyGroupCharacterInvite(groupId, groupInvite);
                await session.CommitAsync();

                return(groupInvite);
            }
        }
예제 #19
0
        public async Task <Guid> CreateInviteAsync(GroupInviteViewModel model, CancellationToken cancellationToken)
        {
            var invite = new GroupInvite()
            {
                EmailAddress = model.EmailAddress,
                GroupId      = model.GroupId,
                IsDeleted    = model.IsDeleted
            };

            _context.GroupInvite.Add(invite);
            await _context.SaveChangesAsync(cancellationToken);

            return(invite.Id);
        }
예제 #20
0
        public async Task Validate_when_an_invite_exists()
        {
            var sut = new RejectGroupInviteValidator(_dbContext);

            // Arrange
            string userSub = Guid.NewGuid().ToString();
            var    user    = new DeUrgenta.Domain.Entities.User
            {
                FirstName = "Integration",
                LastName  = "Test",
                Sub       = userSub
            };

            string adminSub = Guid.NewGuid().ToString();
            var    admin    = new DeUrgenta.Domain.Entities.User
            {
                FirstName = "Admin",
                LastName  = "Test",
                Sub       = adminSub
            };

            await _dbContext.Users.AddAsync(user);

            await _dbContext.Users.AddAsync(admin);

            var group = new Group
            {
                Admin = admin,
                Name  = "group"
            };

            var groupInvite = new GroupInvite
            {
                InvitationReceiver = user,
                InvitationSender   = admin,
                Group = group
            };
            await _dbContext.GroupInvites.AddAsync(groupInvite);

            await _dbContext.Groups.AddAsync(group);

            await _dbContext.SaveChangesAsync();

            // Act
            bool isValid = await sut.IsValidAsync(new RejectGroupInvite(userSub, groupInvite.Id));

            // Assert
            isValid.ShouldBeTrue();
        }
예제 #21
0
        public static string buildGroupInviteSubject(Group group, GroupInvite invite, GXUser user)
        {
            if (group == null)
            {
                return("");
            }
            if (invite == null)
            {
                return("");
            }
            if (user == null)
            {
                return("");
            }

            var sb = new StringBuilder();

            if (!string.IsNullOrEmpty(user.lastName) & !string.IsNullOrEmpty(user.firstName))
            {
                sb.AppendFormat("{0} {1}", user.firstName, user.lastName);
            }
            else
            {
                sb.AppendFormat("{0}", user.Email);
            }

            sb.AppendFormat(" has invited you to to ");
            switch (user.gender)
            {
            case "":
                sb.Append("their");
                break;

            case "m":
                sb.Append("his");
                break;

            case "f":
                sb.Append("her");
                break;

            default:
                sb.Append("their");
                break;
            }
            sb.AppendFormat(" group {0} on Gift Exchange", group.name);

            return(sb.ToString());
        }
예제 #22
0
        bool IGroupInvitesInterface.TryGetValue(UGUI requestingAgent, UUID groupInviteID, out GroupInvite ginvite)
        {
            MemoryGroupInfo grpInfo;
            GroupInvite     intInvite;
            UUID            groupID;

            if (m_GroupInvitesToGroup.TryGetValue(groupInviteID, out groupID) &&
                m_Groups.TryGetValue(groupID, out grpInfo) &&
                grpInfo.Invites.TryGetValue(groupInviteID, out intInvite))
            {
                ginvite = new GroupInvite(intInvite);
                return(true);
            }
            ginvite = null;
            return(false);
        }
예제 #23
0
        public async Task DeleteInviteAsync_ShouldDeleteInvite_ThenReturnInviteResponse()
        {
            const int characterId = 12;
            const int groupId     = 8;
            var       groupInvite = new GroupInvite();
            var       response    = new DeleteInviteResponse();

            _groupService.CancelOrRejectInviteAsync(_executionContext, groupId, characterId)
            .Returns(groupInvite);
            _mapper.Map <DeleteInviteResponse>(groupInvite)
            .Returns(response);

            var result = await _controller.DeleteInviteAsync(_executionContext, groupId, characterId);

            result.Value.Should().BeSameAs(response);
        }
예제 #24
0
        public void CancelOrRejectInviteAsync_ShouldEnsureUserCanDeleteGroupInvite()
        {
            const int groupId          = 42;
            const int characterId      = 24;
            var       executionContext = new NaheulbookExecutionContext();
            var       groupInvite      = new GroupInvite();

            _unitOfWorkFactory.GetUnitOfWork().GroupInvites.GetByCharacterIdAndGroupIdWithGroupWithCharacterAsync(groupId, characterId)
            .Returns(groupInvite);
            _authorizationUtil.When(x => x.EnsureCanDeleteGroupInvite(executionContext, groupInvite))
            .Throw(new TestException());

            Func <Task> act = () => _service.CancelOrRejectInviteAsync(executionContext, groupId, characterId);

            act.Should().Throw <TestException>();
        }
예제 #25
0
        public async static Task <TaskResult> AddInvite(Group group, User user, User target)
        {
            // Validate arguments
            TaskResult validate = await TargetedCommandValidate(group, user, target, "addinvite");

            if (!validate.Succeeded)
            {
                return(validate);
            }

            using (VooperContext context = new VooperContext(VooperContext.DBOptions))
            {
                if (await context.GroupInvites.AnyAsync(x => x.User_Id == target.Id && x.Group_Id == group.Id))
                {
                    return(new TaskResult(false, $"Error: That user is already invited!"));
                }

                GroupInvite invite = new GroupInvite()
                {
                    Id       = Guid.NewGuid().ToString(),
                    Group_Id = group.Id,
                    User_Id  = target.Id
                };

                await context.GroupInvites.AddAsync(invite);

                // Send a notification
                Notification notification = new Notification()
                {
                    NotificationID = Guid.NewGuid().ToString(),
                    Author         = user.Id,
                    Content        = $"Click above to see and join the group!",
                    Source         = 0,
                    Linkback       = $"https://spookvooper.com/Group/View?groupid={group.Id}",
                    Target         = target.Id,
                    TimeSent       = DateTime.UtcNow,
                    Title          = $"You were invited to {group.Name}!",
                    Type           = "Group Invite"
                };

                await context.Notifications.AddAsync(notification);

                await context.SaveChangesAsync();

                return(new TaskResult(true, $"Invited {target.UserName} to {group.Name}."));
            }
        }
        void IGroupInvitesInterface.Add(UGUI requestingAgent, GroupInvite invite)
        {
            var vals = new Dictionary <string, object>
            {
                ["InviteID"]    = invite.ID,
                ["GroupID"]     = invite.Group.ID,
                ["RoleID"]      = invite.RoleID,
                ["PrincipalID"] = invite.Principal.ID,
                ["Timestamp"]   = invite.Timestamp
            };

            using (var conn = new SqlConnection(m_ConnectionString))
            {
                conn.Open();
                conn.InsertInto("groupinvites", vals);
            }
        }
예제 #27
0
        public async Task PostCreateInviteAsync_ShouldCreateInvite_ThenReturnInviteResponse()
        {
            const int groupId             = 8;
            var       createInviteRequest = new CreateInviteRequest();
            var       createdInvite       = new GroupInvite();
            var       groupInviteResponse = new GroupInviteResponse();

            _groupService.CreateInviteAsync(_executionContext, groupId, createInviteRequest)
            .Returns(createdInvite);
            _mapper.Map <GroupInviteResponse>(createdInvite)
            .Returns(groupInviteResponse);

            var result = await _controller.PostCreateInviteAsync(_executionContext, groupId, createInviteRequest);

            result.Value.Should().BeSameAs(groupInviteResponse);
            result.StatusCode.Should().Be(StatusCodes.Status201Created);
        }
        public async Task <RepositoryActionResult <GroupInvite> > AddInviteEmailAsync(int groupId, string senderId, string email)
        {
            var sender = await _context.Users.FirstOrDefaultAsync(u => u.Id == senderId);

            var invited = await _context.Users.FirstOrDefaultAsync(u => u.Email == email);

            var group = await _context.Groups.FirstOrDefaultAsync(e => e.GroupId == groupId);

            if (sender == null || invited == null || group == null)
            {
                return(new RepositoryActionResult <GroupInvite>(null, RepositoryStatus.NotFound));
            }

            var existingInvite = await _context.GroupInvites.FirstOrDefaultAsync(
                i => i.GroupId == groupId && i.Invited.Email == email);

            if (existingInvite != null)
            {
                return(new RepositoryActionResult <GroupInvite>(existingInvite, RepositoryStatus.BadRequest));
            }

            try
            {
                var invite = new GroupInvite {
                    GroupId = groupId, SenderId = senderId, InvitedId = invited.Id
                };
                var result = _context.GroupInvites.Add(invite);
                await _context.SaveChangesAsync();

                return(new RepositoryActionResult <GroupInvite>(result, RepositoryStatus.Created));
            }
            catch (Exception e)
            {
                var ex = new ExceptionWrapper
                {
                    ExceptionMessage    = e.Message,
                    ExceptionStackTrace = e.StackTrace,
                    LogTime             = DateTime.Now
                };
                _context.Exception.Add(ex);
                await _context.SaveChangesAsync();

                return(new RepositoryActionResult <GroupInvite>(null, RepositoryStatus.Error));
            }
        }
예제 #29
0
        public async Task CancelOrRejectInviteAsync_ShouldDeleteInviteFromDatabase()
        {
            const int groupId          = 42;
            const int characterId      = 24;
            var       executionContext = new NaheulbookExecutionContext();
            var       groupInvite      = new GroupInvite();

            _unitOfWorkFactory.GetUnitOfWork().GroupInvites.GetByCharacterIdAndGroupIdWithGroupWithCharacterAsync(groupId, characterId)
            .Returns(groupInvite);

            await _service.CancelOrRejectInviteAsync(executionContext, groupId, characterId);

            Received.InOrder(() =>
            {
                _unitOfWorkFactory.GetUnitOfWork().GroupInvites.Remove(groupInvite);
                _unitOfWorkFactory.GetUnitOfWork().SaveChangesAsync();
            });
        }
예제 #30
0
        public void AcceptInviteAsync_ShouldThrowIfCharacterIsAlreadyInAGroup()
        {
            const int groupId     = 42;
            const int characterId = 24;
            var       character   = new Character {
                GroupId = 8
            };
            var groupInvite = new GroupInvite {
                GroupId = groupId, Character = character
            };

            _unitOfWorkFactory.GetUnitOfWork().GroupInvites.GetByCharacterIdAndGroupIdWithGroupWithCharacterAsync(groupId, characterId)
            .Returns(groupInvite);

            Func <Task> act = () => _service.AcceptInviteAsync(new NaheulbookExecutionContext(), groupId, characterId);

            act.Should().Throw <CharacterAlreadyInAGroupException>();
        }
예제 #31
0
        public virtual Result Invite( User inviter, String receiver, Group group, String msg, String inviteUrl )
        {
            Result result = this.getReceivers( receiver, group.Id );
            if (result.HasErrors) {
                return result;
            }

            List<User> users = result.Info as List<User>;

            foreach (User user in users) {

                GroupInvite g = new GroupInvite();
                g.Receiver = user;
                g.Inviter = inviter;

                g.OwnerId = group.Id;
                g.Msg = msg;
                g.Code = Guid.NewGuid().ToString();

                g.insert();

                //-----------send msg--------------------

                String lnkInvite = inviteUrl.Replace( "999", g.Id.ToString() ) + "?code=" + g.Code;

                String msgTitle = inviter.Name + " 诚邀您加入群组";

                String msgBody = string.Format( "<a href=\"{1}\" target=\"_blank\">{0}</a> 诚邀您加入群组 “{2}”, <a href=\"{3}\" target=\"_blank\">请点击此处接受邀请</a>。 ", inviter.Name, Link.ToMember( inviter ), group.Name, lnkInvite );
                msgBody += "<br/><br/>邀请信息:" + g.Msg;

                msgService.SendMsg( inviter, user.Name, msgTitle, msgBody );

            }

            return new Result();
        }
예제 #32
0
        private String checkValid( GroupInvite gi, String code )
        {
            if (gi == null) return "邀请不存在";

            if (gi.Code.Equals( code ) == false) return "邀请不存在";

            if (ctx.viewer.Id != gi.Receiver.Id) return "邀请不存在";

            Group group = Group.findById( gi.OwnerId );
            if (group == null) return "邀请不存在";

            if (gi.Status == 1) return "邀请不存在"; // 邀请只能用一次。比如:受邀用户捣乱,管理员将其删除。此用户不能再利用旧的邀请码直接进入。

            if (mgrService.IsGroupMember( ctx.viewer.Id, group.Id )) return "您已经是成员";

            return null;
        }