/// <summary>
        /// Sends an e-mail with a notification that the user has been given access to a generic network.
        /// </summary>
        /// <param name="viewModel">Represents the view model of the e-mail.</param>
        public async Task SendWasAddedToNetworkEmailAsync(EmailWasAddedToNetworkViewModel viewModel)
        {
            // Define the variables for the e-mail.
            var apiKey      = _configuration.GetSection("Authentication:SendGrid:AppKey").Value;
            var client      = new SendGridClient(apiKey);
            var from        = new EmailAddress(_configuration.GetSection("EmailSender:Email").Value, _configuration.GetSection("EmailSender:Name").Value);
            var to          = new EmailAddress(viewModel.Email, viewModel.Email);
            var subject     = "NetControl4BioMed - A network was shared with you";
            var htmlContent = await _renderer.RenderPartialToStringAsync("_EmailWasAddedToNetworkPartial", viewModel);

            var msg = MailHelper.CreateSingleEmail(from, to, subject, string.Empty, htmlContent);
            // Send the e-mail.
            await client.SendEmailAsync(msg);
        }
Exemple #2
0
        public async Task <IActionResult> OnPostAsync(string id)
        {
            // Get the current user.
            var user = await _userManager.GetUserAsync(User);

            // Check if there isn't any ID provided.
            if (string.IsNullOrEmpty(id))
            {
                // Display a message.
                TempData["StatusMessage"] = "Error: No ID has been provided.";
                // Redirect to the index page.
                return(RedirectToPage("/Content/DatabaseTypes/PPI/Created/Networks/Index"));
            }
            // Get the items with the provided ID.
            var items = _context.Networks
                        .Where(item => item.NetworkDatabases.Any(item1 => item1.Database.DatabaseType.Name == "PPI"))
                        .Where(item => item.IsPublic || item.NetworkUsers.Any(item1 => item1.User == user))
                        .Where(item => item.Id == id);

            // Check if there were no items found.
            if (items == null || !items.Any())
            {
                // Display a message.
                TempData["StatusMessage"] = "Error: No item has been found with the provided ID, or you don't have access to it.";
                // Redirect to the index page.
                return(RedirectToPage("/Content/DatabaseTypes/PPI/Created/Networks/Index"));
            }
            // Define the view.
            View = new ViewModel
            {
                Network = items
                          .Include(item => item.NetworkUsers)
                          .ThenInclude(item => item.User)
                          .Include(item => item.NetworkUserInvitations)
                          .First()
            };
            // Check if the user does not exist.
            if (user == null)
            {
                // Display a message.
                TempData["StatusMessage"] = "Error: You need to be logged in to add a user to the network.";
                // Redirect to the index page.
                return(RedirectToPage("/Content/DatabaseTypes/PPI/Created/Networks/Details/Accounts/Users/Index", new { id = View.Network.Id }));
            }
            // Check if the reCaptcha is valid.
            if (!await _reCaptchaChecker.IsValid(Input.ReCaptchaToken))
            {
                // Add an error to the model.
                ModelState.AddModelError(string.Empty, "The reCaptcha verification failed.");
                // Return the page.
                return(Page());
            }
            // Check if the provided model is not valid.
            if (!ModelState.IsValid)
            {
                // Add an error to the model.
                ModelState.AddModelError(string.Empty, "An error was encountered. Please check again the input fields.");
                // Return the page.
                return(Page());
            }
            // Check if the provided e-mail address already has access to the network.
            if (View.Network.NetworkUsers.Any(item => item.User.Email == Input.Email) || View.Network.NetworkUserInvitations.Any(item => item.Email == Input.Email))
            {
                // Add an error to the model.
                ModelState.AddModelError(string.Empty, "The user with the provided e-mail already has access to the network.");
                // Return the page.
                return(Page());
            }
            // Try to get the user with the provided e-mail address.
            var userToAdd = _context.Users
                            .FirstOrDefault(item => item.Email == Input.Email);

            // Check if any user has been found.
            if (userToAdd != null)
            {
                // Define a new task.
                var task = new NetworkUsersTask
                {
                    Items = new List <NetworkUserInputModel>
                    {
                        new NetworkUserInputModel
                        {
                            Network = new NetworkInputModel
                            {
                                Id = View.Network.Id
                            },
                            User = new UserInputModel
                            {
                                Id = userToAdd.Id
                            }
                        }
                    }
                };
                // Try to run the task.
                try
                {
                    // Run the task.
                    await task.CreateAsync(_serviceProvider, CancellationToken.None);
                }
                catch (Exception exception)
                {
                    // Add an error to the model.
                    ModelState.AddModelError(string.Empty, exception.Message);
                    // Redisplay the page.
                    return(Page());
                }
            }
            else
            {
                // Define a new task.
                var task = new NetworkUserInvitationsTask
                {
                    Items = new List <NetworkUserInvitationInputModel>
                    {
                        new NetworkUserInvitationInputModel
                        {
                            Network = new NetworkInputModel
                            {
                                Id = View.Network.Id
                            },
                            Email = Input.Email
                        }
                    }
                };
                // Try to run the task.
                try
                {
                    // Run the task.
                    await task.CreateAsync(_serviceProvider, CancellationToken.None);
                }
                catch (Exception exception)
                {
                    // Add an error to the model.
                    ModelState.AddModelError(string.Empty, exception.Message);
                    // Redisplay the page.
                    return(Page());
                }
            }
            // Define the view model for the e-mail.
            var emailAddedToNetworkViewModel = new EmailAddedToNetworkViewModel
            {
                Email          = user.Email,
                Name           = View.Network.Name,
                Url            = _linkGenerator.GetUriByPage(HttpContext, "/Content/DatabaseTypes/PPI/Created/Networks/Details/Index", handler: null, values: new { id = View.Network.Id }),
                AddedEmail     = Input.Email,
                ApplicationUrl = _linkGenerator.GetUriByPage(HttpContext, "/Index", handler: null, values: null)
            };
            // Send the defined e-mails.
            await _emailSender.SendAddedToNetworkEmailAsync(emailAddedToNetworkViewModel);

            // Define the view model for the e-mail.
            var emailWasAddedToNetworkViewModel = new EmailWasAddedToNetworkViewModel
            {
                Email          = Input.Email,
                Name           = View.Network.Name,
                Url            = _linkGenerator.GetUriByPage(HttpContext, "/Content/DatabaseTypes/PPI/Created/Networks/Details/Index", handler: null, values: new { id = View.Network.Id }),
                AddedByEmail   = user.Email,
                ApplicationUrl = _linkGenerator.GetUriByPage(HttpContext, "/Index", handler: null, values: null)
            };
            // Send the defined e-mails.
            await _emailSender.SendWasAddedToNetworkEmailAsync(emailWasAddedToNetworkViewModel);

            // Display a message to the user.
            TempData["StatusMessage"] = "Success: 1 user added successfully to the network.";
            // Redirect to the users page.
            return(RedirectToPage("/Content/DatabaseTypes/PPI/Created/Networks/Details/Accounts/Users/Index", new { id = View.Network.Id }));
        }
Exemple #3
0
        public async Task <IActionResult> OnPostAsync(string id)
        {
            // Get the current user.
            var user = await _userManager.GetUserAsync(User);

            // Check if the user does not exist.
            if (user == null)
            {
                // Display a message.
                TempData["StatusMessage"] = "Error: An error occured while trying to load the user data. If you are already logged in, please log out and try again.";
                // Redirect to the home page.
                return(RedirectToPage("/Index"));
            }
            // Check if there isn't any ID provided.
            if (string.IsNullOrEmpty(id))
            {
                // Display a message.
                TempData["StatusMessage"] = "Error: No ID has been provided.";
                // Redirect to the index page.
                return(RedirectToPage("/Content/Created/Networks/Index"));
            }
            // Get the items with the provided ID.
            var items = _context.Networks
                        .Where(item => item.NetworkUsers.Any(item1 => item1.User == user))
                        .Where(item => item.Id == id);

            // Check if there were no items found.
            if (items == null || !items.Any())
            {
                // Display a message.
                TempData["StatusMessage"] = "Error: No item has been found with the provided ID, or you don't have access to it.";
                // Redirect to the index page.
                return(RedirectToPage("/Content/Created/Networks/Index"));
            }
            // Define the view.
            View = new ViewModel
            {
                Network = items
                          .Include(item => item.NetworkUsers)
                          .ThenInclude(item => item.User)
                          .Include(item => item.NetworkUserInvitations)
                          .First()
            };
            // Check if the reCaptcha is valid.
            if (!await _reCaptchaChecker.IsValid(Input.ReCaptchaToken))
            {
                // Add an error to the model.
                ModelState.AddModelError(string.Empty, "The reCaptcha verification failed.");
                // Return the page.
                return(Page());
            }
            // Check if the provided model is not valid.
            if (!ModelState.IsValid)
            {
                // Add an error to the model.
                ModelState.AddModelError(string.Empty, "An error was encountered. Please check again the input fields.");
                // Return the page.
                return(Page());
            }
            // Check if the provided e-mail address already has access to the network.
            if (View.Network.NetworkUsers.Any(item => item.User.Email == Input.Email) || View.Network.NetworkUserInvitations.Any(item => item.Email == Input.Email))
            {
                // Add an error to the model.
                ModelState.AddModelError(string.Empty, "The user with the provided e-mail already has access to the network.");
                // Return the page.
                return(Page());
            }
            // Try to get the user with the provided e-mail address.
            var userToAdd = _context.Users
                            .FirstOrDefault(item => item.Email == Input.Email);

            // Check if any user has been found.
            if (userToAdd != null)
            {
                // Create the user permission.
                var networkUser = new NetworkUser
                {
                    UserId          = userToAdd.Id,
                    User            = userToAdd,
                    NetworkId       = View.Network.Id,
                    Network         = View.Network,
                    DateTimeCreated = DateTime.Now
                };
                // Mark it for addition to the database.
                _context.NetworkUsers.Add(networkUser);
                // Save the changes to the database.
                await _context.SaveChangesAsync();
            }
            else
            {
                // Create the user permission.
                var networkUserInvitation = new NetworkUserInvitation
                {
                    Email           = Input.Email,
                    NetworkId       = View.Network.Id,
                    Network         = View.Network,
                    DateTimeCreated = DateTime.Now
                };
                // Mark it for addition to the database.
                _context.NetworkUserInvitations.Add(networkUserInvitation);
                // Save the changes to the database.
                await _context.SaveChangesAsync();
            }
            // Define the view model for the e-mails.
            var emailAddedToNetworkViewModel = new EmailAddedToNetworkViewModel
            {
                Email          = user.Email,
                Name           = View.Network.Name,
                Url            = _linkGenerator.GetUriByPage(HttpContext, "/Content/Created/Networks/Details/Index", handler: null, values: new { id = View.Network.Id }),
                AddedEmail     = Input.Email,
                ApplicationUrl = _linkGenerator.GetUriByPage(HttpContext, "/Index", handler: null, values: null)
            };
            var emailWasAddedToNetworkViewModel = new EmailWasAddedToNetworkViewModel
            {
                Email          = Input.Email,
                Name           = View.Network.Name,
                Url            = _linkGenerator.GetUriByPage(HttpContext, "/Content/Created/Networks/Details/Index", handler: null, values: new { id = View.Network.Id }),
                AddedByEmail   = user.Email,
                ApplicationUrl = _linkGenerator.GetUriByPage(HttpContext, "/Index", handler: null, values: null)
            };
            // Send the defined e-mails.
            await _emailSender.SendAddedToNetworkEmailAsync(emailAddedToNetworkViewModel);

            await _emailSender.SendWasAddedToNetworkEmailAsync(emailWasAddedToNetworkViewModel);

            // Display a message to the user.
            TempData["StatusMessage"] = "Success: 1 user added successfully to the network.";
            // Redirect to the users page.
            return(RedirectToPage("/Content/Created/Networks/Details/Accounts/Users/Index", new { id = View.Network.Id }));
        }