示例#1
0
        public async Task SendMessage(string message, string id)
        {
            ChatApplicationUser user = await _usermanager.FindByEmailAsync(Context.User.Identity.Name);

            try
            {
                var msg = new Message()
                {
                    Body           = message,
                    DateSend       = DateTime.Now,
                    SenderUserID   = user.Id,
                    IsDelivered    = false,
                    IsRead         = false,
                    ReceiverUserID = id
                };
                _context.Messages.Add(msg);
                _context.SaveChanges();
            }
            catch (Exception err)
            {
                Console.WriteLine(err);
            }
            if (Context.User.Identity.IsAuthenticated)
            {
                await Clients.User(id).SendAsync("ReceiveMessage", id, message, false);

                await Clients.User(user.Id).SendAsync("ReceiveMessage", user.Id, message, true);
            }
        }
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl ??= Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new ChatApplicationUser
                {
                    First_Name = Input.First_Name,
                    Last_Name  = Input.Last_Name,
                    DOB        = Input.DOB,
                    UserName   = Input.Email,
                    Email      = Input.Email
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
示例#3
0
        private async Task LoadAsync(ChatApplicationUser user)
        {
            var email = await _userManager.GetEmailAsync(user);

            Email = email;

            Input = new InputModel
            {
                NewEmail = email,
            };

            IsEmailConfirmed = await _userManager.IsEmailConfirmedAsync(user);
        }
示例#4
0
        public User CreateUser(ChatApplicationUser caUser)
        {
            User user = new User();

            user.Id          = caUser.Id;
            user.First_Name  = caUser.First_Name;
            user.Last_Name   = caUser.Last_Name;
            user.DOB         = caUser.DOB;
            user.UserName    = caUser.UserName;
            user.Email       = caUser.Email;
            user.PhoneNumber = caUser.PhoneNumber;
            return(user);
        }
示例#5
0
        public async Task <IActionResult> Send_Message(IFormCollection data)
        {
            DatabaseContext dbContext = new DatabaseContext();

            ChatApplicationUser currentUser = await GetCurrentUserAsync();

            Conversation conversation = dbContext.Conversations.Find(data["currentConversationId"]);

            dbContext.Entry(conversation).Collection(c => c.Participants).Load();
            dbContext.Entry(conversation).Collection(c => c.Messages).Load();
            dbContext.Entry(conversation).Reference(c => c.CreatorUser).Load();


            ViewData["selectedConversation"] = conversation;

            User user = dbContext.Users.Find(currentUser.Id);
            List <Conversation> listOfConversation = new List <Conversation>();

            try
            {
                List <Participants> participants = dbContext.Participants.Where(p => p.User.Id == user.Id)
                                                   .Include(participant => participant.User).Include(participant => participant.Conversation).ThenInclude(conversaion => conversaion.Messages).Include(conversation => conversation.Conversation.Participants).ToList();

                foreach (var participant in participants)
                {
                    if (participant != null)
                    {
                        listOfConversation.Add(participant.Conversation);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }


            DashboadViewModel dashboadViewModel = new DashboadViewModel();

            dashboadViewModel.listOfConversation = listOfConversation;
            dashboadViewModel.user = user;
            dashboadViewModel.selectedConverstaion = conversation;
            dashboadViewModel.databaseContext      = new DatabaseContext();
            TempData["selectedConversationId"]     = conversation.Id;

            return(RedirectToAction("Index"));
        }
        private async Task LoadAsync(ChatApplicationUser user)
        {
            var userName = await _userManager.GetUserNameAsync(user);

            var phoneNumber = await _userManager.GetPhoneNumberAsync(user);

            Username = userName;

            Input = new InputModel
            {
                First_Name = user.First_Name,
                Last_Name  = user.Last_Name,
                DOB        = user.DOB,

                PhoneNumber = phoneNumber
            };
        }
示例#7
0
        public async Task <IActionResult> Index()
        {
            DatabaseContext dbContext = new DatabaseContext();

            ChatApplicationUser currentUser = await GetCurrentUserAsync();

            User user = CreateUser(currentUser);

            List <Conversation> listofConversations = new List <Conversation>();

            try
            {
                List <Participants> participants = dbContext.Participants.Where(p => p.User.Id == user.Id)
                                                   .Include(participant => participant.User).Include(participant => participant.Conversation).ThenInclude(conversaion => conversaion.Messages).Include(conversation => conversation.Conversation.Participants).ToList();

                foreach (var participant in participants)
                {
                    if (participant != null)
                    {
                        listofConversations.Add(participant.Conversation);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            DashboadViewModel dashboadViewModel = new DashboadViewModel();

            dashboadViewModel.listOfConversation = listofConversations;
            dashboadViewModel.user            = user;
            dashboadViewModel.databaseContext = new DatabaseContext();

            if (TempData["selectedConversationId"] != null)
            {
                Conversation selectedConversation = dbContext.Conversations.Find(TempData["selectedConversationId"].ToString());

                dbContext.Entry(selectedConversation).Collection(c => c.Participants).Load();
                dbContext.Entry(selectedConversation).Collection(c => c.Messages).Load();
                dbContext.Entry(selectedConversation).Reference(c => c.CreatorUser).Load();
                dashboadViewModel.selectedConverstaion = selectedConversation;
            }
            return(View(dashboadViewModel));
        }
        private async Task LoadSharedKeyAndQrCodeUriAsync(ChatApplicationUser user)
        {
            // Load the authenticator key & QR code URI to display on the form
            var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);

            if (string.IsNullOrEmpty(unformattedKey))
            {
                await _userManager.ResetAuthenticatorKeyAsync(user);

                unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);
            }

            SharedKey = FormatKey(unformattedKey);

            var email = await _userManager.GetEmailAsync(user);

            AuthenticatorUri = GenerateQrCodeUri(email, unformattedKey);
        }
        public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            // Get the information about the user from the external login provider
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ErrorMessage = "Error loading external login information during confirmation.";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }

            if (ModelState.IsValid)
            {
                var user = new ChatApplicationUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user, info);

                    if (result.Succeeded)
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);
                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            LoginProvider = info.LoginProvider;
            ReturnUrl     = returnUrl;
            return(Page());
        }
示例#10
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                var user = new ChatApplicationUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { userId = user.Id, code = code },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    await _signInManager.SignInAsync(user, isPersistent : false);

                    return(LocalRedirect(returnUrl));
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
示例#11
0
        public async Task <IActionResult> FetchUser(string UserId)
        {
            HomeDashboardViewModel homeDashboardViewModel = new HomeDashboardViewModel()
            {
                Users                     = chatApplicationDBContext.Users.ToList(),
                MessagesBetween           = null,
                ReceiverUser              = null,
                LastMessageBetweenTwoUser = new Dictionary <string, Message>()
            };
            var loggedInUser = await userManager.GetUserAsync(User);

            ViewBag.loginUser = loggedInUser.Id;



            for (int i = 0; i < homeDashboardViewModel.Users.Count; i++)
            {
                if (homeDashboardViewModel.Users[i] != loggedInUser)
                {
                    // fetch mesg between these 2 users.
                    var user2Id = homeDashboardViewModel.Users[i].Id;
                    var res     = chatApplicationDBContext.Messages.Where(q =>
                                                                          ((
                                                                               q.ReceiverUserID == user2Id) && (q.SenderUserID == loggedInUser.Id)) ||
                                                                          ((q.SenderUserID == user2Id) && (q.ReceiverUserID == loggedInUser.Id))
                                                                          );

                    if (res != null)
                    {
                        homeDashboardViewModel.MessagesBetween = res.ToList();
                        if (homeDashboardViewModel.MessagesBetween.Count != 0)
                        {
                            homeDashboardViewModel.LastMessageBetweenTwoUser[user2Id] = homeDashboardViewModel.MessagesBetween[homeDashboardViewModel.MessagesBetween.Count - 1];
                        }
                        else
                        {
                            homeDashboardViewModel.LastMessageBetweenTwoUser[user2Id] = null;
                        }
                    }
                }
            }

            for (int i = 0; i < homeDashboardViewModel.Users.Count; i++)
            {
                if (homeDashboardViewModel.Users[i] == loggedInUser)
                {
                    homeDashboardViewModel.Users.Remove(homeDashboardViewModel.Users[i]);
                }
            }


            var result = chatApplicationDBContext.Messages.Where(q =>
                                                                 ((q.ReceiverUserID == UserId) && (q.SenderUserID == loggedInUser.Id)) ||
                                                                 ((q.SenderUserID == UserId) && (q.ReceiverUserID == loggedInUser.Id))
                                                                 );

            homeDashboardViewModel.MessagesBetween = result.ToList();

            ChatApplicationUser receiver = await userManager.FindByIdAsync(UserId);

            ViewBag.receiverId = receiver.Id;
            homeDashboardViewModel.ReceiverUser = receiver;
            return(View("Dashboard", model: homeDashboardViewModel));
        }
        public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            // Get the information about the user from the external login provider
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ErrorMessage = "Error loading external login information during confirmation.";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }

            if (ModelState.IsValid)
            {
                var user = new ChatApplicationUser {
                    UserName = Input.Email, Email = Input.Email
                };

                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user, info);

                    if (result.Succeeded)
                    {
                        _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);

                        var userId = await _userManager.GetUserIdAsync(user);

                        var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                        var callbackUrl = Url.Page(
                            "/Account/ConfirmEmail",
                            pageHandler: null,
                            values: new { area = "Identity", userId = userId, code = code },
                            protocol: Request.Scheme);

                        await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                          $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                        // If account confirmation is required, we need to show the link if we don't have a real email sender
                        if (_userManager.Options.SignIn.RequireConfirmedAccount)
                        {
                            return(RedirectToPage("./RegisterConfirmation", new { Email = Input.Email }));
                        }

                        await _signInManager.SignInAsync(user, isPersistent : false, info.LoginProvider);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            ProviderDisplayName = info.ProviderDisplayName;
            ReturnUrl           = returnUrl;
            return(Page());
        }
示例#13
0
        public async Task <IActionResult> New_Conversation(IFormCollection data)
        {
            string recipentUserName = data["recipentUserName"];
            string creatorId        = data["creatorId"];
            string creatorUserName  = data["creatorUserName"];

            IdentityDBContext identityDbContext = new IdentityDBContext();
            DatabaseContext   databaseContext   = new DatabaseContext();


            ChatApplicationUser cauRecipentUser = identityDbContext.ChatApplicationUsers.Where(ChatApplicationUser => ChatApplicationUser.UserName == recipentUserName).FirstOrDefault();;
            ChatApplicationUser cauCurrentUser  = await GetCurrentUserAsync();

            User currentUser  = databaseContext.Users.Find(cauCurrentUser.Id);
            User recipentUser = databaseContext.Users.Find(cauRecipentUser.Id);

            if (recipentUser == null)
            {
                recipentUser = CreateUser(cauRecipentUser);
                databaseContext.Users.Add(recipentUser);
                databaseContext.SaveChanges();
            }
            if (currentUser == null)
            {
                currentUser = CreateUser(cauCurrentUser);
                databaseContext.Users.Add(currentUser);
                databaseContext.SaveChanges();
            }

            List <Participants> existingCurrentParticipants   = databaseContext.Participants.Where(p => p.User.Id == currentUser.Id).Include(p => p.Conversation).Include(p => p.User).ToList();
            List <Participants> existingRecipientParticipants = databaseContext.Participants.Where(p => p.User.Id == recipentUser.Id).Include(p => p.Conversation).Include(p => p.User).ToList();

            Conversation conversation;

            DashboadViewModel dashboadViewModel;

            foreach (var recipent in existingRecipientParticipants)
            {
                foreach (var current in existingCurrentParticipants)
                {
                    if (current.Conversation.Id == recipent.Conversation.Id)
                    {
                        // existing Conversation
                        conversation = current.Conversation;

                        dashboadViewModel                 = new DashboadViewModel();
                        dashboadViewModel.user            = currentUser;
                        dashboadViewModel.databaseContext = new DatabaseContext();

                        //return Content($"existing conversation with conversation id: {conversation.Id}");
                        return(RedirectToAction("Index", dashboadViewModel));
                    }
                }
            }

            Conversation newConversation = new Conversation();

            newConversation.CreatorUser = currentUser;
            newConversation.Created_at  = DateTime.Now;
            newConversation.Updated_at  = DateTime.Now;

            databaseContext.Conversations.Add(newConversation);
            databaseContext.SaveChanges();

            Participants currentParticipant = new Participants()
            {
                User = currentUser, Conversation = newConversation
            };
            Participants recipientParticipant = new Participants()
            {
                User = recipentUser, Conversation = newConversation
            };

            databaseContext.Participants.Add(currentParticipant);
            databaseContext.Participants.Add(recipientParticipant);

            databaseContext.SaveChanges();

            dashboadViewModel                 = new DashboadViewModel();
            dashboadViewModel.user            = currentUser;
            dashboadViewModel.databaseContext = new DatabaseContext();
            //return Red(newConversation.Id);
            return(RedirectToAction("Index", dashboadViewModel));
        }