public async void Invite([FromBody] InviteViewModel model) { InviteValidator validator = new InviteValidator(); var results = await validator.ValidateAsync(model); if (!results.IsValid) { TempData[TextConstants.TempDataInviteErrorText] = ValidatorHelper.GetErrorString(results.Errors); return; } var ticket = new RegistrationTicket() { ExpirationDate = DateTime.UtcNow + TimeSpan.FromMinutes(30), ProductKey = model.ProductKey, Role = model.Role }; _ticketManager.AddTicket(ticket); var(server, port, login, password, fromEmail) = GetMailConfiguration(); EmailSender sender = new EmailSender(server, string.IsNullOrEmpty(port) ? null : Int32.Parse(port), login, password, fromEmail, model.Email); var link = GetLink(ticket.Id.ToString()); Task.Run(() => sender.Send("Invitation link HSM", link)); }
private ActionResult ViewInvite(InviteViewModel viewModel) { var firmaPage = FirmaPageTypeEnum.InviteUser.GetFirmaPage(); var viewData = new InviteViewData(CurrentFirmaSession, firmaPage); return(RazorView <Invite, InviteViewData, InviteViewModel>(viewData, viewModel)); }
public async Task <IActionResult> InviteUser(InviteViewModel inviteViewModel) { Invite invite = new Invite(); invite.Email = inviteViewModel.Email; invite.FacilityId = inviteViewModel.FacilityId; invite.OrganizationId = inviteViewModel.organization_id; invite.RoleId = inviteViewModel.RoleId; invite.CreationDate = DateTime.Now; var InvitedUser = await _inviteservice.InsertInvite(invite); var claimsIdentity = new ClaimsIdentity(new List <Claim>() { new Claim(ClaimTypes.Name, InvitedUser.Email), new Claim(ClaimTypes.NameIdentifier, InvitedUser.Id.ToString()), }, "Identity.Application"); var token = _passwordService.CreateAccessToken(_passwordService.CreateJwtClaims(claimsIdentity)); var baseUrl = string.Format("{0}://{1}{2}/", Request.Scheme, Request.Host, Request.PathBase) + "api/User/GetInvitedUser?token=" + token; //api / User / GetInvitedUser ? id = 4 var organisation = await _organizationService.GetOrganization(inviteViewModel.organization_id); var emailBody = string.Format(AppConstants.InviteEmailTemplate, baseUrl); var emailsubjects = string.Format(AppConstants.InviteEmailSubject, organisation.Name); var apiKey = AppConstants.SendGridKey; var result = await _sendEmailService.send_email_sendgrid(apiKey, invite.Email, emailsubjects, emailBody); return(Ok(result)); }
public PartialViewResult InviteModal() { var userId = User.Identity.GetUserId(); var user = db.Users.Find(userId); var houseId = user.HouseholdId; var housename = ""; if (user.Household == null) { housename = "NoHouse"; } if (user.Household != null) { housename = user.Household.Name; } var house = housename; var HouseInfo = new InviteViewModel { HouseholdId = houseId, UserFirst = user.FirstName, UserLast = user.LastName, House = house, SendEmail = user.Email }; return(PartialView("~/Views/Shared/_InviteModal.cshtml", HouseInfo)); }
public async Task SendEventManagerInviteShouldCreateInvite_WhenUserIsOrgAdminForCampaign() { // Arrange var mockMediator = new Mock <IMediator>(); var @event = new Event { Campaign = new Campaign() { ManagingOrganizationId = 1 } }; mockMediator.Setup(mock => mock.SendAsync(It.IsAny <EventByEventIdQuery>())).ReturnsAsync(@event); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); sut.MakeUserAnOrgAdmin(organizationId: "1"); var invite = new InviteViewModel { EventId = 1, InviteeEmailAddress = "*****@*****.**", CustomMessage = "test message" }; // Act IActionResult result = await sut.SendEventManagerInvite(invite.EventId, invite); // Assert mockMediator.Verify(x => x.SendAsync(It.Is <CreateEventManagerInviteCommand>(c => c.Invite == invite)), Times.Once); }
public async Task <string> InviteWizardAsync(InviteViewModel inviteViewModel) { //Create a new Company - Database var companyId = await CreateCompanyAsync(inviteViewModel.CompanyName, inviteViewModel.CompanyDescription); //Create a new BTUser - UserManager var user = new AppUser { Email = inviteViewModel.Email, UserName = inviteViewModel.Email, FirstName = inviteViewModel.FirstName, LastName = inviteViewModel.LastName, EmailConfirmed = true, CompanyId = companyId }; var result = await _userManager.CreateAsync(user, "Xyz$098#"); //Assign that user to a role - RoleService await _roleService.AddUserToRoleAsync(user, Roles.Admin.ToString()); //Create a new project - Database var projectId = await CreateProjectAsync(inviteViewModel.ProjectName, inviteViewModel.ProjectDescription, companyId); //Assign that user to that project - ProjectService await _projectService.AddUserToProjectAsync(user.Id, projectId); return(user.Id); }
public async Task CreateEventManagerInvite() { var handler = new CreateEventManagerInviteCommandHandler(Context); var invite = new InviteViewModel { CustomMessage = "message", EventId = 5, InviteeEmailAddress = "*****@*****.**", }; var inviteCommand = new CreateEventManagerInviteCommand { Invite = invite, UserId = "userId" }; handler.DateTimeUtcNow = () => new DateTime(2016, 5, 29); await handler.Handle(inviteCommand); Context.CampaignManagerInvites.Count().ShouldBe(0); Context.EventManagerInvites.Count().ShouldBe(1); Context.EventManagerInvites.FirstOrDefault().AcceptedDateTimeUtc.ShouldBe(null); Context.EventManagerInvites.FirstOrDefault().CustomMessage.ShouldBe("message"); Context.EventManagerInvites.FirstOrDefault().EventId.ShouldBe(5); Context.EventManagerInvites.FirstOrDefault().InviteeEmailAddress.ShouldBe("*****@*****.**"); Context.EventManagerInvites.FirstOrDefault().RejectedDateTimeUtc.ShouldBe(null); Context.EventManagerInvites.FirstOrDefault().RevokedDateTimeUtc.ShouldBe(null); Context.EventManagerInvites.FirstOrDefault().SenderUserId.ShouldBe("userId"); Context.EventManagerInvites.FirstOrDefault().SentDateTimeUtc.ShouldBe(new DateTime(2016, 5, 29)); }
public async Task SendEventManagerInvitePostReturnsUnauthorizedResult_WhenUserIsNotOrgAdminForCampaign() { // Arrange var mockMediator = new Mock <IMediator>(); var @event = new Event { Campaign = new Campaign() { ManagingOrganizationId = 1 } }; mockMediator.Setup(mock => mock.SendAsync(It.IsAny <EventByEventIdQuery>())).ReturnsAsync(@event); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); sut.MakeUserAnOrgAdmin(organizationId: "2"); var invite = new InviteViewModel(); // Act IActionResult result = await sut.SendEventManagerInvite(eventId, invite); // Assert Assert.IsType <UnauthorizedResult>(result); }
/// <summary> /// Generates the invite menu item. /// </summary> /// <returns></returns> private MenuItem GenerateInviteMenuItem() { var item = new MenuItem(); item.Header = Resources.InviteViewMenuTitle; var isEnabled = startupParams.AuthProvider != null; item.IsEnabled = isEnabled; item.Click += (sender, args) => { var model = new InviteModel(startupParams.AuthProvider); model.MessageLogged += this.OnMessageLogged; var viewModel = new InviteViewModel(model); var view = new InviteView(viewModel) { Owner = loadedParams.DynamoWindow, WindowStartupLocation = WindowStartupLocation.CenterOwner }; view.ShowDialog(); model.MessageLogged -= this.OnMessageLogged; }; return(item); }
public async Task <IActionResult> InviteUser(int id, [FromBody] InviteViewModel model) { var userId = User.GetUserId(); if (model.UserId == userId) { return(this.BadRequestError("You can't invite yourself.")); } var ev = await _eventService.GetEventByIdAsync(id, nameof(Event.Period), nameof(Event.Owner)); if (userId != ev.Owner.Id) { return(this.BadRequestError("Only owner can invite users.")); } if (ev.IsPrivate) { return(this.BadRequestError("You can't invite users on private event.")); } if (ev.IsOld(DateTime.UtcNow)) { return(this.BadRequestError("You can't invite users on events from the past.")); } await _eventService.InviteUserAsync(ev.Id, model.UserId, userId, model.IsReadOnly); var invitation = await _invitationService.GetInvitationAsync(id, model.UserId); await _invitationManager.UserInvitedAsync(model.UserId, _mapper.Map <InvitationViewModel>(invitation)); return(Ok()); }
public async Task <IActionResult> Create([Bind("Email, FirstName, LastName, CompanyName, CompanyDescription, ProjectName, ProjectDescription")] InviteViewModel inviteViewModel) { if (ModelState.IsValid) { var userId = await _inviteService.InviteWizardAsync(inviteViewModel); var companyId = _context.Companies.FirstOrDefault(c => c.Name == inviteViewModel.CompanyName).Id; var invite = new Invite { Email = inviteViewModel.Email, CompanyId = companyId, InviteDate = DateTime.Now, IsValid = true, InvitorId = _userManager.GetUserId(User), InviteeId = userId, CompanyToken = Guid.NewGuid() }; _context.Add(invite); await _context.SaveChangesAsync(); var code = invite.CompanyToken; var callbackUrl = Url.Action( "AcceptInvite", "Tickets", values: new { userId, code, }, protocol: Request.Scheme); await _emailSender.SendEmailAsync(invite.Email, "Join my Bug Tracker", $"Create a ticket in my bug tracker by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."); return(RedirectToAction(nameof(Index))); } return(View(inviteViewModel)); }
internal List <InviteViewModel> getInviteByStudentId(string studentId) { using (SqlConnection sqlConnection = new SqlConnection(connectionString)) { using (SqlCommand command = new SqlCommand("sp_UserGetInvitesByStudentId", sqlConnection)) { try { sqlConnection.Open(); command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@Student", studentId); SqlDataReader rdr = command.ExecuteReader(); List <InviteViewModel> inviteList = new List <InviteViewModel>(); while (rdr.Read()) { InviteViewModel invite = new InviteViewModel(); invite.Id = Convert.ToInt32(rdr["Id"]); invite.StudentId = rdr["StudentId"].ToString(); invite.TeacherId = rdr["TeacherId"].ToString(); invite.SubjectId = Convert.ToInt32(rdr["SubjectId"]); invite.Accepted = Convert.ToBoolean(rdr["Accepted"]); invite.CreateDate = Convert.ToDateTime(rdr["CreateDate"]); inviteList.Add(invite); } return(inviteList); } catch (Exception ex) { throw ex; } } } }
public IActionResult AddNewRecordLabel(InviteViewModel model) { if (!ModelState.IsValid) { return(View(model)); } var response = _userManager.CreateUser(model.Name, model.Email, Role.RecordLabel); if (response == null) { ModelState.AddModelError("Email", "Email already exists"); return(View(model)); } var user = response.Result; _recordLabelManager.Create(new RecordLabel() { User = user }, CurrentLoggedUserId); _recordLabelManager.Save(); var code = _userManager.GeneratePasswordResetTokenAsync(user).Result; var callbackUrl = Url.ResetPasswordCallbackLink(user.Id.ToString(), code, Request.Scheme); _emailsManager.PrepareSendMail(EmailTemplateType.InvitedRecordLabel, model.Email, callbackUrl); return(View("SuccessfullyInvited")); }
public async Task <IActionResult> SendEventManagerInvite(int eventId, InviteViewModel invite) { if (invite == null) { return(BadRequest()); } if (ModelState.IsValid) { var @event = await _mediator.SendAsync(new EventByEventIdQuery { EventId = eventId }); if (@event == null) { return(BadRequest()); } if (!IsUserAuthorizedToSendInvite(@event.Campaign.ManagingOrganizationId)) { return(Unauthorized()); } invite.EventId = eventId; var user = await _userManager.GetUserAsync(User); await _mediator.SendAsync(new CreateEventManagerInviteCommand { Invite = invite, UserId = user?.Id }); return(RedirectToAction(actionName: "Details", controllerName: "Event", routeValues: new { area = AreaNames.Admin, id = invite.EventId })); } return(View("Send", invite)); }
/// <summary> /// Create an invite and send it to the user. /// </summary> /// <param name="invite"> The invite. </param> /// <param name="userId"> The user id of the person doing the inviting. </param> /// <param name="inviteIndexUri"> The invite Index Uri. </param> /// <returns> The <see cref="InviteViewModel"/>. </returns> public InviteViewModel CreateInvite(InviteViewModel invite, int userId, Uri inviteIndexUri) { // Check if the invite already exists var foundInvite = this.repo.GetInvite(invite.InviteeEmailAddress); if (foundInvite != null) { return(this.ResendInvite(foundInvite, inviteIndexUri) ? this.conversions.ConvertDatabaseModelToViewModel(foundInvite) : null); } var inviteToCreate = this.conversions.ConvertViewModelToDatabaseModel(invite); inviteToCreate.CreatorID = userId; inviteToCreate.CreatedAt = DateTime.Now; inviteToCreate.Token = Guid.NewGuid().ToString(); var createdInvite = this.repo.CreateInvite(inviteToCreate); if (createdInvite == null) { return(null); } var email = new InviteEmail(createdInvite); email.Send(inviteIndexUri); return(this.conversions.ConvertDatabaseModelToViewModel(createdInvite)); }
public async Task <IActionResult> SendCampaignManagerInvite(int campaignId, InviteViewModel invite) { if (invite == null) { return(BadRequest()); } if (ModelState.IsValid) { var campaign = await _mediator.SendAsync(new CampaignByCampaignIdQuery { CampaignId = campaignId }); if (campaign == null) { return(BadRequest()); } if (!IsUserAuthorizedToSendInvite(campaign.ManagingOrganizationId)) { return(Unauthorized()); } invite.CampaignId = campaignId; var user = await _userManager.GetUserAsync(User); await _mediator.SendAsync(new CreateCampaignManagerInviteCommand { Invite = invite, UserId = user?.Id }); return(RedirectToAction(actionName: "Details", controllerName: "Campaign", routeValues: new { area = "Admin", id = invite.CampaignId })); } return(View("Send", invite)); }
public async Task <IActionResult> Edit(InviteViewModel model) { if (ModelState.IsValid) { var currentUser = await User.GetApplicationUser(_userManager); var invite = await _context.Invites.Include(i => i.CreatedUser).SingleAsync(m => m.Id == model.Id); if (invite == null || invite.InvitedById != currentUser.Id) { return(NotFound()); } var createdUser = invite.CreatedUser; createdUser.Email = model.Email; createdUser.DisplayName = model.Email; createdUser.UserName = model.Email; await _userManager.UpdateAsync(createdUser); await _invitesService.SendEmail(invite, Url); return(RedirectToAction(nameof(Index))); } return(View(model)); }
public async Task SendEventManagerInviteShouldNotCreateInvite_WhenUserIsNotOrgAdminForCampaign() { // Arrange var mockMediator = new Mock <IMediator>(); var @event = new Event { Campaign = new Campaign() { ManagingOrganizationId = 1 } }; mockMediator.Setup(mock => mock.SendAsync(It.IsAny <EventByEventIdQuery>())).ReturnsAsync(@event); var sut = new InviteController(mockMediator.Object, new FakeUserManager()); sut.MakeUserAnOrgAdmin(organizationId: "2"); var invite = new InviteViewModel(); // Act IActionResult result = await sut.SendEventManagerInvite(eventId, invite); // Assert mockMediator.Verify(x => x.SendAsync(It.IsAny <CreateCampaignManagerInviteCommand>()), Times.Never); }
public JsonResult Invite([FromBody] InviteViewModel model) { SmtpClient client = new SmtpClient(Configuration["Smtp:Host"], int.Parse(Configuration["Smtp:Port"])); client.UseDefaultCredentials = false; client.Credentials = new NetworkCredential(Configuration["Smtp:User"], Configuration["Smtp:Password"]); MailMessage message = new MailMessage(); message.From = new MailAddress("*****@*****.**"); message.To.Add(new MailAddress(model.Email)); StreamReader reader = new StreamReader("Emails/invitation.html"); string letter = reader.ReadToEnd(); reader.Dispose(); reader.Close(); message.Body = letter; message.IsBodyHtml = true; message.Subject = "You are the chosen one"; client.Send(message); return(Json(new { status = true })); }
public ActionResult AddtoHouse(InviteViewModel model, int id) { var house = db.Household.Find(id); model.Id.Equals(id); return(View(model)); }
public void Startup(ViewStartupParams p) { publishModel = new PublishModel(p.AuthProvider, p.CustomNodeManager); publishViewModel = new PublishViewModel(publishModel); inviteModel = new InviteModel(p.AuthProvider); inviteModel.MessageLogged += this.OnMessageLogged; inviteViewModel = new InviteViewModel(inviteModel); }
public void InviteRejected() { var i = new InviteViewModel(new Structures.AndersonInvite()); bool result = true; i.InviteProcessed += (_, b) => result = b; i.Invite_Rejected.Execute(); Assert.False(result); }
public void InviteAccepted() { var i = new InviteViewModel(new Structures.AndersonInvite()); bool result = false; i.InviteProcessed += (_, b) => result = b; i.Invite_Accepted.Execute(); Assert.True(result); }
public IActionResult Invite() { var listOfContacts = GetEmailsList(); var model = new InviteViewModel() { Contacts = listOfContacts }; return(View(model)); }
public async Task <IActionResult> Invite(string name) { var users = await userService.GetAllAsync(); ViewData["Users"] = new SelectList(users.Where(u => u.Rank != "Admin" && u.Rank != "Organizer"), "Username", "Username"); var inviteViewModel = new InviteViewModel(); inviteViewModel.Name = name; return(View(inviteViewModel)); }
private ActionResult ViewInvite(InviteViewModel viewModel) { var neptunePage = NeptunePage.GetNeptunePageByPageType(NeptunePageType.InviteUser); var organizations = HttpRequestStorage.DatabaseEntities.Organizations.OrderBy(x => x.OrganizationName).ToList(); var cancelUrl = Request.UrlReferrer != null?Request.UrlReferrer.ToString() : SitkaRoute <HomeController> .BuildUrlFromExpression(x => x.Index()); var viewData = new InviteViewData(CurrentPerson, organizations, neptunePage, cancelUrl); return(RazorView <Invite, InviteViewData, InviteViewModel>(viewData, viewModel)); }
public async Task <IActionResult> SendInvite([FromBody] InviteViewModel invite) { if (User.Identity.IsAuthenticated && !DataService.GetUserByNameWithOrg(User.Identity.Name).IsAdministrator) { return(Unauthorized()); } if (!ModelState.IsValid) { return(BadRequest()); } Request.Headers.TryGetValue("OrganizationID", out var orgID); if (!DataService.DoesUserExist(invite.InvitedUser)) { var result = await DataService.CreateUser(invite.InvitedUser, invite.IsAdmin, orgID); if (result) { var user = await UserManager.FindByEmailAsync(invite.InvitedUser); await UserManager.ConfirmEmailAsync(user, await UserManager.GenerateEmailConfirmationTokenAsync(user)); return(Ok()); } else { return(BadRequest("There was an issue creating the new account.")); } } else { var newInvite = DataService.AddInvite(orgID, invite); var inviteURL = $"{Request.Scheme}://{Request.Host}/Invite?id={newInvite.ID}"; var emailResult = await EmailSender.SendEmailAsync(invite.InvitedUser, "Invitation to Organization in Remotely", $@"<img src='{Request.Scheme}://{Request.Host}/images/Remotely_Logo.png'/> <br><br> Hello! <br><br> You've been invited to join an organization in Remotely. <br><br> You can join the organization by <a href='{HtmlEncoder.Default.Encode(inviteURL)}'>clicking here</a>.", orgID); if (!emailResult) { return(Problem("There was an error sending the invitation email.")); } return(Ok()); } }
public IActionResult SendInvite([FromBody] InviteViewModel model) { //Получаем из токена username var username = User.Identity.Name; //Ищем данного пользователя var user = _context.Users .Include(u => u.UserGroups) .ThenInclude(ug => ug.Group) .FirstOrDefault(u => u.Username == username); int group_id = model.GroupId; //Ищем данную группу var group = _context.Groups .Include(g => g.UserGroups) .ThenInclude(ug => ug.User) .FirstOrDefault(g => g.Id == group_id); var requesterUsername = model.UserName; //Ищем пользователя, который сделал запрос var userToInvite = _context.Users .Include(u => u.UserGroups) .ThenInclude(ug => ug.Group) .FirstOrDefault(u => u.Username == requesterUsername); //Если все существует if (user != null && group != null && userToInvite != null) { //Смотрим сть ли уже у пользователя приглашение var request = _context.Invites .Include(ppr => ppr.User) .Include(ppr => ppr.Group) .FirstOrDefault(ppr => ppr.Group.Id == group_id && ppr.User.Id == userToInvite.Id); //Если нет, то приглашаем, если есть то игнорируем if (request == null) { var newInvite = new InviteToGroup { User = userToInvite, Group = group }; _context.Invites.Add(newInvite); _context.SaveChanges(); } return(Ok()); } else { return(Unauthorized()); } }
public async Task <IActionResult> ChooseJury(string name) { var users = await this.userService.GetAllAsync(); ViewData["Users"] = new SelectList(users.Where(u => u.Rank == "Master" || u.Rank == "Wise and Benevolent Photo Dictator"), "Username", "Username"); var inviteViewModel = new InviteViewModel(); inviteViewModel.Name = name; return(View(inviteViewModel)); }
//you are now //leaving the main page //we will miss you public ActionResult InviteUser(int id) { if (db.Households.FirstOrDefault(h => h.Id == id).Keyword == null) { return(RedirectToAction("SetKeyword", new { Id = id })); } var model = new InviteViewModel(); model.Id = id; return(View(model)); }