Esempio n. 1
0
        public async Task InviteUser(InviteUserModel inviteUserModel, CancellationToken cancellationToken)
        {
            var userInvitation = await this.UserService.InviteUserAsync(inviteUserModel, cancellationToken : cancellationToken);

            var           userName     = this.CurrentUserProvider.GetUsername();
            StringBuilder completeBody = new(inviteUserModel.CustomMessage);

            completeBody.AppendLine();
            string baseUrl          = $"{this.Request.Scheme}://{this.Request.Host.Value}";
            var    userHomePagePath = Common.Global.Constants.UserPagesRoutes.UserHomePage
                                      .Replace("{UserId:long}", userInvitation.InvitingApplicationUserId.ToString());
            string invitingUserHomeUrl = $"{baseUrl}{userHomePagePath}";
            string authPath            = $"authentication/login?returnUrl={Uri.EscapeDataString(invitingUserHomeUrl)}";
            string fullLink            = $"{baseUrl}/{authPath}";
            string link = $"<a href='{fullLink}'>{fullLink}</a>";

            completeBody.AppendLine($"Once you are on the website you can create your account using the Sign up link." +
                                    $"Your invite code is: {userInvitation.InviteCode}");
            completeBody.AppendLine(link);
            await this.EmailService.SendEmailAsync(
                toEmailAddress : inviteUserModel.ToEmailAddress,
                subject : $"{userName} is inviting you to " +
                $"FairPlayTube: The Next Generation Of Video Sharing Portals.",
                body : completeBody.ToString(), isBodyHtml : true,
                cancellationToken : cancellationToken);
        }
Esempio n. 2
0
        public async Task <IHttpActionResult> Invite(InviteUserModel model)
        {
            try
            {
                if (string.IsNullOrEmpty(model.Email))
                {
                    return(BadRequest(ResponseMessages.InviteUserEmailRequired.ToDesc()));
                }

                if (await _userRepository.IsUserActive(model.Email))
                {
                    return(BadRequest(ResponseMessages.EmailDuplicate.ToDesc()));
                }

                if (!await _userRepository.IsEmailExists(model.Email))
                {
                    await _userRepository.AddAsync(new User
                    {
                        IsActive = false,
                        Email    = model.Email
                    });
                }

                var user = await _userRepository.GetUserAsync(model.Email);

                if (user == null)
                {
                    return(BadRequest(ResponseMessages.UserNotFound.ToDesc()));
                }

                await _logRepository.UpdateAccess(new LogAccessModel
                {
                    LogId    = model.LogId,
                    UserId   = user._id.ToString(),
                    CanRead  = model.CanRead,
                    CanWrite = model.CanWrite
                });

                var body = _emailTemplateRenderer.Render(EmailTemplateName.InviteUser, new
                {
                    ClientDomain = ConfigurationManager.AppSettings["ClientDomain"],
                });

                var sendEmailModel = new SendEmailModel
                {
                    Body    = body,
                    Subject = "You has been invited to monitorr.io",
                    Emails  = { model.Email }
                };

                await _emailSender.SendAsync(sendEmailModel);

                return(Ok(ResponseMessages.Ok.ToDesc()));
            }
            catch (Exception ex)
            {
                LogVerbose(ex);
            }
            return(InternalServerError());
        }
Esempio n. 3
0
        public async Task <UserInvitation> InviteUserAsync(InviteUserModel inviteUserModel, CancellationToken cancellationToken)
        {
            var userInvitationEntity = await this.FairplaytubeDatabaseContext.UserInvitation
                                       .Where(p => p.InvitedUserEmail == inviteUserModel.ToEmailAddress).SingleOrDefaultAsync(cancellationToken: cancellationToken);

            if (userInvitationEntity is not null)
            {
                throw new CustomValidationException($"An invitation already exists for user: {inviteUserModel.ToEmailAddress}");
            }
            var currentUserObjectId = this.CurrentUserProvider.GetObjectId();
            var currentUserEntity   = await this.FairplaytubeDatabaseContext.ApplicationUser
                                      .Where(p => p.AzureAdB2cobjectId.ToString() == currentUserObjectId).SingleAsync(cancellationToken: cancellationToken);

            userInvitationEntity = new UserInvitation()
            {
                InviteCode                = Guid.NewGuid(),
                InvitedUserEmail          = inviteUserModel.ToEmailAddress,
                InvitingApplicationUserId = currentUserEntity.ApplicationUserId,
            };
            await this.FairplaytubeDatabaseContext.UserInvitation.AddAsync(userInvitationEntity, cancellationToken : cancellationToken);

            await this.FairplaytubeDatabaseContext.SaveChangesAsync(cancellationToken : cancellationToken);

            return(userInvitationEntity);
        }
Esempio n. 4
0
        public async Task <long> CreateInvitation(InviteUserModel model, string bossUserId, string bossEmail,
                                                  string token, DateTime invitationDateTime)
        {
            var existingInvitation = await GetUserInvitationByEmail(model.EmailAddress.ToLower(), bossUserId);

            if (existingInvitation != null)
            {
                throw new ArgumentException($"An invitation for email: {model.EmailAddress.ToLower()} already exists.");
            }

            await using var command = _connection.CreateCommand();
            command.CommandType     = CommandType.StoredProcedure;
            command.CommandText     = "CreateInvitation";
            command.Parameters.AddWithValue("@BossUserId", bossUserId);
            command.Parameters.AddWithValue("@BossEmail", bossEmail);
            command.Parameters.AddWithValue("@UserEmail", model.EmailAddress.ToLower());
            command.Parameters.AddWithValue("@Token", token);
            command.Parameters.AddWithValue("@InvitationDate", invitationDateTime);

            if (_connection.State != ConnectionState.Open)
            {
                await _connection.OpenAsync();
            }
            await using var reader = await command.ExecuteReaderAsync(CommandBehavior.CloseConnection);

            await reader.ReadAsync();

            return((long)reader.GetDecimal(0));
        }
Esempio n. 5
0
        public async Task <StatusMessage> InviteUser(InviteUserModel model)
        {
            var result = new StatusMessage();

            if (!ModelState.IsValid)
            {
                result.IsSuccessful = false;
                result.Message      = ModelState.GetErrorMessage();
                return(result);
            }
            PasswordHasher objpassword = new PasswordHasher();
            var            password    = objpassword.HashPassword(GenerateRandomPassword(10));
            var            user        = new InviteUserCommand()
            {
                AppartmentNumber = model.AppartmentNumber,
                ContactNumber1   = model.ContactNumber1,
                ContactNumber2   = model.ContactNumber2,
                FirstName        = model.FirstName,
                LastName         = model.LastName,
                MiddleName       = model.MiddleName,
                PasswordHash     = password,
                PrimaryEmail     = model.PrimaryEmail,
                RoleID           = model.RoleID,
                UserType         = model.UserType
            };

            return(Mediator.Execute(user).Result);
        }
        public ActionResult InviteStudent(int classroomId)
        {
            var inviteForm = new InviteUserModel()
            {
                ClassroomId = classroomId
            };

            return(View(inviteForm));
        }
Esempio n. 7
0
        public virtual ActionResult AddInvitedUser(InviteUserModel model)
        {
            if (model.UserId.HasValue || !model.InvitedUser.IsNullOrEmpty())
            {
                return(Json(new { Content = RenderPartialViewToString(MVC.Shared.Views.InvitedUser, model) }));
            }

            return(Json(null));
        }
        public async Task <IActionResult> InviteUser(InviteUserModel inviteUserModel)
        {
            var graphServiceClient = GraphServiceClientHelper.CreateGraphServiceClient();
            var invitation         = await graphServiceClient.Invitations.Request().AddAsync(new Invitation
            {
                InviteRedirectUrl       = "http://localhost:2509",
                InvitedUserDisplayName  = inviteUserModel.DisplayName,
                InvitedUserEmailAddress = inviteUserModel.EmailAddress,
                InvitedUserMessageInfo  = new InvitedUserMessageInfo
                {
                    CustomizedMessageBody = inviteUserModel.InviteMessage
                },
                SendInvitationMessage = inviteUserModel.SendInviteMessage
            });

            inviteUserModel.Status = invitation.Status;

            return(View(inviteUserModel));
        }
Esempio n. 9
0
        public async Task InviteUserAsync(InviteUserModel inviteUserModel)
        {
            var authorizedHttpClient = this.HttpClientService.CreateAuthorizedClient();
            var response             = await authorizedHttpClient.PostAsJsonAsync <InviteUserModel>(
                Constants.ApiRoutes.UserController.InviteUser, inviteUserModel);

            if (!response.IsSuccessStatusCode)
            {
                ProblemHttpResponse problemHttpResponse = await response.Content.ReadFromJsonAsync <ProblemHttpResponse>();

                if (problemHttpResponse != null)
                {
                    throw new CustomValidationException(problemHttpResponse.Detail);
                }
                else
                {
                    throw new CustomValidationException(response.ReasonPhrase);
                }
            }
        }
Esempio n. 10
0
        public async Task <IHttpActionResult> InviteAgain(InviteUserModel model)
        {
            try
            {
                if (string.IsNullOrEmpty(model.UserId))
                {
                    return(BadRequest(ResponseMessages.UserNotFound.ToDesc()));
                }

                var user = await _userRepository.GetById(model.UserId);

                if (user == null || user.IsActive)
                {
                    return(BadRequest(ResponseMessages.UserCannotBeInvited.ToDesc()));
                }

                var body = _emailTemplateRenderer.Render(EmailTemplateName.InviteUser, new
                {
                    ClientDomain = ConfigurationManager.AppSettings["ClientDomain"],
                });

                var sendEmailModel = new SendEmailModel
                {
                    Body    = body,
                    Subject = "You has been invited to monitorr.io",
                    Emails  = { user.Email }
                };

                await _emailSender.SendAsync(sendEmailModel);

                return(Ok(ResponseMessages.Ok.ToDesc()));
            }
            catch (Exception ex)
            {
                LogVerbose(ex);
            }
            return(InternalServerError());
        }
 public ActionResult InviteStudent(InviteUserModel model, string returnUrl)
 {
     try
     {
         var user = db.Users.FirstOrDefault(x => x.Email == model.Email);
         if (user != null)
         {
             var classroom = db.Classrooms.Include(x => x.Students)
                             .FirstOrDefault(x => x.Id == model.ClassroomId);
             if (classroom != null)
             {
                 classroom.Students.Add(user);
                 db.SaveChanges();
                 if (string.IsNullOrEmpty(returnUrl))
                 {
                     return(RedirectToAction("Index", "Home"));
                 }
                 return(Redirect(returnUrl));
             }
             else
             {
                 ModelState.AddModelError("", "Такого класса не существует!");
                 return(View(model));
             }
         }
         else
         {
             ModelState.AddModelError("", "Такого пользователя не существует!");
             return(View(model));
         }
     }
     catch (Exception e)
     {
         return(RedirectToAction("Index", "Error", new { error = e.Message }));
     }
 }
Esempio n. 12
0
        public ActionResult AddHouseholdMembers(List<HouseholdMemberModel> householdMembers)
        {
            ViewData["competed"] = true;

            string tempUrl = string.Empty;
            foreach (var member in householdMembers.Where(m => !string.IsNullOrEmpty(m.Email)))
            {
                // create invite additional members url
                var url = Url.Action("RegisterHouseholdMembers", "Account", new
                {
                    emailaddress = member.Email,
                    inviter = member.InviterName,
                    addressid = member.AddressId,
                    firstname = member.FirstName,
                    lastname = member.LastName
                }, Request.Url.Scheme);

                tempUrl = string.Format("{0} ... {1}", tempUrl, url);

                // Give them the Invite Member Bonus
                int numBonusPoints = Convert.ToInt16(ConfigurationManager.AppSettings["BonusPoints.InviteMember.Points"]);
                string descBonusPoints = Convert.ToString(ConfigurationManager.AppSettings["BonusPoints.InviteMember.Description"]);
                int? transactionTypeId = Convert.ToInt16(ConfigurationManager.AppSettings["TransactionType.ShareHeart"]);

                // email content
                if (User.Identity.IsAuthenticated)
                {
                    var membership = Membership.GetUser();
                    if (membership != null)
                    {
                        var userModel = new InviteUserModel
                        {
                            Email = member.Email,
                            FirstName = member.FirstName,
                            LastName = member.LastName,
                            User_Id = new Guid(member.InviterId)
                        };

                        InviteUserModel invited = new UserService().InviteHouseholdMembers(userModel, numBonusPoints, descBonusPoints, transactionTypeId);

                        //Send email to invite members to register
                        EmailService.SendEmailAdditionalMemberInvitation(member.Email, member.InviterName, url);
                    }

                    //return RedirectToAction("InviteFriends", new {urltemp = tempUrl}); TODO later
                    return RedirectToAction("MyProfile", "Account");
                }
            }

            //return RedirectToAction("InviteFriends");
            return RedirectToAction("MyProfile", "Account");
        }
Esempio n. 13
0
        public bool AdditionalUsersAjax(string email, string firstname, string lastname)
        {
            //TODO check model state etc.
            var currentUser = new UserService().GetUserById(new Guid(LayoutViewModel.ProviderUserKey));

            var isValid = !string.IsNullOrWhiteSpace(email) &&
                          !string.IsNullOrWhiteSpace(firstname) &&
                          !string.IsNullOrWhiteSpace(lastname);

            if (isValid)
            {

                // create invite additional members url
                var url = Url.Action("RegisterHouseholdMembers", "Account", new
                {
                    emailaddress = email,
                    inviter = currentUser.FirstName,
                    addressid = currentUser.AddressModel.Id,
                    firstname = firstname,
                    lastname = lastname
                }, Request.Url.Scheme);

                // email content

                var userModel = new InviteUserModel
                {
                    Email = email,
                    FirstName = firstname,
                    LastName = lastname,
                    User_Id = currentUser.Id
                };

                int numBonusPoints = Convert.ToInt16(ConfigurationManager.AppSettings["BonusPoints.InviteMember.Points"]);
                string descBonusPoints = Convert.ToString(ConfigurationManager.AppSettings["BonusPoints.InviteMember.Description"]);
                int? transactionTypeId = Convert.ToInt16(ConfigurationManager.AppSettings["TransactionType.ShareHeart"]);

                InviteUserModel invited = new UserService().InviteHouseholdMembers(userModel, numBonusPoints, descBonusPoints, transactionTypeId);

                //Send email to invite members to register
                EmailService.SendEmailAdditionalMemberInvitation(email, currentUser.FirstName, url);

                return true;
            }

            return false;
        }
Esempio n. 14
0
        public ActionResult AdditionalUsers(HouseholdMemberModel householdMemberModel)
        {
            LayoutViewModel.ActiveLink = Links.AccountAdditionalUsers;

            //TODO check model state etc.
            var currentUser = new UserService().GetUserById(new Guid(LayoutViewModel.ProviderUserKey));

            var isValid = !string.IsNullOrWhiteSpace(householdMemberModel.Email) &&
                          !string.IsNullOrWhiteSpace(householdMemberModel.ConfirmEmail) &&
                          !string.IsNullOrWhiteSpace(householdMemberModel.FirstName) &&
                          !string.IsNullOrWhiteSpace(householdMemberModel.LastName);

            if (isValid)
            {

                // create invite additional members url
                var url = Url.Action("RegisterHouseholdMembers", "Account", new
                {
                    emailaddress = householdMemberModel.Email,
                    inviter = currentUser.FirstName,
                    addressid = currentUser.AddressModel.Id,
                    firstname = householdMemberModel.FirstName,
                    lastname = householdMemberModel.LastName
                }, Request.Url.Scheme);

                // email content

                var userModel = new InviteUserModel
                {
                    Email = householdMemberModel.Email,
                    FirstName = householdMemberModel.FirstName,
                    LastName = householdMemberModel.LastName,
                    User_Id = currentUser.Id
                };

                // Give them the Invite Member Bonus
                int numBonusPoints = Convert.ToInt16(ConfigurationManager.AppSettings["BonusPoints.InviteMember.Points"]);
                string descBonusPoints = Convert.ToString(ConfigurationManager.AppSettings["BonusPoints.InviteMember.Description"]);
                int? transactionTypeId = Convert.ToInt16(ConfigurationManager.AppSettings["TransactionType.ShareHeart"]);

                InviteUserModel invited = new UserService().InviteHouseholdMembers(userModel, numBonusPoints, descBonusPoints, transactionTypeId);

                //Send email to invite members to register
                EmailService.SendEmailAdditionalMemberInvitation(householdMemberModel.Email, householdMemberModel.InviterName, url);

            }

            return RedirectToAction("AdditionalUsers");
        }
Esempio n. 15
0
        public InviteUserModel InviteHouseholdMembers(InviteUserModel userModel, int numBonusPoints, string descBonusPoints, int? transactionTypeId)
        {
            using (var context = new greenMoneyEntities())
            {
                Users1 inviterUser = context.Users1.FirstOrDefault(x => x.Id == userModel.User_Id);
                var user = new InvitedUsers
                {
                    FirstName = userModel.FirstName,
                    LastName = userModel.LastName,
                    Email = userModel.Email,
                    User_Id = userModel.User_Id
                };

                context.InvitedUsers.Add(user);
                AddPoints(context, inviterUser, numBonusPoints, descBonusPoints, transactionTypeId);

                context.SaveChanges();

                return userModel;
            }
        }
Esempio n. 16
0
 public InviteUserModel InviteHouseholdMembers(InviteUserModel userModel, int numBonusPoints, string descBonusPoints, int? transactionTypeId)
 {
     return new UserRepository().InviteHouseholdMembers(userModel, numBonusPoints, descBonusPoints, transactionTypeId);
 }
Esempio n. 17
0
        public async Task <HttpResponseMessage> Invite(InviteUserModel model, [FromUri] string redirectUrl = "")
        {
            if (!ModelState.IsValid)
            {
                return(InvalidModelState(ModelState));
            }

            var newUser = await UserManager.FindByEmailAsync(model.EmailAddress.Trim());

            var token = "";

            if (newUser != null)
            {
                token = await UserManager.GenerateEmailConfirmationTokenAsync(newUser.Id);

                SendInviteEmail(model.EmailAddress,
                                "",
                                newUser.Id,
                                token,
                                redirectUrl);

                // check if it is deleted
                var deletedUser = DB.Users.Where(a => a.Id == newUser.UserId && a.IsDeleted == true).FirstOrDefault();

                if (deletedUser != null)
                {
                    deletedUser.IsDeleted = false;
                    await DB.SaveChangesAsync();

                    if (UserManager.IsInRole(newUser.Id, this._roleAdmin))
                    {
                        UserManager.RemoveFromRole(newUser.Id, this._roleAdmin);
                    }

                    if (UserManager.IsInRole(newUser.Id, this._roleSuperAdmin))
                    {
                        UserManager.RemoveFromRole(newUser.Id, this._roleSuperAdmin);
                    }

                    UserManager.AddToRole(newUser.Id, this._roleUser);
                }
            }
            else
            {
                var user = new ApplicationUser()
                {
                    UserName = model.EmailAddress.Trim(), Email = model.EmailAddress.Trim()
                };

                var            generatedPass = Membership.GeneratePassword(8, 2);
                IdentityResult result        = UserManager.Create(user, generatedPass);

                var newAddedUser = await UserManager.FindByEmailAsync(model.EmailAddress.Trim());

                token = await UserManager.GenerateEmailConfirmationTokenAsync(newAddedUser.Id);

                SendInviteEmail(model.EmailAddress,
                                "",
                                newAddedUser.Id,
                                token,
                                redirectUrl,
                                generatedPass);

                UserManager.AddToRole(newAddedUser.Id, this._roleUser);
            }

            return(StatusOk());
        }
Esempio n. 18
0
        public async Task <ActionResult> Invite(InviteUserModel Model, int?CoLicense, int?CoProfile)
        {
            if (ModelState.IsValid)
            {
                var manager     = new UserManager <ApplicationUser>(new Microsoft.AspNet.Identity.EntityFramework.UserStore <ApplicationUser>(new ApplicationDbContext()));
                var currentUser = manager.FindById(User.Identity.GetUserId());
                var siteUserID  = currentUser.siteuserid;
                var siteCoID    = currentUser.sitecoid;

                using (ePontiv2Entities db = new ePontiv2Entities())
                    using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                    {
                        CommonRepository repo = new CommonRepository();
                        ViewBag.Licenses = new SelectList(db.GetLicensesBySiteCoID(siteCoID).ToList(), nameof(GetLicenseListBySiteCoID_Result.LicenseID), nameof(GetLicenseListBySiteCoID_Result.Version));
                        ViewBag.Profiles = new SelectList(db.GetProfilesBySiteCoID(siteCoID).ToList(), nameof(GetProfilesBySiteCoID_Result.ViewID), nameof(GetProfilesBySiteCoID_Result.Name));
                        string invitationCode = Guid.NewGuid().ToString("n") + Guid.NewGuid().ToString("n");
                        //db.InsertInviteeBySiteCoID(siteCoID, Model.FirstName, Model.LastName, CoProfile, Model.Email, Model.Phone, invitationCode, CoLicense);
                        //db.SaveChanges();
                        //ASP Net User
                        var user = new ApplicationUser
                        {
                            UserName    = Model.Email,
                            Email       = Model.Email,
                            PhoneNumber = Model.Phone,
                            sitecoid    = siteCoID
                        };

                        var userCreateStatus = await UserManager.CreateAsync(user);

                        if (userCreateStatus.Succeeded == false)
                        {
                            AddErrors(userCreateStatus);
                            return(View(Model));
                        }

                        //site user
                        var siteUser = new SiteUsers();
                        db.SiteUsers.Add(siteUser);

                        siteUser.ASPNetUserID    = user.Id;
                        siteUser.SiteCoID        = siteCoID;
                        siteUser.UserFirstName   = Model.FirstName;
                        siteUser.UserLastName    = Model.LastName;
                        siteUser.UserDisplayName = string.Format("{0} {1}", Model.FirstName, Model.LastName);
                        siteUser.UserStatus      = "Active";
                        siteUser.TimeZoneID      = 1;
                        db.SaveChanges();

                        var aspNetUser = db.AspNetUsers.Where(p => p.Id == user.Id).FirstOrDefault();
                        if (aspNetUser != null)
                        {
                            aspNetUser.siteuserid     = siteUser.SiteUserID;
                            aspNetUser.sitecoid       = siteUser.SiteCoID ?? 0;
                            aspNetUser.InvitationCode = invitationCode;

                            db.SaveChanges();
                        }
                        tran.Complete();

                        // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                        // Send an email with this link
                        // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                        try
                        {
                            var callbackUrl = Url.Action("Register", "Account", new { invitation = invitationCode }, protocol: Request.Url.Scheme);
                            //await UserManager.SendEmailAsync(user.Id, "You are invited", "Hi,<br>You are invited. Please accept the invitation by clicking <a href=\"" + callbackUrl + "\">here</a>");
                            await Mailer.Execute("You are invited", Model.Email, Model.FirstName + " " + Model.LastName, "Hi,<br>You are invited. Please accept the invitation by clicking <a href=\"" + callbackUrl + "\">here</a><br><br>Thanks.");

                            return(RedirectToAction("Login"));
                        }
                        catch (Exception ex)
                        {
                            LogRepository.LogException(ex);
                        }
                    }
                //invitation sent. reset model, so that new use can be invited
                Model = new InviteUserModel()
                {
                    IsInvitationSent = true
                };
                return(View(Model));
            }

            // If we got this far, something failed, redisplay form
            return(View(Model));
        }