Ejemplo n.º 1
0
        public async Task <UserDto> CreateOrUpdateUserAsync(UserDto user)
        {
            using (MessengerDbContext context = contextFactory.Create())
            {
                User userInfo = await context.Users
                                .Include(opt => opt.UserPublicKeys)
                                .Include(opt => opt.Phones)
                                .Include(opt => opt.Emails)
                                .Include(opt => opt.BlackList)
                                .Include(opt => opt.Tokens)
                                .FirstOrDefaultAsync(opt => opt.Id == user.Id)
                                .ConfigureAwait(false);

                if (userInfo != null)
                {
                    userInfo = UserConverter.GetUser(userInfo, user);
                    context.Update(userInfo);
                }
                else
                {
                    userInfo = UserConverter.GetUser(user);
                    await context.AddAsync(userInfo).ConfigureAwait(false);
                }
                await context.SaveChangesAsync().ConfigureAwait(false);

                return(UserConverter.GetUserDto(userInfo, null, null));
            }
        }
        public async Task <string> AddNewOperationAsync(long nodeId, long userId)
        {
            using (MessengerDbContext context = contextFactory.Create())
            {
                long currentTime          = DateTime.UtcNow.ToUnixTime();
                var  uncomplededOperation = await context.ChangeUserNodeOperations
                                            .FirstOrDefaultAsync(opt => !opt.Completed && opt.UserId == userId && opt.ExpirationTime > currentTime).ConfigureAwait(false);

                if (uncomplededOperation != null)
                {
                    context.Remove(uncomplededOperation);
                }
                ChangeUserNodeOperation operation = new ChangeUserNodeOperation
                {
                    NodeId         = nodeId,
                    UserId         = userId,
                    OperationId    = RandomExtensions.NextString(64),
                    Completed      = false,
                    RequestTime    = currentTime,
                    ExpirationTime = currentTime + (long)TimeSpan.FromDays(1).TotalSeconds
                };
                await context.AddAsync(operation).ConfigureAwait(false);

                await context.SaveChangesAsync().ConfigureAwait(false);

                return(operation.OperationId);
            }
        }
Ejemplo n.º 3
0
        public async Task <ChatVm> NewOrEditChatAsync(ChatVm targetChat)
        {
            if (targetChat == null)
            {
                return(null);
            }

            try
            {
                using (MessengerDbContext context = contextFactory.Create())
                {
                    var query = from chat in context.Chats
                                where chat.Id == targetChat.Id
                                select chat;
                    Chat editableChat = await query.Include(opt => opt.ChatUsers).FirstOrDefaultAsync().ConfigureAwait(false);

                    if (editableChat == null)
                    {
                        editableChat = ChatConverter.GetChat(targetChat);
                        if (targetChat.Users != null)
                        {
                            editableChat.ChatUsers = ChatUserConverter.GetChatUsers(targetChat.Users).ToList();
                        }

                        await context.AddAsync(editableChat).ConfigureAwait(false);
                    }
                    else
                    {
                        editableChat = ChatConverter.GetChat(editableChat, new EditChatVm
                        {
                            About    = targetChat.About,
                            Name     = targetChat.Name,
                            Photo    = targetChat.Photo,
                            Public   = targetChat.Public,
                            Security = targetChat.Security,
                            Visible  = targetChat.Visible
                        });
                        if (!targetChat.Users.IsNullOrEmpty())
                        {
                            editableChat.ChatUsers = ChatUserConverter.GetChatUsers(targetChat.Users);
                        }

                        context.Update(editableChat);
                    }
                    await context.SaveChangesAsync().ConfigureAwait(false);

                    return(ChatConverter.GetChatVm(editableChat));
                }
            }
            catch (DbUpdateException ex)
            {
                Logger.WriteLog(ex);
                return(targetChat);
            }
            catch (Exception ex)
            {
                Logger.WriteLog(ex);
                return(null);
            }
        }
Ejemplo n.º 4
0
        public async Task NewOrEditNodeAsync(NodeVm targetNode)
        {
            try
            {
                using (MessengerDbContext context = contextFactory.Create())
                {
                    var node = await context.Nodes.FindAsync(targetNode.Id).ConfigureAwait(false);

                    if (node == null)
                    {
                        node = NodeConverter.GetNode(targetNode);
                        await context.AddAsync(node).ConfigureAwait(false);
                    }
                    else
                    {
                        node = NodeConverter.GetNode(targetNode);
                        context.Update(node);
                    }
                    await context.SaveChangesAsync().ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLog(ex);
            }
        }
        public async Task <UserChat> Add(UserChat entity)
        {
            var result = await context.AddAsync(entity);

            await context.SaveChangesAsync();

            return(result.Entity);
        }
Ejemplo n.º 6
0
        public async Task <KeyVm> SetNewSymmetricKeyForChat(KeyVm key, long chatId, long userId)
        {
            using (MessengerDbContext context = contextFactory.Create())
            {
                ChatUser chatUser = await context.ChatUsers
                                    .Where(opt => opt.ChatId == chatId &&
                                           opt.UserId == userId &&
                                           opt.UserRole >= UserRole.Admin &&
                                           !opt.Deleted && !opt.Banned)
                                    .FirstOrDefaultAsync()
                                    .ConfigureAwait(false);

                if (chatUser == null)
                {
                    throw new UserIsNotInConversationException();
                }

                Key chatKey = await context.Keys.FirstOrDefaultAsync(opt => opt.ChatId == chatId).ConfigureAwait(false);

                if (chatKey == null)
                {
                    chatKey        = KeyConverter.GetKey(key);
                    chatKey.ChatId = chatId;
                    chatKey.UserId = null;
                    chatKey.KeyId  = RandomExtensions.NextInt64();
                    await context.AddAsync(chatKey).ConfigureAwait(false);
                }
                else
                {
                    chatKey.ChatId  = chatId;
                    chatKey.KeyData = key.Data;
                    chatKey.Version = 1;
                    chatKey.UserId  = null;
                    chatKey.GenerationTimeSeconds = key.GenerationTime;
                    chatKey.ExpirationTimeSeconds = key.GenerationTime + key.Lifetime;
                    context.Update(chatKey);
                }
                await context.SaveChangesAsync().ConfigureAwait(false);

                return(KeyConverter.GetKeyVm(chatKey));
            }
        }
        private async Task HandleNewUserBlockSegmentAsync(BlockSegmentVm segment)
        {
            using (MessengerDbContext _context = CreateContext())
            {
                using (var transaction = await _context.Database.BeginTransactionAsync().ConfigureAwait(false))
                {
                    try
                    {
                        if (!await _context.Users.AnyAsync(user => user.Id == segment.SegmentHeader.ObjectId).ConfigureAwait(false))
                        {
                            if (TryDecryptPrivateData <UserVm>(segment, out var userData))
                            {
                                User user = UserConverter.GetUser(UserConverter.GetUserDto(userData));
                                await _context.Users.AddAsync(user).ConfigureAwait(false);
                            }
                            else
                            {
                                await _context.AddAsync(new User
                                {
                                    Id        = segment.SegmentHeader.ObjectId,
                                    NodeId    = segment.NodeId,
                                    Confirmed = true
                                }).ConfigureAwait(false);
                            }
                            await _context.SaveChangesAsync().ConfigureAwait(false);

                            transaction.Commit();
                        }
                    }
                    catch (Exception ex)
                    {
                        AddErrorMessage(nameof(HandleNewUserBlockSegmentAsync), ex.ToString());
                        transaction.Rollback();
                    }
                }
            }
        }
Ejemplo n.º 8
0
        public async Task <ChatVm> AddUsersToChatAsync(IEnumerable <long> usersId, long chatId, long userId)
        {
            using (MessengerDbContext context = contextFactory.Create())
            {
                using (var transaction = await context.Database.BeginTransactionAsync().ConfigureAwait(false))
                {
                    Chat chat = await context.Chats.FirstOrDefaultAsync(opt => opt.Id == chatId).ConfigureAwait(false);

                    if (chat == null)
                    {
                        throw new ConversationNotFoundException(chatId);
                    }
                    User requestingUser = await context.Users.FindAsync(userId).ConfigureAwait(false);

                    if (requestingUser == null || requestingUser.Deleted)
                    {
                        throw new AddUserChatException();
                    }
                    ChatUser chatUser = await context.ChatUsers
                                        .FirstOrDefaultAsync(opt => opt.ChatId == chatId && opt.UserId == userId).ConfigureAwait(false);

                    List <ChatUserVm> addedUsers = new List <ChatUserVm>();
                    if (chat.Deleted)
                    {
                        throw new ConversationIsNotValidException();
                    }
                    if (chatUser != null && chatUser.Banned)
                    {
                        throw new ChatUserBlockedException();
                    }
                    if (usersId.Count() == 1 && usersId.FirstOrDefault() == userId)
                    {
                        if (chat.Type == (int)ChatType.Private)
                        {
                            throw new AddUserChatException();
                        }
                        if (chatUser == null)
                        {
                            chatUser = ChatUserConverter.GetNewChatUser(chatId, userId, null);
                            await context.AddAsync(chatUser).ConfigureAwait(false);
                        }
                        else if (chatUser.Deleted)
                        {
                            chatUser.Deleted = false;
                            chatUser.User    = requestingUser;
                            context.Update(chatUser);
                        }
                        if (!chat.NodesId.Contains(NodeSettings.Configs.Node.Id))
                        {
                            createMessagesService.DownloadMessageHistoryAsync(chat.NodesId.FirstOrDefault(), chat.Id, ConversationType.Chat, null, false);
                        }
                        chat.NodesId = chat.NodesId.Append(requestingUser.NodeId.Value).Distinct().ToArray();
                        addedUsers.Add(ChatUserConverter.GetChatUserVm(chatUser));
                    }
                    else
                    {
                        if ((chatUser?.Deleted).GetValueOrDefault(true))
                        {
                            throw new AddUserChatException();
                        }

                        if (await loadUsersService.IsUserBlacklisted(userId, usersId).ConfigureAwait(false))
                        {
                            throw new UserBlockedException();
                        }

                        ExpressionStarter <User> usersCondition = PredicateBuilder.New <User>();
                        usersCondition = usersId.Aggregate(usersCondition,
                                                           (current, value) => current.Or(opt => opt.Id == value).Expand());
                        List <User> existingUsers = await context.Users
                                                    .AsNoTracking()
                                                    .Where(usersCondition)
                                                    .ToListAsync()
                                                    .ConfigureAwait(false);

                        ExpressionStarter <ChatUser> chatUsersCondition = PredicateBuilder.New <ChatUser>();
                        chatUsersCondition = existingUsers.Select(opt => opt.Id).Aggregate(chatUsersCondition,
                                                                                           (current, value) => current.Or(opt => opt.UserId == value && opt.ChatId == chatId).Expand());
                        List <ChatUser> validChatUsers = await context.ChatUsers
                                                         .Where(chatUsersCondition)
                                                         .Include(opt => opt.User)
                                                         .ToListAsync()
                                                         .ConfigureAwait(false);

                        foreach (ChatUser user in validChatUsers)
                        {
                            if (!user.Banned && user.Deleted)
                            {
                                user.Deleted = false;
                                addedUsers.Add(ChatUserConverter.GetChatUserVm(user));
                            }
                        }
                        context.UpdateRange(validChatUsers);
                        List <long>     newChatUsersId = existingUsers.Select(opt => opt.Id).Except(validChatUsers.Select(opt => opt.UserId)).ToList();
                        List <ChatUser> newChatUsers   = newChatUsersId.Select(id => ChatUserConverter.GetNewChatUser(chatId, id, userId)).ToList();
                        chat.NodesId = chat.NodesId?.Concat(existingUsers.Select(opt => opt.NodeId.GetValueOrDefault())).Distinct().ToArray()
                                       ?? existingUsers.Select(opt => opt.NodeId.GetValueOrDefault()).Distinct().ToArray();
                        await context.ChatUsers
                        .AddRangeAsync(newChatUsers)
                        .ConfigureAwait(false);

                        /* foreach (ChatUser user in newChatUsers)
                         * {
                         *   user.User = existingUsers.FirstOrDefault(opt => opt.Id == user.UserId);
                         * }*/
                        addedUsers.AddRange(ChatUserConverter.GetChatUsersVm(newChatUsers));
                    }
                    context.Update(chat);
                    transaction.Commit();
                    await context.SaveChangesAsync()
                    .ConfigureAwait(false);

                    ChatVm resultChat = ChatConverter.GetChatVm(chat);
                    resultChat.Users = addedUsers;
                    return(resultChat);
                }
            }
        }
Ejemplo n.º 9
0
        public async Task <NodeKeysDto> CreateNewNodeKeysAsync(long?nodeId, KeyLength keyLength, uint lifetime)
        {
            byte[] password;
            using (SHA256 sha256 = SHA256.Create())
            {
                password = sha256.ComputeHash(Encoding.UTF8.GetBytes(NodeSettings.Configs.Password));
            }
            long keyId = RandomExtensions.NextInt64();

            using (MessengerDbContext context = contextFactory.Create())
            {
                var nodeKeysId = await context.NodesKeys
                                 .Where(opt => opt.NodeId == nodeId)
                                 .Select(opt => opt.KeyId)
                                 .ToListAsync()
                                 .ConfigureAwait(false);

                while (nodeKeysId.Contains(keyId))
                {
                    keyId = RandomExtensions.NextInt64();
                }
                byte[] symmetricKey = Encryptor.GetSymmetricKey(256, keyId, lifetime, password);
                Encryptor.KeyLengthType encKeysLength;
                Encryptor.KeyLengthType signKeysLength;
                switch (keyLength)
                {
                case KeyLength.Short:
                    encKeysLength  = Encryptor.KeyLengthType.EncryptShort;
                    signKeysLength = Encryptor.KeyLengthType.SignShort;
                    break;

                case KeyLength.Medium:
                    encKeysLength  = Encryptor.KeyLengthType.EncryptMedium;
                    signKeysLength = Encryptor.KeyLengthType.SignMedium;
                    break;

                case KeyLength.Long:
                default:
                    encKeysLength  = Encryptor.KeyLengthType.EncryptLong;
                    signKeysLength = Encryptor.KeyLengthType.SignLong;
                    break;
                }
                var      asymKeys       = Encryptor.GenerateAsymmetricKeys(keyId, lifetime, encKeysLength, password);
                var      signAsymKeys   = Encryptor.GenerateAsymmetricKeys(keyId, lifetime, signKeysLength, password);
                long     generationTime = DateTime.UtcNow.ToUnixTime();
                NodeKeys nodeKeys       = new NodeKeys
                {
                    GenerationTime = generationTime,
                    ExpirationTime = generationTime + lifetime,
                    KeyId          = keyId,
                    NodeId         = nodeId.GetValueOrDefault(),
                    PublicKey      = asymKeys.FirstValue,
                    PrivateKey     = asymKeys.SecondValue,
                    SymmetricKey   = symmetricKey,
                    SignPublicKey  = signAsymKeys.FirstValue,
                    SignPrivateKey = signAsymKeys.SecondValue
                };
                await context.AddAsync(nodeKeys).ConfigureAwait(false);

                await context.SaveChangesAsync().ConfigureAwait(false);

                return(new NodeKeysDto
                {
                    ExpirationTime = nodeKeys.ExpirationTime,
                    GenerationTime = nodeKeys.GenerationTime,
                    KeyId = nodeKeys.KeyId,
                    NodeId = nodeKeys.NodeId,
                    PrivateKey = nodeKeys.PrivateKey,
                    PublicKey = nodeKeys.PublicKey,
                    SymmetricKey = nodeKeys.SymmetricKey,
                    SignPublicKey = nodeKeys.SignPublicKey,
                    SignPrivateKey = nodeKeys.SignPrivateKey,
                    Password = password
                });
            }
        }