private bool CheckValidName(string name, out object error)
        {
            error = null;

            if (string.IsNullOrEmpty(name = (name ?? "").Trim()))
            {
                error = new
                {
                    error   = new[] { "error" },
                    message = "name is required"
                };

                return(false);
            }

            if (!UserFormatter.IsValidUserName(name, string.Empty))
            {
                error = new
                {
                    error   = new[] { "error" },
                    message = "name is incorrect"
                };

                return(false);
            }

            return(true);
        }
        private UserInfo AddUser(UserInfo userInfo)
        {
            UserInfo newUserInfo;

            try
            {
                newUserInfo = userInfo.Clone() as UserInfo;

                if (newUserInfo == null)
                {
                    return(Constants.LostUser);
                }

                _log.DebugFormat("Adding or updating user in database, userId={0}", userInfo.ID);

                SecurityContext.CurrentAccount = ASC.Core.Configuration.Constants.CoreSystem;

                if (string.IsNullOrEmpty(newUserInfo.UserName))
                {
                    var limitExceeded = TenantStatisticsProvider.GetUsersCount() >= TenantExtra.GetTenantQuota().ActiveUsers;

                    newUserInfo = UserManagerWrapper.AddUser(newUserInfo, UserManagerWrapper.GeneratePassword(), true,
                                                             false, isVisitor: limitExceeded);
                }
                else
                {
                    if (!UserFormatter.IsValidUserName(userInfo.FirstName, userInfo.LastName))
                    {
                        throw new Exception(Resource.ErrorIncorrectUserName);
                    }

                    CoreContext.UserManager.SaveUserInfo(newUserInfo);
                }

                /*var photoUrl = samlResponse.GetRemotePhotoUrl();
                 * if (!string.IsNullOrEmpty(photoUrl))
                 * {
                 *  var photoLoader = new UserPhotoLoader();
                 *  photoLoader.SaveOrUpdatePhoto(photoUrl, userInfo.ID);
                 * }*/
            }
            finally
            {
                SecurityContext.Logout();
            }

            return(newUserInfo);
        }
Exemple #3
0
        public void RegisterTenant(TenantRegistrationInfo ri, out Tenant tenant)
        {
            if (ri == null)
            {
                throw new ArgumentNullException("registrationInfo");
            }
            if (string.IsNullOrEmpty(ri.Address))
            {
                throw new Exception("Address can not be empty");
            }

            if (string.IsNullOrEmpty(ri.Email))
            {
                throw new Exception("Account email can not be empty");
            }
            if (ri.FirstName == null)
            {
                throw new Exception("Account firstname can not be empty");
            }
            if (ri.LastName == null)
            {
                throw new Exception("Account lastname can not be empty");
            }
            if (!UserFormatter.IsValidUserName(ri.FirstName, ri.LastName))
            {
                throw new Exception("Incorrect firstname or lastname");
            }

            if (string.IsNullOrEmpty(ri.Password))
            {
                ri.Password = Crypto.GeneratePassword(6);
            }

            // create tenant
            tenant = new Tenant(ri.Address.ToLowerInvariant())
            {
                Name         = ri.Name,
                Language     = ri.Culture.Name,
                TimeZone     = ri.TimeZoneInfo,
                HostedRegion = ri.HostedRegion,
                PartnerId    = ri.PartnerId,
                AffiliateId  = ri.AffiliateId,
                Industry     = ri.Industry,
                Spam         = ri.Spam,
                Calls        = ri.Calls
            };

            tenant = tenantService.SaveTenant(tenant);

            // create user
            var user = new UserInfo
            {
                UserName         = ri.Email.Substring(0, ri.Email.IndexOf('@')),
                LastName         = ri.LastName,
                FirstName        = ri.FirstName,
                Email            = ri.Email,
                MobilePhone      = ri.MobilePhone,
                WorkFromDate     = TenantUtil.DateTimeNow(tenant.TimeZone),
                ActivationStatus = ri.ActivationStatus
            };

            user = userService.SaveUser(tenant.TenantId, user);
            userService.SetUserPassword(tenant.TenantId, user.ID, ri.Password);
            userService.SaveUserGroupRef(tenant.TenantId, new UserGroupRef(user.ID, Constants.GroupAdmin.ID, UserGroupRefType.Contains));

            // save tenant owner
            tenant.OwnerId = user.ID;
            tenant         = tenantService.SaveTenant(tenant);

            settingsManager.SaveSettings(new TenantAnalyticsSettings {
                Analytics = ri.Analytics
            }, tenant.TenantId);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            Page.RegisterBodyScripts("~/js/third-party/xregexp.js", "~/UserControls/Management/ConfirmInviteActivation/js/confirm_invite_activation.js")
            .RegisterStyle("~/UserControls/Management/ConfirmInviteActivation/css/confirm_invite_activation.less");

            var uid = Guid.Empty;

            try
            {
                uid = new Guid(Request["uid"]);
            }
            catch
            {
            }

            var email = GetEmailAddress();

            if (_type != ConfirmType.Activation && AccountLinkControl.IsNotEmpty && !CoreContext.Configuration.Personal)
            {
                var thrd = (AccountLinkControl)LoadControl(AccountLinkControl.Location);
                thrd.InviteView     = true;
                thrd.ClientCallback = "loginJoinCallback";
                thrdParty.Visible   = true;
                thrdParty.Controls.Add(thrd);
            }

            Page.Title = HeaderStringHelper.GetPageTitle(Resource.Authorization);

            UserInfo user;

            try
            {
                SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);

                user = CoreContext.UserManager.GetUserByEmail(email);
                var usr = CoreContext.UserManager.GetUsers(uid);
                if (usr.ID.Equals(Constants.LostUser.ID) || usr.ID.Equals(ASC.Core.Configuration.Constants.Guest.ID))
                {
                    usr = CoreContext.UserManager.GetUsers(CoreContext.TenantManager.GetCurrentTenant().OwnerId);
                }

                var photoData = UserPhotoManager.GetUserPhotoData(usr.ID, UserPhotoManager.MediumFotoSize);

                _userAvatar = photoData == null?usr.GetMediumPhotoURL() : "data:image/png;base64," + Convert.ToBase64String(photoData);

                _userName = usr.DisplayUserName(true);
                _userPost = (usr.Title ?? "").HtmlEncode();
            }
            finally
            {
                SecurityContext.Logout();
            }

            if (_type == ConfirmType.LinkInvite || _type == ConfirmType.EmpInvite)
            {
                if (TenantStatisticsProvider.GetUsersCount() >= TenantExtra.GetTenantQuota().ActiveUsers&& _employeeType == EmployeeType.User)
                {
                    ShowError(UserControlsCommonResource.TariffUserLimitReason);
                    return;
                }

                if (!user.ID.Equals(Constants.LostUser.ID))
                {
                    ShowError(CustomNamingPeople.Substitute <Resource>("ErrorEmailAlreadyExists"));
                    return;
                }
            }

            else if (_type == ConfirmType.Activation)
            {
                if (user.IsActive)
                {
                    Response.Redirect(CommonLinkUtility.GetDefault());
                    return;
                }

                if (user.ID.Equals(Constants.LostUser.ID) || user.Status == EmployeeStatus.Terminated)
                {
                    ShowError(string.Format(Resource.ErrorUserNotFoundByEmail, email));
                    return;
                }
            }

            var tenant = CoreContext.TenantManager.GetCurrentTenant();

            if (tenant != null)
            {
                var settings = IPRestrictionsSettings.Load();
                if (settings.Enable && !IPSecurity.IPSecurity.Verify(tenant))
                {
                    ShowError(Resource.ErrorAccessRestricted);
                    return;
                }
            }

            if (!IsPostBack)
            {
                return;
            }

            var firstName = GetFirstName();
            var lastName  = GetLastName();

            var          passwordHash       = (Request["passwordHash"] ?? "").Trim();
            var          analytics          = (Request["analytics"] ?? "").Trim() == "True";
            var          mustChangePassword = false;
            LoginProfile thirdPartyProfile;

            //thirdPartyLogin confirmInvite
            if (Request["__EVENTTARGET"] == "thirdPartyLogin")
            {
                var valueRequest = Request["__EVENTARGUMENT"];
                thirdPartyProfile = new LoginProfile(valueRequest);

                if (!string.IsNullOrEmpty(thirdPartyProfile.AuthorizationError))
                {
                    // ignore cancellation
                    if (thirdPartyProfile.AuthorizationError != "Canceled at provider")
                    {
                        ShowError(HttpUtility.HtmlEncode(thirdPartyProfile.AuthorizationError));
                    }
                    return;
                }

                if (string.IsNullOrEmpty(thirdPartyProfile.EMail))
                {
                    ShowError(HttpUtility.HtmlEncode(Resource.ErrorNotCorrectEmail));
                    return;
                }
            }

            if (Request["__EVENTTARGET"] == "confirmInvite")
            {
                if (String.IsNullOrEmpty(email))
                {
                    _errorMessage = Resource.ErrorEmptyUserEmail;
                    return;
                }

                if (!email.TestEmailRegex())
                {
                    _errorMessage = Resource.ErrorNotCorrectEmail;
                    return;
                }

                if (String.IsNullOrEmpty(firstName))
                {
                    _errorMessage = Resource.ErrorEmptyUserFirstName;
                    return;
                }

                if (String.IsNullOrEmpty(lastName))
                {
                    _errorMessage = Resource.ErrorEmptyUserLastName;
                    return;
                }

                if (String.IsNullOrEmpty(passwordHash))
                {
                    _errorMessage = Resource.ErrorPasswordEmpty;
                    return;
                }
            }
            var userID = Guid.Empty;

            try
            {
                SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
                if (_type == ConfirmType.EmpInvite || _type == ConfirmType.LinkInvite)
                {
                    if (TenantStatisticsProvider.GetUsersCount() >= TenantExtra.GetTenantQuota().ActiveUsers&& _employeeType == EmployeeType.User)
                    {
                        ShowError(UserControlsCommonResource.TariffUserLimitReason);
                        return;
                    }

                    UserInfo newUser;
                    if (Request["__EVENTTARGET"] == "confirmInvite")
                    {
                        var fromInviteLink = _type == ConfirmType.LinkInvite;
                        newUser = CreateNewUser(firstName, lastName, email, passwordHash, _employeeType, fromInviteLink);

                        var messageAction = _employeeType == EmployeeType.User ? MessageAction.UserCreatedViaInvite : MessageAction.GuestCreatedViaInvite;
                        MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, messageAction, MessageTarget.Create(newUser.ID), newUser.DisplayUserName(false));

                        userID = newUser.ID;

                        var settings = TenantAnalyticsSettings.LoadForCurrentUser();
                        settings.Analytics = analytics;

                        settings.SaveForCurrentUser();
                    }

                    if (Request["__EVENTTARGET"] == "thirdPartyLogin")
                    {
                        if (String.IsNullOrEmpty(passwordHash))
                        {
                            passwordHash       = UserManagerWrapper.GeneratePassword();
                            mustChangePassword = true;
                        }

                        var valueRequest = Request["__EVENTARGUMENT"];
                        thirdPartyProfile = new LoginProfile(valueRequest);
                        newUser           = CreateNewUser(GetFirstName(thirdPartyProfile), GetLastName(thirdPartyProfile), GetEmailAddress(thirdPartyProfile), passwordHash, _employeeType, false);

                        var messageAction = _employeeType == EmployeeType.User ? MessageAction.UserCreatedViaInvite : MessageAction.GuestCreatedViaInvite;
                        MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, messageAction, MessageTarget.Create(newUser.ID), newUser.DisplayUserName(false));

                        userID = newUser.ID;
                        if (!String.IsNullOrEmpty(thirdPartyProfile.Avatar))
                        {
                            SaveContactImage(userID, thirdPartyProfile.Avatar);
                        }

                        var linker = new AccountLinker("webstudio");
                        linker.AddLink(userID.ToString(), thirdPartyProfile);
                    }
                }
                else if (_type == ConfirmType.Activation)
                {
                    if (!UserFormatter.IsValidUserName(firstName, lastName))
                    {
                        throw new Exception(Resource.ErrorIncorrectUserName);
                    }

                    SecurityContext.SetUserPasswordHash(user.ID, passwordHash);

                    user.ActivationStatus = EmployeeActivationStatus.Activated;
                    user.FirstName        = firstName;
                    user.LastName         = lastName;
                    CoreContext.UserManager.SaveUserInfo(user);

                    userID = user.ID;

                    //notify
                    if (user.IsVisitor())
                    {
                        StudioNotifyService.Instance.GuestInfoAddedAfterInvite(user);
                        MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, MessageAction.GuestActivated, MessageTarget.Create(user.ID), user.DisplayUserName(false));
                    }
                    else
                    {
                        StudioNotifyService.Instance.UserInfoAddedAfterInvite(user);
                        MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, MessageAction.UserActivated, MessageTarget.Create(user.ID), user.DisplayUserName(false));
                    }
                }
            }
            catch (SecurityContext.PasswordException)
            {
                _errorMessage = HttpUtility.HtmlEncode(Resource.ErrorPasswordRechange);
                return;
            }
            catch (Exception exception)
            {
                _errorMessage = HttpUtility.HtmlEncode(exception.Message);
                return;
            }
            finally
            {
                SecurityContext.Logout();
            }

            user = CoreContext.UserManager.GetUsers(userID);
            try
            {
                var cookiesKey = SecurityContext.AuthenticateMe(user.Email, passwordHash);
                CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey);
                MessageService.Send(HttpContext.Current.Request, MessageAction.LoginSuccess);
                StudioNotifyService.Instance.UserHasJoin();

                if (mustChangePassword)
                {
                    StudioNotifyService.Instance.UserPasswordChange(user);
                }
            }
            catch (Exception exception)
            {
                (Page as Confirm).ErrorMessage = HttpUtility.HtmlEncode(exception.Message);
                return;
            }

            UserHelpTourHelper.IsNewUser = true;
            if (CoreContext.Configuration.Personal)
            {
                PersonalSettings.IsNewUser = true;
            }
            Response.Redirect(CommonLinkUtility.GetDefault());
        }
        public static UserInfo AddUser(UserInfo userInfo, string password, bool afterInvite = false, bool notify = true, bool isVisitor = false, bool fromInviteLink = false, bool makeUniqueName = true)
        {
            if (userInfo == null)
            {
                throw new ArgumentNullException("userInfo");
            }

            if (!UserFormatter.IsValidUserName(userInfo.FirstName, userInfo.LastName))
            {
                throw new Exception(Resource.ErrorIncorrectUserName);
            }

            CheckPasswordPolicy(password);

            if (!CheckUniqueEmail(userInfo.ID, userInfo.Email))
            {
                throw new Exception(CustomNamingPeople.Substitute <Resource>("ErrorEmailAlreadyExists"));
            }
            if (makeUniqueName)
            {
                userInfo.UserName = MakeUniqueName(userInfo);
            }
            if (!userInfo.WorkFromDate.HasValue)
            {
                userInfo.WorkFromDate = TenantUtil.DateTimeNow();
            }

            if (!CoreContext.Configuration.Personal && !fromInviteLink)
            {
                userInfo.ActivationStatus = !afterInvite ? EmployeeActivationStatus.Pending : EmployeeActivationStatus.Activated;
            }

            var newUserInfo = CoreContext.UserManager.SaveUserInfo(userInfo, isVisitor);

            SecurityContext.SetUserPassword(newUserInfo.ID, password);

            if (CoreContext.Configuration.Personal)
            {
                StudioNotifyService.Instance.SendUserWelcomePersonal(newUserInfo);
                return(newUserInfo);
            }

            if ((newUserInfo.Status & EmployeeStatus.Active) == EmployeeStatus.Active && notify)
            {
                //NOTE: Notify user only if it's active
                if (afterInvite)
                {
                    if (isVisitor)
                    {
                        StudioNotifyService.Instance.GuestInfoAddedAfterInvite(newUserInfo);
                    }
                    else
                    {
                        StudioNotifyService.Instance.UserInfoAddedAfterInvite(newUserInfo);
                    }

                    if (fromInviteLink)
                    {
                        StudioNotifyService.Instance.SendEmailActivationInstructions(newUserInfo, newUserInfo.Email);
                    }
                }
                else
                {
                    //Send user invite
                    if (isVisitor)
                    {
                        StudioNotifyService.Instance.GuestInfoActivation(newUserInfo);
                    }
                    else
                    {
                        StudioNotifyService.Instance.UserInfoActivation(newUserInfo);
                    }
                }
            }

            if (isVisitor)
            {
                CoreContext.UserManager.AddUserIntoGroup(newUserInfo.ID, ASC.Core.Users.Constants.GroupVisitor.ID);
            }

            return(newUserInfo);
        }