Exemplo n.º 1
0
        public async Task <IActionResult> PrivateChat(int user1Id, int user2Id)
        {
            var users = new List <int> {
                user1Id, user2Id
            };
            var privChat = await _context.PrivateChats
                           .Include(x => x.User1)
                           .Include(x => x.User2)
                           .Include(x => x.Chat)
                           .FirstOrDefaultAsync(x => users.Contains(x.User1.Id) && users.Contains(x.User2.Id));

            if (privChat is null)
            {
                var chat = new Chat()
                {
                    ChatName = (await _context.Users.FindAsync(user1Id)).NickName +
                               "-" + (await _context.Users.FindAsync(user2Id)).NickName
                };

                privChat = new PrivateChat()
                {
                    Chat  = chat,
                    User1 = await _context.Users.FindAsync(user1Id),
                    User2 = await _context.Users.FindAsync(user2Id)
                };

                await _context.Chats.AddAsync(chat);

                await _context.PrivateChats.AddAsync(privChat);

                await _context.SaveChangesAsync();
            }

            return(RedirectToAction("Chat", "Chat", new { chatId = privChat.Chat.Id }));
        }
Exemplo n.º 2
0
        public async Task GetById_ShouldSuccess()
        {
            var client = this.factory.CreateClient();

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
                "Bearer",
                await AuthenticationUtilities.GetTestUserAccessTokenAsync(client));

            MessengerContext context = this.factory.Server.Host.Services.GetService(typeof(MessengerContext))
                                       as MessengerContext;

            await context.Users.AddRangeAsync(this.GenerateUsers(5));

            await context.SaveChangesAsync();

            var dbUser = await context.Users.Skip(2).FirstAsync();

            var response = await client.GetAsync($"/api/users/{dbUser.Id}");

            response.EnsureSuccessStatusCode();

            var user = response.Content.ReadAsAsync(typeof(UserViewModel)).Result as UserViewModel;

            Assert.NotNull(user);
            Assert.Equal(dbUser.UserName, user.UserName);
        }
Exemplo n.º 3
0
        public async Task <IActionResult> Create(Message message)
        {
            if (ModelState.IsValid)
            {
                message.UserName = User.Identity.Name;
                var sender = await _userManager.GetUserAsync(User);

                message.UserID = sender.Id;
                await _context.Messages.AddAsync(message);

                await _context.SaveChangesAsync();

                return(RedirectToAction("ChatHome"));
            }
            return(Error());
        }
Exemplo n.º 4
0
        public async Task Delete_ShouldSuccess()
        {
            var client = this.factory.CreateClient();

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
                "Bearer",
                await AuthenticationUtilities.GetTestUserAccessTokenAsync(client));

            MessengerContext context = this.factory.Server.Host.Services.GetService(typeof(MessengerContext))
                                       as MessengerContext;

            await context.Users.AddRangeAsync(this.GenerateUsers(5));

            await context.SaveChangesAsync();

            var dbUser = await context.Users.Skip(2).FirstAsync();

            int previousCount = await context.Users.CountAsync();

            var response = await client.DeleteAsync($"/api/users/{dbUser.Id}");

            response.EnsureSuccessStatusCode();

            int currentCount = await context.Users.CountAsync();

            Assert.NotEqual(previousCount, currentCount);
            Assert.Equal(previousCount, currentCount + 1);
            Assert.False(await context.Users.AnyAsync(x => x.Id == dbUser.Id));
        }
Exemplo n.º 5
0
        /// <summary>
        /// Load conversation between '_activeUser' and '_receiver' if exists, create new otherwise.
        /// </summary>
        /// <returns>Void</returns>
        private async Task LoadConversation()
        {
            using (var _db = new MessengerContext())
            {
                // Attaching users to this context
                _db.Users.Attach(_activeUser);
                _db.Users.Attach(_receiver);

                // Find conversation between these two users if one already exists
                var _conversationsMatch = await _db.Conversations
                                          .Where(c => c.FirstUser.UserId == _activeUser.UserId || c.FirstUser.UserId == _receiver.UserId)
                                          .Where(c => c.SecondUser.UserId == _activeUser.UserId || c.SecondUser.UserId == _receiver.UserId)
                                          .Include(x => x.Messages)
                                          .SingleOrDefaultAsync();

                if (_conversationsMatch != null)
                {
                    _conversation = _conversationsMatch;
                    return;
                }

                // Only runs when Conversation does not exists
                var _newConversation = new Conversation
                {
                    FirstUser  = _activeUser,
                    SecondUser = _receiver,
                    Messages   = new List <Message>()
                };

                _conversation = _newConversation;

                _db.Conversations.AddOrUpdate(_newConversation);
                await _db.SaveChangesAsync();
            }
        }
Exemplo n.º 6
0
        // Handles the click event on 'sendBtn'
        private async void SendButton_Click(object sender, EventArgs e)
        {
            // Display sent message first
            var _msgText       = messageTextBox.Text;
            var _messageBubble = new MessageBubble(_activeUser, MessageType.Outgoing, _msgText);

            messageFlowLayoutPanel.Controls.Add(_messageBubble);
            messageTextBox.Clear();

            // Save message to database
            using (var _db = new MessengerContext())
            {
                _db.Users.Attach(_activeUser);
                _db.Conversations.Attach(_conversation);

                var _message = new Message()
                {
                    Sender = _activeUser,
                    Text   = _msgText
                };

                _conversation.Messages.Add(_message);

                // Assign updated Message list to object in db
                var _dbMessages = await _db.Conversations.FirstAsync(x => x.ConversationId == _conversation.ConversationId);

                _dbMessages.Messages = _conversation.Messages;

                await _db.SaveChangesAsync();
            }
        }
Exemplo n.º 7
0
        // Handles the click event on 'registerUserBtn'
        private async void RegisterUserBtn_Click(object sender, EventArgs e)
        {
            // Check if input is not empty
            if (textUsername.Text == String.Empty || textPassword.Text == String.Empty)
            {
                MessageBox.Show("Invalid username or password.\n\nPlease try again with valid inputs.", "Invalid Arguments", MessageBoxButtons.OK, MessageBoxIcon.Error);
                textUsername.Clear();
                textPassword.Clear();
                textPasswordCheck.Clear();
                return;
            }

            // Check if retyped password is correct
            if (textPassword.Text != textPasswordCheck.Text)
            {
                MessageBox.Show("Passwords do not match!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                textPassword.Clear();
                textPasswordCheck.Clear();
                return;
            }

            var _username = textUsername.Text;
            var _pass     = textPassword.Text;

            // Compute hashed pass
            var _hashedPass = Encoding.ASCII.GetString(_md5Crypto.ComputeHash(Encoding.ASCII.GetBytes(_pass)));

            // Check if username is available
            if (await CheckUsernameAvailability(_username))
            {
                using (var _dbContext = new MessengerContext())
                {
                    var _newUser = new User()
                    {
                        Username = _username,
                        Password = _hashedPass
                    };

                    _dbContext.Users.AddOrUpdate(_newUser);
                    await _dbContext.SaveChangesAsync();
                }

                MessageBox.Show($"Well done! {_username.ToUpper()} was registered successfully.", "Success",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
                _mainForm.OpenChildForm(new LoginForm(_mainForm));

                Console.WriteLine($"DEBUG:\nusername: {_username} password: {_pass} hash: {_hashedPass}");
            }

            // Username is NOT available
            else
            {
                MessageBox.Show($"Sorry, but {_username} is already taken!", "Invalid Username", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                textUsername.Clear();
                textPassword.Clear();
                textPasswordCheck.Clear();
            }
        }
        private async void SeedDataForMessagesTesting(MessengerContext context)
        {
            User testUser = context.Users.First();

            Conversation conversation = new Conversation
            {
                Name = "test conversation"
            };
            await context.Conversations.AddAsync(conversation);

            await context.SaveChangesAsync();

            UserConversation userConversation = new UserConversation
            {
                ConversationId = conversation.ConversationId,
                IsOwner        = true,
                UserId         = testUser.Id
            };
            await context.UserConversations.AddAsync(userConversation);

            await context.SaveChangesAsync();

            await context.Messages.AddRangeAsync(new Message[]
            {
                new Message
                {
                    Content      = "test message 1",
                    OwnerId      = testUser.Id,
                    DateSent     = DateTime.Now,
                    Conversation = conversation
                },
                new Message
                {
                    Content      = "test message 2",
                    OwnerId      = testUser.Id,
                    DateSent     = DateTime.Now.AddSeconds(5),
                    Conversation = conversation
                }
            });

            await context.SaveChangesAsync();
        }
Exemplo n.º 9
0
        public async Task <PrivateMessageDto> AddMessage(AddPrivateMessageDto message)
        {
            var messageToAdd = _mapper.Map <PrivateMessage>(message);

            _context.PrivateMessages.Add(messageToAdd);
            await _context.SaveChangesAsync();

            var result = _mapper.Map <PrivateMessageDto>(messageToAdd);

            return(result);
        }
Exemplo n.º 10
0
        public async Task <IActionResult> SendMessage(MessageForm messageForm)
        {
            var message = new Message()
            {
                Text = messageForm.Text,
                Chat = await _context.Chats.FindAsync(messageForm.ChatId),
                User = await _context.Users.FindAsync(messageForm.UserId),
                Time = DateTime.Now
            };

            if (messageForm.MessageToReplyId != 0)
            {
                message.MessageToReply = await _context.Messages.FindAsync(messageForm.MessageToReplyId);
            }

            await _context.Messages.AddAsync(message);

            await _context.SaveChangesAsync();

            return(Json(new { sentId = message.Id }));
        }
Exemplo n.º 11
0
        public async Task <IActionResult> RemoveMessage([FromQuery] string messageId, string returnUrl = null)
        {
            var user = await _userManager.GetUserAsync(User);

            var mID = user.GetMessagesID();

            var message = await _messengerContext.Messages.FirstOrDefaultAsync(m => m.Id == messageId);

            message.Level--;
            await _messengerContext.SaveChangesAsync();

            return(RedirectStandart(returnUrl));
        }
Exemplo n.º 12
0
        public async Task Send <T>(T message, User to, User from) where T : class
        {
            var json = JsonConvert.SerializeObject(message);

            var user = await _userManager.Users.FirstOrDefaultAsync(u => u == to);

            if (user != null)
            {
                var newMessage = await _messengerContext.AddAsync(new Message()
                {
                    From  = from.Id,
                    Level = MessageLevel.Normal,
                    Test  = json
                });

                user.AddMessagesID(newMessage.Entity.Id);

                await _messengerContext.SaveChangesAsync();

                await _userManager.UpdateAsync(user);
            }
        }
Exemplo n.º 13
0
        public async Task Refresh_RevokedRefreshToken_ShouldSuccess()
        {
            var client = this.factory.CreateClient();

            MessengerContext context = this.factory.Server.Host.Services.GetService(typeof(MessengerContext)) as MessengerContext;

            #region Login

            var data = new
            {
                UserName = "******",
                Password = "******"
            };

            StringContent content = new StringContent(JsonConvert.SerializeObject(data).ToString(), Encoding.UTF8, "application/json");

            HttpResponseMessage loginResponse = await client.PostAsync("/api/auth/login", content);

            loginResponse.EnsureSuccessStatusCode();

            #endregion

            User user = await context.Users.SingleAsync(x => x.UserName == "testuser");

            RefreshToken refreshToken = await context.RefreshTokens.SingleAsync(x => x.UserId == user.Id);

            refreshToken.Revoked = true;
            await context.SaveChangesAsync();

            string stringLoginResponse = await loginResponse.Content.ReadAsStringAsync();

            JObject loginJsonResult = JObject.Parse(stringLoginResponse);

            var refreshTokenViewModel = new RefreshTokenViewModel()
            {
                RefreshToken = loginJsonResult.Value <string>("refreshToken"),
                Token        = loginJsonResult.Value <string>("token")
            };

            StringContent       refreshContent  = new StringContent(JsonConvert.SerializeObject(refreshTokenViewModel), Encoding.UTF8, "application/json");
            HttpResponseMessage refreshResponse = await client.PostAsync("/api/auth/refresh", refreshContent);

            Assert.Equal(HttpStatusCode.BadRequest, refreshResponse.StatusCode);
        }