コード例 #1
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Page.RegisterBodyScripts("~/usercontrols/management/confirminviteactivation/js/confirm_invite_activation.js");

            Page.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(ASC.Core.Users.Constants.LostUser.ID) || usr.ID.Equals(ASC.Core.Configuration.Constants.Guest.ID))
                {
                    usr = CoreContext.UserManager.GetUsers(CoreContext.TenantManager.GetCurrentTenant().OwnerId);
                }

                _userAvatar = usr.GetMediumPhotoURL();
                _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(ASC.Core.Users.Constants.LostUser.ID))
                {
                    ShowError(CustomNamingPeople.Substitute <Resource>("ErrorEmailAlreadyExists"));
                    return;
                }
            }

            else if (_type == ConfirmType.Activation)
            {
                if (user.IsActive)
                {
                    ShowError(Resource.ErrorConfirmURLError);
                    return;
                }

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

            var tenant = CoreContext.TenantManager.GetCurrentTenant();

            if (tenant != null)
            {
                var settings = SettingsManager.Instance.LoadSettings <IPRestrictionsSettings>(tenant.TenantId);
                if (settings.Enable && !IPSecurity.IPSecurity.Verify(tenant.TenantId))
                {
                    ShowError(Resource.ErrorAccessRestricted);
                    return;
                }
            }

            if (!IsPostBack)
            {
                return;
            }

            var          firstName          = GetFirstName();
            var          lastName           = GetLastName();
            var          pwd                = (Request["pwdInput"] ?? "").Trim();
            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;
                }

                var checkPassResult = CheckPassword(pwd);
                if (!String.IsNullOrEmpty(checkPassResult))
                {
                    _errorMessage = checkPassResult;
                    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, pwd, _employeeType, fromInviteLink);

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

                        userID = newUser.ID;
                    }

                    if (Request["__EVENTTARGET"] == "thirdPartyLogin")
                    {
                        if (!String.IsNullOrEmpty(CheckPassword(pwd)))
                        {
                            pwd = UserManagerWrapper.GeneratePassword();
                            mustChangePassword = true;
                        }
                        var valueRequest = Request["__EVENTARGUMENT"];
                        thirdPartyProfile = new LoginProfile(valueRequest);
                        newUser           = CreateNewUser(GetFirstName(thirdPartyProfile), GetLastName(thirdPartyProfile), GetEmailAddress(thirdPartyProfile), pwd, _employeeType, false);

                        var messageAction = _employeeType == EmployeeType.User ? MessageAction.UserCreatedViaInvite : MessageAction.GuestCreatedViaInvite;
                        MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, messageAction, 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)
                {
                    user.ActivationStatus = EmployeeActivationStatus.Activated;
                    user.FirstName        = firstName;
                    user.LastName         = lastName;
                    CoreContext.UserManager.SaveUserInfo(user);
                    SecurityContext.SetUserPassword(user.ID, pwd);

                    userID = user.ID;

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

            user = CoreContext.UserManager.GetUsers(userID);
            try
            {
                var cookiesKey = SecurityContext.AuthenticateMe(user.Email, pwd);
                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("~/");
        }
コード例 #2
0
        public object SaveUsers(string userList, bool importUsersAsCollaborators)
        {
            if (!SecurityContext.CheckPermissions(Constants.Action_AddRemoveUser))
            {
                return new { Status = (int)Operation.Error, Message = Resources.Resource.ErrorAccessDenied }
            }
            ;

            var coll = new List <UserResults>();

            try
            {
                var jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();

                var ruleObj = jsSerializer.Deserialize <List <UserData> >(userList);
                var error   = 0;

                foreach (var userData in ruleObj)
                {
                    var validateEmail = UserManagerWrapper.ValidateEmail(userData.Email);
                    if (!validateEmail || String.IsNullOrEmpty(userData.FirstName) || String.IsNullOrEmpty(userData.LastName))
                    {
                        coll.Add(new UserResults
                        {
                            Email  = userData.Email,
                            Result = Resources.Resource.ImportContactsIncorrectFields,
                            Class  = !validateEmail ? "error3" : "error1"
                        });
                        error++;
                        continue;
                    }

                    var us = CoreContext.UserManager.GetUserByEmail(userData.Email);

                    if (us.ID != Constants.LostUser.ID)
                    {
                        coll.Add(new UserResults
                        {
                            Email  = userData.Email,
                            Result = Resources.Resource.ImportContactsAlreadyExists,
                            Class  = "error2"
                        });
                        error++;
                        continue;
                    }

                    if (error != 0)
                    {
                        continue;
                    }

                    if (!importUsersAsCollaborators && TenantStatisticsProvider.GetUsersCount() >= TenantExtra.GetTenantQuota().ActiveUsers)
                    {
                        importUsersAsCollaborators = true;
                    }

                    UserManagerWrapper.AddUser(new UserInfo
                    {
                        Email     = userData.Email,
                        FirstName = userData.FirstName,
                        LastName  = userData.LastName
                    }, UserManagerWrapper.GeneratePassword(), false, true, importUsersAsCollaborators);
                    coll.Add(new UserResults {
                        Email = userData.Email, Result = String.Empty
                    });
                }
                return(new { Status = (int)Operation.Success, Data = coll });
            }
            catch (Exception ex)
            {
                return(new { Status = (int)Operation.Error, Message = ex.Message });
            }
        }
コード例 #3
0
        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.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);

                if (string.IsNullOrEmpty(newUserInfo.UserName))
                {
                    if (string.IsNullOrWhiteSpace(newUserInfo.FirstName))
                    {
                        newUserInfo.FirstName = Resource.FirstName;
                    }

                    if (string.IsNullOrWhiteSpace(newUserInfo.LastName))
                    {
                        newUserInfo.LastName = Resource.LastName;
                    }

                    if (TenantStatisticsProvider.GetUsersCount() < TenantExtra.GetTenantQuota().ActiveUsers)
                    {
                        newUserInfo = UserManagerWrapper.AddUser(newUserInfo, UserManagerWrapper.GeneratePassword(), true,
                                                                 false);
                    }
                    else
                    {
                        newUserInfo = UserManagerWrapper.AddUser(newUserInfo, UserManagerWrapper.GeneratePassword(), true,
                                                                 false, true);
                    }
                }
                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);
        }
コード例 #4
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "confirm_invite_activation_style", "<link rel=\"stylesheet\" type=\"text/css\" href=\"" + WebSkin.GetUserSkin().GetAbsoluteWebPath("usercontrols/management/confirminviteactivation/css/<theme_folder>/confirm_invite_activation.css") + "\">", false);
            Page.ClientScript.RegisterClientScriptInclude(typeof(string), "confirm_invite_activation_script", WebPath.GetPath("usercontrols/management/confirminviteactivation/js/confirm_invite_activation.js"));

            _tenantInfoSettings = SettingsManager.Instance.LoadSettings <TenantInfoSettings>(TenantProvider.CurrentTenantID);

            Guid uid = Guid.Empty;

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

            var type = typeof(ConfirmType).TryParseEnum(Request["type"] ?? "", ConfirmType.EmpInvite);

            var email = GetEmailAddress();
            var key   = Request["key"] ?? "";
            var fap   = Request["fap"] ?? "";

            //if (!string.IsNullOrEmpty(_email))
            //{
            //var thrd = LoadControl(AccountLinkControl.Location) as AccountLinkControl;
            //thrd.InviteView = true;
            //thrd.ClientCallback = "loginJoinCallback";
            //thrdParty.Controls.Add(thrd);
            //}
            Page.Title = HeaderStringHelper.GetPageTitle(Resources.Resource.Authorization, null, null);

            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(ASC.Core.Users.Constants.LostUser.ID) || usr.ID.Equals(ASC.Core.Configuration.Constants.Guest.ID))
                {
                    usr = CoreContext.UserManager.GetUsers(CoreContext.TenantManager.GetCurrentTenant().OwnerId);
                }

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

            if (type == ConfirmType.LinkInvite || type == ConfirmType.EmpInvite)
            {
                if (!user.ID.Equals(ASC.Core.Users.Constants.LostUser.ID))
                {
                    ShowError(CustomNamingPeople.Substitute <Resources.Resource>("ErrorEmailAlreadyExists"));
                    return;
                }
            }

            else if (type == ConfirmType.Activation)
            {
                if (user.IsActive)
                {
                    ShowError(Resources.Resource.ErrorConfirmURLError);
                    return;
                }

                if (user.ID.Equals(ASC.Core.Users.Constants.LostUser.ID))
                {
                    ShowError(string.Format(Resources.Resource.ErrorUserNotFoundByEmail, email));
                    return;
                }
            }

            if (!IsPostBack)
            {
                return;
            }

            var          firstName = GetFirstName();
            var          lastName  = GetLastName();
            var          pwd       = (Request["pwdInput"] ?? "").Trim();
            var          repwd     = (Request["repwdInput"] ?? "").Trim();
            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(Resources.Resource.ErrorNotCorrectEmail));
                    return;
                }
            }

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

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

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

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

                var checkPassResult = CheckPassword(pwd, repwd);
                if (!String.IsNullOrEmpty(checkPassResult))
                {
                    _errorMessage = checkPassResult;
                    return;
                }
            }
            var userID = Guid.Empty;

            try
            {
                SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
                if (type == ConfirmType.EmpInvite || type == ConfirmType.LinkInvite)
                {
                    UserInfo newUser;
                    if (Request["__EVENTTARGET"] == "confirmInvite")
                    {
                        newUser = CreateNewUser(firstName, lastName, email, pwd);
                        userID  = newUser.ID;
                    }

                    if (Request["__EVENTTARGET"] == "thirdPartyLogin")
                    {
                        if (!String.IsNullOrEmpty(CheckPassword(pwd, repwd)))
                        {
                            pwd = UserManagerWrapper.GeneratePassword();
                        }
                        var valueRequest = Request["__EVENTARGUMENT"];
                        thirdPartyProfile = new LoginProfile(valueRequest);
                        newUser           = CreateNewUser(GetFirstName(thirdPartyProfile), GetLastName(thirdPartyProfile), GetEmailAddress(thirdPartyProfile), pwd);
                        userID            = newUser.ID;

                        var linker = new AccountLinker(WebConfigurationManager.ConnectionStrings["webstudio"]);
                        linker.AddLink(userID.ToString(), thirdPartyProfile);
                    }

                    #region Department

                    try
                    {
                        var deptID = new Guid((Request["deptID"] ?? "").Trim());
                        CoreContext.UserManager.AddUserIntoGroup(userID, deptID);
                    }
                    catch
                    {
                    }

                    #endregion
                }
                else if (type == ConfirmType.Activation)
                {
                    user.ActivationStatus = EmployeeActivationStatus.Activated;
                    user.FirstName        = firstName;
                    user.LastName         = lastName;
                    CoreContext.UserManager.SaveUserInfo(user);
                    SecurityContext.SetUserPassword(user.ID, pwd);

                    userID = user.ID;

                    //notify
                    StudioNotifyService.Instance.UserInfoAddedAfterInvite(user, pwd);
                }

                if (String.Equals(fap, "1"))
                {
                    CoreContext.UserManager.AddUserIntoGroup(userID, ASC.Core.Users.Constants.GroupAdmin.ID);
                }
            }
            catch (Exception exception)
            {
                (Page as confirm).ErrorMessage = HttpUtility.HtmlEncode(exception.Message);
                return;
            }
            finally
            {
                SecurityContext.Logout();
            }

            try
            {
                var cookiesKey = SecurityContext.AuthenticateMe(userID.ToString(), pwd);
                CookiesManager.SetCookies(CookiesType.UserID, userID.ToString());
                CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey);
                StudioNotifyService.Instance.UserHasJoin();
            }
            catch (Exception exception)
            {
                (Page as confirm).ErrorMessage = HttpUtility.HtmlEncode(exception.Message);
                return;
            }

            UserOnlineManager.Instance.RegistryOnlineUser(SecurityContext.CurrentAccount.ID);
            WebItemManager.Instance.ItemGlobalHandlers.Login(SecurityContext.CurrentAccount.ID);
            var smsAuthSettings = SettingsManager.Instance.LoadSettings <StudioSmsNotificationSettings>(TenantProvider.CurrentTenantID);
            if (smsAuthSettings.Enable)
            {
                var uData = new UserTransferData();
                var usr   = CoreContext.UserManager.GetUsers(userID);
                uData.Login  = usr.Email;
                uData.UserId = userID;
                Session["UserTransferData"] = uData;
            }

            Response.Redirect("~/");
        }
コード例 #5
0
        public string GetRandomPassword()
        {
            var password = UserManagerWrapper.GeneratePassword();

            return(password);
        }
コード例 #6
0
            public void RunJob()
            {
                Status = (int)Operation.Success;
                CoreContext.TenantManager.SetCurrentTenant((int)Id);
                SecurityContext.AuthenticateMe(UserId);

                if (!SecurityContext.CheckPermissions(Constants.Action_AddRemoveUser))
                {
                    Error       = Resource.ErrorAccessDenied;
                    IsCompleted = true;
                    return;
                }

                try
                {
                    var jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                    var ruleObj      = jsSerializer.Deserialize <List <UserData> >(userList);
                    var error        = 0;

                    var percentStep = 100.0 / ruleObj.Count;
                    foreach (var userData in ruleObj)
                    {
                        var validateEmail = UserManagerWrapper.ValidateEmail(userData.Email);
                        if (!validateEmail || String.IsNullOrEmpty(userData.FirstName) || String.IsNullOrEmpty(userData.LastName))
                        {
                            Data.Add(new UserResults
                            {
                                Email  = userData.Email,
                                Result = Resource.ImportContactsIncorrectFields,
                                Class  = !validateEmail ? "error3" : "error1"
                            });
                            error++;
                            Percentage += percentStep;
                            continue;
                        }

                        var us = CoreContext.UserManager.GetUserByEmail(userData.Email);

                        if (us.ID != Constants.LostUser.ID)
                        {
                            Data.Add(new UserResults
                            {
                                Email  = userData.Email,
                                Result = CustomNamingPeople.Substitute <Resource>("ImportContactsAlreadyExists"),
                                Class  = "error2"
                            });
                            error++;
                            Percentage += percentStep;
                            continue;
                        }

                        if (!importUsersAsCollaborators && TenantStatisticsProvider.GetUsersCount() >= TenantExtra.GetTenantQuota().ActiveUsers)
                        {
                            importUsersAsCollaborators = true;
                        }

                        var userInfo = new UserInfo
                        {
                            Email     = userData.Email,
                            FirstName = userData.FirstName,
                            LastName  = userData.LastName
                        };
                        UserManagerWrapper.AddUser(userInfo, UserManagerWrapper.GeneratePassword(), false, true, importUsersAsCollaborators);

                        var messageAction = importUsersAsCollaborators ? MessageAction.GuestImported : MessageAction.UserImported;
                        MessageService.Send(httpHeaders, messageAction, userInfo.DisplayUserName(false));

                        Data.Add(new UserResults {
                            Email = userData.Email, Result = String.Empty
                        });
                        Percentage += percentStep;
                    }
                }
                catch (Exception ex)
                {
                    Status = (int)Operation.Error;
                    Error  = ex.Message;
                }

                IsCompleted = true;
            }
コード例 #7
0
        private void SaveUsers(IBaseCamp basecampManager)
        {
            var employees = basecampManager.People;
            var step      = 100.0 / employees.Count();

            foreach (var person in employees)
            {
                try
                {
                    if (TenantExtra.GetRemainingCountUsers() <= 0)
                    {
                        _importUsersOverLimitAsCollaborators = true;
                    }

                    StatusState.StatusUserProgress(step);
                    var userID = FindUserByEmail(person.EmailAddress);

                    if (userID.Equals(Guid.Empty))
                    {
                        var userName = Regex.Replace(person.UserName, @"[!|@|#|$|%|'|+]", "");
                        var name     = userName.Split(' ');
                        var userInfo = new UserInfo
                        {
                            Email     = person.EmailAddress,
                            FirstName = name.First(),
                            LastName  = name.Count() > 1 ? name.Last() : "",
                            UserName  = userName,
                            Status    = EmployeeStatus.Active,
                        };
                        var collaboratorFlag = _importUsersOverLimitAsCollaborators || _importUsersAsCollaborators;

                        if (!UserManagerWrapper.ValidateEmail(userInfo.Email))
                        {
                            throw new Exception("Invalid email");
                        }

                        var newUserInfo = UserManagerWrapper.AddUser(userInfo, UserManagerWrapper.GeneratePassword(), false, !_disableNotifications, collaboratorFlag);
                        _newUsersID.Add(new UserIDWrapper {
                            InBasecamp = person.ID, InProjects = newUserInfo.ID
                        });

                        //save user avatar
                        const string emptyAvatar = "http://asset0.37img.com/global/default_avatar_v1_4/avatar.gif?r=3";
                        if (person.AvatarUrl != emptyAvatar)
                        {
                            UserPhotoManager.SaveOrUpdatePhoto(newUserInfo.ID, StreamFile(person.AvatarUrl));
                        }
                    }
                    else
                    {
                        _newUsersID.Add(new UserIDWrapper {
                            InBasecamp = person.ID, InProjects = userID
                        });
                    }
                }
                catch (Exception e)
                {
                    StatusState.StatusLogError(string.Format(ImportResource.FailedToSaveUser, person.EmailAddress), e);
                    LogError(string.Format("user '{0}' failed", person.EmailAddress), e);
                    _newUsersID.RemoveAll(x => x.InBasecamp == person.ID);
                }
            }
        }
コード例 #8
0
        public void RunJob()
        {
            Status = (int)Operation.Success;
            CoreContext.TenantManager.SetCurrentTenant((int)Id);
            SecurityContext.AuthenticateMe(UserId);

            if (!SecurityContext.CheckPermissions(Constants.Action_AddRemoveUser))
            {
                Error       = Resource.ErrorAccessDenied;
                IsCompleted = true;
                return;
            }

            try
            {
                var     jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                var     ruleObj      = jsSerializer.Deserialize <List <UserData> >(userList);
                var     error        = 0;
                Address address;
                GetUserCounter = ruleObj.Count;

                foreach (var userData in ruleObj)
                {
                    var isGuest      = userData.Status == EmployeeType.All ? importUsersAsCollaborators : userData.Status == EmployeeType.Visitor;
                    var isValidEmail = Parser.TryParseAddress(userData.Email, out address);

                    if (!isValidEmail || String.IsNullOrEmpty(userData.FirstName) || String.IsNullOrEmpty(userData.LastName))
                    {
                        Data.Add(new UserResults
                        {
                            Email  = userData.Email,
                            Result = Resource.ImportContactsIncorrectFields,
                            Class  = !isValidEmail ? "error3" : "error1"
                        });
                        error++;
                        Percentage++;
                        continue;
                    }

                    var us = CoreContext.UserManager.GetUserByEmail(userData.Email);

                    if (us.ID != Constants.LostUser.ID)
                    {
                        Data.Add(new UserResults
                        {
                            Email  = userData.Email,
                            Result = CustomNamingPeople.Substitute <Resource>("ImportContactsAlreadyExists"),
                            Class  = "error2"
                        });
                        error++;
                        Percentage++;
                        continue;
                    }

                    if (isGuest && !(CoreContext.Configuration.Standalone || CoreContext.UserManager.GetUsersByGroup(Constants.GroupVisitor.ID).Length < Constants.CoefficientOfVisitors * TenantExtra.GetTenantQuota().ActiveUsers))
                    {
                        break;
                    }

                    var userInfo = new UserInfo
                    {
                        Email     = userData.Email,
                        FirstName = userData.FirstName,
                        LastName  = userData.LastName
                    };

                    UserManagerWrapper.AddUser(userInfo, UserManagerWrapper.GeneratePassword(), false, true, isGuest);

                    var messageAction = isGuest ? MessageAction.GuestImported : MessageAction.UserImported;
                    MessageService.Send(httpHeaders, messageAction, MessageTarget.Create(userInfo.ID), string.Format("{0} ({1})", userInfo.DisplayUserName(false), userInfo.Email));

                    Data.Add(new UserResults {
                        Email = userData.Email, Result = String.Empty
                    });
                    Percentage++;
                }
            }
            catch (Exception ex)
            {
                Status = (int)Operation.Error;
                Error  = ex.Message;
            }

            IsCompleted = true;
        }
コード例 #9
0
        public WizardSettings SaveData(WizardModel wizardModel)
        {
            try
            {
                var(email, passwordHash, lng, timeZone, promocode, amiid, subscribeFromSite) = wizardModel;

                var tenant   = TenantManager.GetCurrentTenant();
                var settings = SettingsManager.Load <WizardSettings>();
                if (settings.Completed)
                {
                    throw new Exception("Wizard passed.");
                }

                if (!string.IsNullOrEmpty(SetupInfo.AmiMetaUrl) && IncorrectAmiId(amiid))
                {
                    //throw new Exception(Resource.EmailAndPasswordIncorrectAmiId); TODO
                }

                if (tenant.OwnerId == Guid.Empty)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(6)); // wait cache interval
                    tenant = TenantManager.GetTenant(tenant.TenantId);
                    if (tenant.OwnerId == Guid.Empty)
                    {
                        Log.Error(tenant.TenantId + ": owner id is empty.");
                    }
                }

                var currentUser = UserManager.GetUsers(TenantManager.GetCurrentTenant().OwnerId);

                if (!UserManagerWrapper.ValidateEmail(email))
                {
                    throw new Exception(Resource.EmailAndPasswordIncorrectEmail);
                }

                if (string.IsNullOrEmpty(passwordHash))
                {
                    throw new Exception(Resource.ErrorPasswordEmpty);
                }

                SecurityContext.SetUserPasswordHash(currentUser.ID, passwordHash);

                email = email.Trim();
                if (currentUser.Email != email)
                {
                    currentUser.Email            = email;
                    currentUser.ActivationStatus = EmployeeActivationStatus.NotActivated;
                }
                UserManager.SaveUserInfo(currentUser);

                if (!string.IsNullOrWhiteSpace(promocode))
                {
                    try
                    {
                        PaymentManager.ActivateKey(promocode);
                    }
                    catch (Exception err)
                    {
                        Log.Error("Incorrect Promo: " + promocode, err);
                        throw new Exception(Resource.EmailAndPasswordIncorrectPromocode);
                    }
                }

                if (RequestLicense)
                {
                    TariffSettings.SetLicenseAccept(SettingsManager);
                    MessageService.Send(MessageAction.LicenseKeyUploaded);

                    LicenseReader.RefreshLicense();
                }

                settings.Completed = true;
                SettingsManager.Save(settings);

                TrySetLanguage(tenant, lng);

                tenant.TimeZone = TimeZoneConverter.GetTimeZone(timeZone).Id;

                TenantManager.SaveTenant(tenant);

                StudioNotifyService.SendCongratulations(currentUser);
                StudioNotifyService.SendRegData(currentUser);

                if (subscribeFromSite && TenantExtra.Opensource && !CoreBaseSettings.CustomMode)
                {
                    SubscribeFromSite(currentUser);
                }

                return(settings);
            }
            catch (BillingNotFoundException)
            {
                throw new Exception(UserControlsCommonResource.LicenseKeyNotFound);
            }
            catch (BillingNotConfiguredException)
            {
                throw new Exception(UserControlsCommonResource.LicenseKeyNotCorrect);
            }
            catch (BillingException)
            {
                throw new Exception(UserControlsCommonResource.LicenseException);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                throw;
            }
        }
コード例 #10
0
        private void SaveUsers(BaseCamp basecampManager)
        {
            var employees = basecampManager.People;
            var step      = 100.0 / employees.Count();

            foreach (var person in employees.Where(x => _withClosed ? true : !x.Deleted))
            {
                try
                {
                    Status.UserProgress += step;
                    Guid userID = FindUserByEmail(person.EmailAddress);

                    if (userID.Equals(Guid.Empty))
                    {
                        UserInfo userInfo = new UserInfo()
                        {
                            Email     = person.EmailAddress,
                            FirstName = person.FirstName,
                            LastName  = person.LastName,
                            Title     = person.Title,
                            Status    = person.Deleted ? EmployeeStatus.Terminated : EmployeeStatus.Active,
                        };

                        if (!string.IsNullOrEmpty(person.PhoneNumberMobile))
                        {
                            userInfo.AddSocialContact(SocialContactsManager.ContactType_mobphone, person.PhoneNumberMobile);
                        }
                        if (!string.IsNullOrEmpty(person.PhoneNumberHome))
                        {
                            userInfo.AddSocialContact(SocialContactsManager.ContactType_phone, person.PhoneNumberHome);
                        }
                        if (!string.IsNullOrEmpty(person.PhoneNumberOffice))
                        {
                            userInfo.AddSocialContact(SocialContactsManager.ContactType_phone, person.PhoneNumberOffice);
                        }
                        if (!string.IsNullOrEmpty(person.PhoneNumberFax))
                        {
                            userInfo.AddSocialContact(SocialContactsManager.ContactType_phone, person.PhoneNumberFax);
                        }
                        if (!string.IsNullOrEmpty(person.ImHandle))
                        {
                            switch (person.ImService)
                            {
                            case "MSN":
                                userInfo.AddSocialContact(SocialContactsManager.ContactType_msn, person.ImHandle);
                                break;

                            case "ICQ":
                                userInfo.AddSocialContact(SocialContactsManager.ContactType_icq, person.ImHandle);
                                break;

                            case "Yahoo":
                                userInfo.AddSocialContact(SocialContactsManager.ContactType_yahoo, person.ImHandle);
                                break;

                            case "Jabber":
                                userInfo.AddSocialContact(SocialContactsManager.ContactType_jabber, person.ImHandle);
                                break;

                            case "Skype":
                                userInfo.AddSocialContact(SocialContactsManager.ContactType_skype, person.ImHandle);
                                break;

                            case "Google":
                                userInfo.AddSocialContact(SocialContactsManager.ContactType_gmail, person.ImHandle);
                                break;
                            }
                        }

                        var newUserInfo = UserManagerWrapper.AddUser(userInfo, UserManagerWrapper.GeneratePassword(), false, !_disableNotifications);
                        if (person.Administrator)
                        {
                            CoreContext.UserManager.AddUserIntoGroup(newUserInfo.ID, ASC.Core.Users.Constants.GroupAdmin.ID);
                        }
                        NewUsersID.Add(new UserIDWrapper()
                        {
                            inBasecamp = person.ID, inProjects = newUserInfo.ID
                        });

                        //save user avatar
                        const string emptyAvatar = "http://asset1.37img.com/global/missing/avatar.png?r=3";//TODO:?!!! Wtf??!!
                        if (person.AvatarUrl != emptyAvatar)
                        {
                            UserPhotoManager.SaveOrUpdatePhoto(newUserInfo.ID, StreamFile(person.AvatarUrl));
                        }
                    }
                    else
                    {
                        NewUsersID.Add(new UserIDWrapper()
                        {
                            inBasecamp = person.ID, inProjects = userID
                        });
                    }
                }
                catch (Exception e)
                {
                    Status.LogError(string.Format(SettingsResource.FailedToSaveUser, person.EmailAddress), e);
                    LogError(string.Format("user '{0}' failed", person.EmailAddress), e);
                    NewUsersID.RemoveAll(x => x.inBasecamp == person.ID);
                }
            }
        }
コード例 #11
0
ファイル: BoxApp.cs プロジェクト: DavidLama/AppServer
        private UserInfo GetUserInfo(Token token, out bool isNew)
        {
            isNew = false;
            if (token == null)
            {
                Logger.Error("BoxApp: token is null");
                throw new SecurityException("Access token is null");
            }

            var resultResponse = string.Empty;

            try
            {
                resultResponse = RequestHelper.PerformRequest(BoxUrlUserInfo,
                                                              headers: new Dictionary <string, string> {
                    { "Authorization", "Bearer " + token }
                });
                Logger.Debug("BoxApp: userinfo response - " + resultResponse);
            }
            catch (Exception ex)
            {
                Logger.Error("BoxApp: userinfo request", ex);
            }

            var boxUserInfo = JObject.Parse(resultResponse);

            if (boxUserInfo == null)
            {
                Logger.Error("Error in userinfo request");
                return(null);
            }

            var email    = boxUserInfo.Value <string>("login");
            var userInfo = UserManager.GetUserByEmail(email);

            if (Equals(userInfo, Constants.LostUser))
            {
                userInfo = new UserInfo
                {
                    FirstName   = boxUserInfo.Value <string>("name"),
                    Email       = email,
                    MobilePhone = boxUserInfo.Value <string>("phone"),
                };

                var cultureName = boxUserInfo.Value <string>("language");
                if (string.IsNullOrEmpty(cultureName))
                {
                    cultureName = Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName;
                }
                var cultureInfo = SetupInfo.EnabledCultures.Find(c => string.Equals(c.TwoLetterISOLanguageName, cultureName, StringComparison.InvariantCultureIgnoreCase));
                if (cultureInfo != null)
                {
                    userInfo.CultureName = cultureInfo.Name;
                }
                else
                {
                    Logger.DebugFormat("From box app new personal user '{0}' without culture {1}", userInfo.Email, cultureName);
                }

                if (string.IsNullOrEmpty(userInfo.FirstName))
                {
                    userInfo.FirstName = FilesCommonResource.UnknownFirstName;
                }
                if (string.IsNullOrEmpty(userInfo.LastName))
                {
                    userInfo.LastName = FilesCommonResource.UnknownLastName;
                }

                try
                {
                    SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
                    userInfo = UserManagerWrapper.AddUser(userInfo, UserManagerWrapper.GeneratePassword());
                }
                finally
                {
                    AuthContext.Logout();
                }

                isNew = true;

                Logger.Debug("BoxApp: new user " + userInfo.ID);
            }

            return(userInfo);
        }
コード例 #12
0
        public static bool TryLdapAuth(string login, string password)
        {
            if (!SetupInfo.IsVisibleSettings(ManagementType.LdapSettings.ToString()))
            {
                return(false);
            }

            var settings = SettingsManager.Instance.LoadSettings <LDAPSupportSettings>(TenantProvider.CurrentTenantID);

            if (!settings.EnableLdapAuthentication)
            {
                return(false);
            }
            try
            {
                var importer = new LDAPUserImporter();
                try
                {
                    ADDomain.CheckCredentials(login, password, settings.Server, settings.PortNumber);
                }
                catch (Exception)
                {
                    return(false);
                }

                var sid = importer.GetSidOfCurrentUser(login, settings);
                if (sid == null)
                {
                    return(false);
                }
                importer.GetDiscoveredGroupsByAttributes(settings);
                var userInfo = CoreContext.UserManager.GetUserBySid("l" + sid);
                if (userInfo == ASC.Core.Users.Constants.LostUser)
                {
                    userInfo = CoreContext.UserManager.GetUserBySid(sid);
                    if (userInfo == ASC.Core.Users.Constants.LostUser)
                    {
                        userInfo = importer.GetDiscoveredUser(settings, sid);
                        if (userInfo == ASC.Core.Users.Constants.LostUser)
                        {
                            return(false);
                        }
                        try
                        {
                            SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
                            if (TenantStatisticsProvider.GetUsersCount() < TenantExtra.GetTenantQuota().ActiveUsers)
                            {
                                userInfo = UserManagerWrapper.AddUser(userInfo, UserManagerWrapper.GeneratePassword(), true, false);
                            }
                            else
                            {
                                userInfo = UserManagerWrapper.AddUser(userInfo, UserManagerWrapper.GeneratePassword(), true, false, true);
                            }
                            importer.AddUserIntoGroups(userInfo, settings);
                            importer.AddUserInCacheGroups(userInfo);
                        }
                        finally
                        {
                            SecurityContext.Logout();
                        }
                    }
                }
                else
                {
                    if (importer.GetDiscoveredUser(settings, sid) == ASC.Core.Users.Constants.LostUser)
                    {
                        return(false);
                    }
                    userInfo.Sid = sid;
                    try
                    {
                        SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
                        if (TenantStatisticsProvider.GetUsersCount() < TenantExtra.GetTenantQuota().ActiveUsers)
                        {
                            userInfo = UserManagerWrapper.AddUser(userInfo, UserManagerWrapper.GeneratePassword(), true, false);
                        }
                        else
                        {
                            userInfo = UserManagerWrapper.AddUser(userInfo, UserManagerWrapper.GeneratePassword(), true, false, true);
                        }
                    }
                    finally
                    {
                        SecurityContext.Logout();
                    }
                }
                var cookiesKey = SecurityContext.AuthenticateMe(userInfo.ID);
                CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey);
                return(true);
            }
            catch (Exception e)
            {
                ADDomain.LogError(e.Message);
                return(false);
            }
        }
コード例 #13
0
 public AuthenticationController(
     UserManager userManager,
     TenantManager tenantManager,
     SecurityContext securityContext,
     TenantCookieSettingsHelper tenantCookieSettingsHelper,
     CookiesManager cookiesManager,
     PasswordHasher passwordHasher,
     EmailValidationKeyModelHelper emailValidationKeyModelHelper,
     ICache cache,
     SetupInfo setupInfo,
     MessageService messageService,
     ProviderManager providerManager,
     IOptionsSnapshot <AccountLinker> accountLinker,
     CoreBaseSettings coreBaseSettings,
     PersonalSettingsHelper personalSettingsHelper,
     StudioNotifyService studioNotifyService,
     UserManagerWrapper userManagerWrapper,
     UserHelpTourHelper userHelpTourHelper,
     Signature signature,
     InstanceCrypto instanceCrypto,
     DisplayUserSettingsHelper displayUserSettingsHelper,
     MessageTarget messageTarget,
     StudioSmsNotificationSettingsHelper studioSmsNotificationSettingsHelper,
     SettingsManager settingsManager,
     SmsManager smsManager,
     TfaManager tfaManager,
     TimeZoneConverter timeZoneConverter,
     SmsKeyStorage smsKeyStorage,
     CommonLinkUtility commonLinkUtility,
     ApiContext apiContext,
     AuthContext authContext)
 {
     UserManager                   = userManager;
     TenantManager                 = tenantManager;
     SecurityContext               = securityContext;
     TenantCookieSettingsHelper    = tenantCookieSettingsHelper;
     CookiesManager                = cookiesManager;
     PasswordHasher                = passwordHasher;
     EmailValidationKeyModelHelper = emailValidationKeyModelHelper;
     Cache                               = cache;
     SetupInfo                           = setupInfo;
     MessageService                      = messageService;
     ProviderManager                     = providerManager;
     AccountLinker                       = accountLinker;
     CoreBaseSettings                    = coreBaseSettings;
     PersonalSettingsHelper              = personalSettingsHelper;
     StudioNotifyService                 = studioNotifyService;
     UserHelpTourHelper                  = userHelpTourHelper;
     Signature                           = signature;
     InstanceCrypto                      = instanceCrypto;
     DisplayUserSettingsHelper           = displayUserSettingsHelper;
     MessageTarget                       = messageTarget;
     StudioSmsNotificationSettingsHelper = studioSmsNotificationSettingsHelper;
     SettingsManager                     = settingsManager;
     SmsManager                          = smsManager;
     TfaManager                          = tfaManager;
     TimeZoneConverter                   = timeZoneConverter;
     SmsKeyStorage                       = smsKeyStorage;
     CommonLinkUtility                   = commonLinkUtility;
     ApiContext                          = apiContext;
     AuthContext                         = authContext;
     UserManagerWrapper                  = userManagerWrapper;
 }
コード例 #14
0
        public static bool TryGetLdapUserInfo(string login, string password, out UserInfo userInfo)
        {
            userInfo = ASC.Core.Users.Constants.LostUser;

            try
            {
                if (!LdapIsEnable)
                {
                    return(false);
                }

                var settings = SettingsManager.Instance.LoadSettings <LDAPSupportSettings>(TenantProvider.CurrentTenantID);
                if (!settings.EnableLdapAuthentication)
                {
                    return(false);
                }

                var importer = new LDAPUserImporter(settings);

                var ldapUserInfo = ASC.Core.Users.Constants.LostUser;
                try
                {
                    var ldapSettingsChecker = WorkContext.IsMono
                        ? new NovellLdapSettingsChecker()
                        : new SystemLdapSettingsChecker() as LdapSettingsChecker;

                    var parsedLogin = ldapSettingsChecker.ParseLogin(login);

                    var ldapUsers = importer.FindLdapUsers(parsedLogin);

                    foreach (var ldapUser in ldapUsers)
                    {
                        try
                        {
                            ldapUserInfo = ldapUser.Key;
                            var ldapUserObject = ldapUser.Value;

                            if (ldapUserInfo.Equals(ASC.Core.Users.Constants.LostUser) ||
                                ldapUserObject == null ||
                                string.IsNullOrEmpty(ldapUserObject.DistinguishedName))
                            {
                                continue;
                            }

                            string currentLogin;

                            if (!WorkContext.IsMono)
                            {
                                currentLogin =
                                    ldapUserObject.InvokeGet(Constants.ADSchemaAttributes.ACCOUNT_NAME) as string;
                            }
                            else
                            {
                                currentLogin = ldapUserObject.DistinguishedName;
                            }

                            ldapSettingsChecker.CheckCredentials(currentLogin, password, settings.Server,
                                                                 settings.PortNumber,
                                                                 settings.StartTls);

                            break;
                        }
                        catch (Exception)
                        {
                            ldapUserInfo = ASC.Core.Users.Constants.LostUser;
                        }
                    }

                    if (ldapUserInfo.Equals(ASC.Core.Users.Constants.LostUser))
                    {
                        return(false);
                    }
                }
                catch (Exception)
                {
                    return(false);
                }

                if (settings.GroupMembership && !importer.IsUserExistsInGroups(ldapUserInfo))
                {
                    return(false);
                }

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

                    userInfo = UserManagerWrapper.SyncUserLDAP(ldapUserInfo);

                    if (userInfo == null || userInfo.Equals(ASC.Core.Users.Constants.LostUser))
                    {
                        return(false);
                    }

                    userInfo.Sid = ldapUserInfo.Sid;

                    importer.SyncUserGroupMembership(userInfo);
                }
                finally
                {
                    SecurityContext.Logout();
                }

                return(true);
            }
            catch (Exception e)
            {
                Log.ErrorFormat("TryGetLdapUserInfo(login: '******') Unexpected error: {1}", login, e);
                userInfo = ASC.Core.Users.Constants.LostUser;
                return(false);
            }
        }
コード例 #15
0
 public GoogleDriveApp(
     PathProvider pathProvider,
     TenantUtil tenantUtil,
     AuthContext authContext,
     SecurityContext securityContext,
     UserManager userManager,
     UserManagerWrapper userManagerWrapper,
     CookiesManager cookiesManager,
     MessageService messageService,
     Global global,
     GlobalStore globalStore,
     EmailValidationKeyProvider emailValidationKeyProvider,
     FilesLinkUtility filesLinkUtility,
     SettingsManager settingsManager,
     PersonalSettingsHelper personalSettingsHelper,
     BaseCommonLinkUtility baseCommonLinkUtility,
     IOptionsMonitor <ILog> option,
     FileUtility fileUtility,
     FilesSettingsHelper filesSettingsHelper,
     IOptionsSnapshot <AccountLinker> snapshot,
     SetupInfo setupInfo,
     GoogleLoginProvider googleLoginProvider,
     TokenHelper tokenHelper,
     DocumentServiceConnector documentServiceConnector,
     ThirdPartyAppHandlerService thirdPartyAppHandlerService,
     IServiceProvider serviceProvider,
     TenantManager tenantManager,
     CoreBaseSettings coreBaseSettings,
     CoreSettings coreSettings,
     IConfiguration configuration,
     ICacheNotify <ConsumerCacheItem> cache,
     ConsumerFactory consumerFactory,
     string name, int order, Dictionary <string, string> additional)
     : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, name, order, additional)
 {
     Logger                      = option.CurrentValue;
     PathProvider                = pathProvider;
     TenantUtil                  = tenantUtil;
     AuthContext                 = authContext;
     SecurityContext             = securityContext;
     UserManager                 = userManager;
     UserManagerWrapper          = userManagerWrapper;
     CookiesManager              = cookiesManager;
     MessageService              = messageService;
     Global                      = global;
     GlobalStore                 = globalStore;
     EmailValidationKeyProvider  = emailValidationKeyProvider;
     FilesLinkUtility            = filesLinkUtility;
     SettingsManager             = settingsManager;
     PersonalSettingsHelper      = personalSettingsHelper;
     BaseCommonLinkUtility       = baseCommonLinkUtility;
     FileUtility                 = fileUtility;
     FilesSettingsHelper         = filesSettingsHelper;
     Snapshot                    = snapshot;
     SetupInfo                   = setupInfo;
     GoogleLoginProvider         = googleLoginProvider;
     TokenHelper                 = tokenHelper;
     DocumentServiceConnector    = documentServiceConnector;
     ThirdPartyAppHandlerService = thirdPartyAppHandlerService;
     ServiceProvider             = serviceProvider;
 }
コード例 #16
0
        public AjaxResponse SaveUser(UserInfoEx userInfoEx, string photoPath)
        {
            var resp = new AjaxResponse();

            if (!SecurityContext.IsAuthenticated)
            {
                resp.rs1 = "0";
                return(resp);
            }

            var isNew = userInfoEx.Info.ID.Equals(Guid.Empty);


            userInfoEx.Info.Email = (userInfoEx.Info.Email ?? "").Trim();

            if (String.IsNullOrEmpty(userInfoEx.Info.FirstName.Trim()))
            {
                resp.rs1 = "0";
                resp.rs2 = "<div>" + Resources.Resource.ErrorEmptyUserFirstName + "</div>";
                return(resp);
            }
            else if (String.IsNullOrEmpty(userInfoEx.Info.LastName.Trim()))
            {
                resp.rs1 = "0";
                resp.rs2 = "<div>" + Resources.Resource.ErrorEmptyUserLastName + "</div>";
                return(resp);
            }
            else if (String.IsNullOrEmpty(userInfoEx.Info.Email.Trim()) || !userInfoEx.Info.Email.TestEmailRegex())
            {
                resp.rs1 = "0";
                resp.rs2 = "<div>" + Resources.Resource.ErrorNotCorrectEmail + "</div>";
                return(resp);
            }

            if (isNew)
            {
                userInfoEx.Pwd = UserManagerWrapper.GeneratePassword();
            }

            try
            {
                var self = SecurityContext.CurrentAccount.ID.Equals(userInfoEx.Info.ID);

                var newDepartment = CoreContext.GroupManager.GetGroupInfo(userInfoEx.DepartmentID);
                if (newDepartment != ASC.Core.Users.Constants.LostGroupInfo)
                {
                    userInfoEx.Info.Department = newDepartment.Name;
                }

                UserInfo newUserInfo = null;

                if (isNew && SecurityContext.IsAuthenticated &&
                    SecurityContext.CheckPermissions(ASC.Core.Users.Constants.Action_AddRemoveUser))
                {
                    var disableEditGroups = false;
                    if (!SecurityContext.CheckPermissions(ASC.Core.Users.Constants.Action_EditGroups))
                    {
                        userInfoEx.Info.Title = "";
                        disableEditGroups     = true;
                    }

                    newUserInfo = UserManagerWrapper.AddUser(userInfoEx.Info, userInfoEx.Pwd);

                    if (disableEditGroups == false && userInfoEx.DepartmentID != Guid.Empty)
                    {
                        CoreContext.UserManager.AddUserIntoGroup(newUserInfo.ID, userInfoEx.DepartmentID);
                    }

                    resp.rs3  = "add_user";
                    resp.rs10 = CustomNamingPeople.Substitute <Resources.Resource>("UserMakerAddUser").HtmlEncode();
                }
                else if (SecurityContext.CheckPermissions(ASC.Core.Users.Constants.Action_EditUser) ||
                         (self && SecurityContext.CheckPermissions(new UserSecurityProvider(SecurityContext.CurrentAccount.ID), ASC.Core.Users.Constants.Action_EditUser)))
                {
                    newUserInfo = (UserInfo)CoreContext.UserManager.GetUsers(userInfoEx.Info.ID).Clone();

                    newUserInfo.FirstName    = userInfoEx.Info.FirstName.Trim();
                    newUserInfo.LastName     = userInfoEx.Info.LastName.Trim();
                    newUserInfo.Sex          = userInfoEx.Info.Sex;
                    newUserInfo.Title        = userInfoEx.Info.Title.Trim();
                    newUserInfo.BirthDate    = userInfoEx.Info.BirthDate;
                    newUserInfo.WorkFromDate = userInfoEx.Info.WorkFromDate;

                    newUserInfo.Notes      = userInfoEx.Info.Notes.Trim();
                    newUserInfo.Department = userInfoEx.Info.Department;

                    newUserInfo.Location = userInfoEx.Info.Location.Trim();

                    newUserInfo.Contacts.Clear();
                    userInfoEx.Info.Contacts.ForEach(c => newUserInfo.Contacts.Add(c));

                    if (SecurityContext.CheckPermissions(ASC.Core.Users.Constants.Action_EditGroups))
                    {
                        var oldDep = GetDepartmentForUser(userInfoEx.Info.ID);

                        if (oldDep != null && !oldDep.ID.Equals(userInfoEx.DepartmentID))
                        {
                            CoreContext.UserManager.RemoveUserFromGroup(newUserInfo.ID, oldDep.ID);
                            newUserInfo.Department = "";
                        }

                        if (((oldDep != null && !oldDep.ID.Equals(userInfoEx.DepartmentID)) || oldDep == null) &&
                            userInfoEx.DepartmentID != Guid.Empty)
                        {
                            CoreContext.UserManager.AddUserIntoGroup(newUserInfo.ID, userInfoEx.DepartmentID);

                            var dep = CoreContext.GroupManager.GetGroupInfo(userInfoEx.DepartmentID);
                            newUserInfo.Department = dep.Name;
                        }
                    }

                    UserManagerWrapper.SaveUserInfo(newUserInfo);

                    resp.rs3  = "edit_user";
                    resp.rs10 = Resources.Resource.UserMakerEditUser;
                    resp.rs5  = SecurityContext.CurrentAccount.ID.Equals(newUserInfo.ID) ? "1" : "";

                    if (self && !CoreContext.UserManager.IsUserInGroup(SecurityContext.CurrentAccount.ID, ASC.Core.Users.Constants.GroupAdmin.ID))
                    {
                        StudioNotifyService.Instance.SendMsgToAdminAboutProfileUpdated();
                    }
                }
                else
                {
                    resp.rs1 = "0";
                    return(resp);
                }

                if (!String.IsNullOrEmpty(photoPath))
                {
                    var fileName = Path.GetFileName(photoPath);
                    var data     = UserPhotoManager.GetTempPhotoData(fileName);
                    UserPhotoManager.SaveOrUpdatePhoto(newUserInfo.ID, data);
                    try
                    {
                        UserPhotoManager.RemoveTempPhoto(fileName);
                    }
                    catch
                    {
                    }
                    ;
                }

                resp.rs1 = "1";
            }
            catch (Exception e)
            {
                resp.rs1 = "0";
                resp.rs2 = "<div>" + e.Message.HtmlEncode() + "</div>";
            }
            return(resp);
        }
コード例 #17
0
        private UserInfo GetUserInfo(Token token, out bool isNew)
        {
            isNew = false;
            if (token == null)
            {
                Logger.Error("GoogleDriveApp: token is null");
                throw new SecurityException("Access token is null");
            }

            LoginProfile loginProfile = null;

            try
            {
                loginProfile = GoogleLoginProvider.Instance.GetLoginProfile(token.GetRefreshedToken(TokenHelper));
            }
            catch (Exception ex)
            {
                Logger.Error("GoogleDriveApp: userinfo request", ex);
            }

            if (loginProfile == null)
            {
                Logger.Error("Error in userinfo request");
                return(null);
            }

            var userInfo = UserManager.GetUserByEmail(loginProfile.EMail);

            if (Equals(userInfo, Constants.LostUser))
            {
                userInfo = loginProfile.ProfileToUserInfo(CoreBaseSettings);

                var cultureName = loginProfile.Locale;
                if (string.IsNullOrEmpty(cultureName))
                {
                    cultureName = Thread.CurrentThread.CurrentUICulture.Name;
                }

                var cultureInfo = SetupInfo.EnabledCultures.Find(c => string.Equals(c.Name, cultureName, StringComparison.InvariantCultureIgnoreCase));
                if (cultureInfo != null)
                {
                    userInfo.CultureName = cultureInfo.Name;
                }
                else
                {
                    Logger.DebugFormat("From google app new personal user '{0}' without culture {1}", userInfo.Email, cultureName);
                }

                try
                {
                    SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
                    userInfo = UserManagerWrapper.AddUser(userInfo, UserManagerWrapper.GeneratePassword());
                }
                finally
                {
                    SecurityContext.Logout();
                }

                isNew = true;

                Logger.Debug("GoogleDriveApp: new user " + userInfo.ID);
            }

            return(userInfo);
        }
コード例 #18
0
        [Create("password", false, false)] //NOTE: this method doesn't requires auth!!!  //NOTE: this method doesn't check payment!!!
        public string SendUserPassword(string email)
        {
            var userInfo = UserManagerWrapper.SendUserPassword(email);

            return(String.Format(Resource.MessageYourPasswordSuccessfullySendedToEmail, userInfo.Email));
        }
コード例 #19
0
        public object SaveData(string email, string pwd, string lng, string promocode)
        {
            try
            {
                var tenant   = CoreContext.TenantManager.GetCurrentTenant();
                var settings = SettingsManager.Instance.LoadSettings <WizardSettings>(tenant.TenantId);
                if (settings.Completed)
                {
                    throw new Exception("Wizard passed.");
                }

                if (tenant.OwnerId == Guid.Empty)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(6)); // wait cache interval
                    tenant = CoreContext.TenantManager.GetTenant(tenant.TenantId);
                    if (tenant.OwnerId == Guid.Empty)
                    {
                        LogManager.GetLogger("ASC.Web.FirstTime").Error(tenant.TenantId + ": owner id is empty.");
                    }
                }

                var currentUser = CoreContext.UserManager.GetUsers(CoreContext.TenantManager.GetCurrentTenant().OwnerId);
                var cookie      = SecurityContext.AuthenticateMe(currentUser.ID);
                CookiesManager.SetCookies(CookiesType.AuthKey, cookie);

                if (!UserManagerWrapper.ValidateEmail(email))
                {
                    throw new Exception(Resource.EmailAndPasswordIncorrectEmail);
                }

                UserManagerWrapper.SetUserPassword(currentUser.ID, pwd);

                email = email.Trim();
                if (currentUser.Email != email)
                {
                    currentUser.Email            = email;
                    currentUser.ActivationStatus = EmployeeActivationStatus.NotActivated;
                }
                CoreContext.UserManager.SaveUserInfo(currentUser);

                if (!string.IsNullOrWhiteSpace(promocode))
                {
                    try
                    {
                        CoreContext.PaymentManager.ActivateKey(promocode);
                    }
                    catch (Exception err)
                    {
                        LogManager.GetLogger("ASC.Web.FirstTime").Error("Incorrect Promo: " + promocode, err);
                        throw new Exception(Resource.EmailAndPasswordIncorrectPromocode);
                    }
                }

                if (RequestLicense)
                {
                    TariffSettings.LicenseAccept = true;
                    MessageService.Send(HttpContext.Current.Request, MessageAction.LicenseKeyUploaded);

                    LicenseReader.RefreshLicense();
                }

                settings.Completed = true;
                SettingsManager.Instance.SaveSettings(settings, tenant.TenantId);

                TrySetLanguage(tenant, lng);

                StudioNotifyService.Instance.SendCongratulations(currentUser);
                FirstTimeTenantSettings.SendInstallInfo(currentUser);

                return(new { Status = 1, Message = Resource.EmailAndPasswordSaved });
            }
            catch (BillingNotFoundException)
            {
                return(new { Status = 0, Message = UserControlsCommonResource.LicenseKeyNotFound });
            }
            catch (BillingNotConfiguredException)
            {
                return(new { Status = 0, Message = UserControlsCommonResource.LicenseKeyNotCorrect });
            }
            catch (BillingException)
            {
                return(new { Status = 0, Message = UserControlsCommonResource.LicenseException });
            }
            catch (Exception ex)
            {
                LogManager.GetLogger("ASC.Web.FirstTime").Error(ex);
                return(new { Status = 0, Message = ex.Message });
            }
        }
コード例 #20
0
        private static UserInfo GetUserInfo(Token token, out bool isNew)
        {
            isNew = false;
            if (token == null)
            {
                Global.Logger.Error("GoogleDriveApp: token is null");
                throw new SecurityException("Access token is null");
            }

            var resultResponse = string.Empty;

            try
            {
                resultResponse = RequestHelper.PerformRequest(GoogleUrlUserInfo.Replace("{access_token}", HttpUtility.UrlEncode(token.ToString())));
                Global.Logger.Debug("GoogleDriveApp: userinfo response - " + resultResponse);
            }
            catch (Exception ex)
            {
                Global.Logger.Error("GoogleDriveApp: userinfo request", ex);
            }

            var googleUserInfo = JObject.Parse(resultResponse);

            if (googleUserInfo == null)
            {
                Global.Logger.Error("Error in userinfo request");
                return(null);
            }

            var email    = googleUserInfo.Value <string>("email");
            var userInfo = CoreContext.UserManager.GetUserByEmail(email);

            if (Equals(userInfo, Constants.LostUser))
            {
                userInfo = new UserInfo
                {
                    FirstName = googleUserInfo.Value <string>("given_name"),
                    LastName  = googleUserInfo.Value <string>("family_name"),
                    Email     = email,
                };

                var gender = googleUserInfo.Value <string>("gender");
                if (!string.IsNullOrEmpty(gender))
                {
                    userInfo.Sex = gender == "male";
                }

                var cultureName = googleUserInfo.Value <string>("locale");
                if (string.IsNullOrEmpty(cultureName))
                {
                    cultureName = Thread.CurrentThread.CurrentUICulture.Name;
                }

                var cultureInfo = SetupInfo.EnabledCultures.Find(c => String.Equals(c.Name, cultureName, StringComparison.InvariantCultureIgnoreCase));
                if (cultureInfo != null)
                {
                    userInfo.CultureName = cultureInfo.Name;
                }
                else
                {
                    Global.Logger.DebugFormat("From google app new personal user '{0}' without culture {1}", userInfo.Email, cultureName);
                }

                if (string.IsNullOrEmpty(userInfo.FirstName))
                {
                    userInfo.FirstName = FilesCommonResource.UnknownFirstName;
                }
                if (string.IsNullOrEmpty(userInfo.LastName))
                {
                    userInfo.LastName = FilesCommonResource.UnknownLastName;
                }

                var pwd = UserManagerWrapper.GeneratePassword();

                try
                {
                    SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
                    userInfo = UserManagerWrapper.AddUser(userInfo, pwd);
                }
                finally
                {
                    SecurityContext.Logout();
                }

                isNew = true;

                Global.Logger.Debug("GoogleDriveApp: new user " + userInfo.ID);
            }

            return(userInfo);
        }
コード例 #21
0
        private static UserInfo GetUserInfo(Token token, out bool isNew)
        {
            isNew = false;
            if (token == null)
            {
                Global.Logger.Error("BoxApp: token is null");
                throw new SecurityException("Access token is null");
            }

            var resultResponse = RequestHelper.PerformRequest(BoxUrlUserInfo,
                                                              headers: new Dictionary <string, string> {
                { "Authorization", "Bearer " + token.AccessToken }
            });

            Global.Logger.Debug("BoxApp: userinfo response - " + resultResponse);

            var boxUserInfo = JObject.Parse(resultResponse);

            if (boxUserInfo == null)
            {
                Global.Logger.Error("Error in userinfo request");
                return(null);
            }

            var email    = boxUserInfo.Value <string>("login");
            var userInfo = CoreContext.UserManager.GetUserByEmail(email);

            if (Equals(userInfo, Constants.LostUser))
            {
                userInfo = new UserInfo
                {
                    Status       = EmployeeStatus.Active,
                    FirstName    = boxUserInfo.Value <string>("name"),
                    Email        = email,
                    MobilePhone  = boxUserInfo.Value <string>("phone"),
                    WorkFromDate = TenantUtil.DateTimeNow(),
                };

                var cultureName = boxUserInfo.Value <string>("language") ?? CultureInfo.CurrentUICulture.Name;
                var cultureInfo = SetupInfo.EnabledCultures.Find(c => String.Equals(c.TwoLetterISOLanguageName, cultureName, StringComparison.InvariantCultureIgnoreCase));
                if (cultureInfo != null)
                {
                    userInfo.CultureName = cultureInfo.Name;
                }

                if (string.IsNullOrEmpty(userInfo.FirstName))
                {
                    userInfo.FirstName = FilesCommonResource.UnknownFirstName;
                }
                if (string.IsNullOrEmpty(userInfo.LastName))
                {
                    userInfo.LastName = FilesCommonResource.UnknownLastName;
                }

                var pwd = UserManagerWrapper.GeneratePassword();

                try
                {
                    SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
                    userInfo = UserManagerWrapper.AddUser(userInfo, pwd);
                }
                finally
                {
                    SecurityContext.Logout();
                }

                isNew = true;

                Global.Logger.Debug("BoxApp: new user " + userInfo.ID);
            }

            return(userInfo);
        }
コード例 #22
0
        public object SaveData(string email, string pwd, string lng, string promocode)
        {
            try
            {
                var tenant   = CoreContext.TenantManager.GetCurrentTenant();
                var settings = SettingsManager.Instance.LoadSettings <WizardSettings>(tenant.TenantId);
                if (settings.Completed)
                {
                    return(new { Status = 0, Message = "Wizard passed." });
                }

                if (tenant.OwnerId == Guid.Empty)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(6)); // wait cache interval
                    tenant = CoreContext.TenantManager.GetTenant(tenant.TenantId);
                    if (tenant.OwnerId == Guid.Empty)
                    {
                        LogManager.GetLogger("ASC.Web.FirstTime").Error(tenant.TenantId + ": owner id is empty.");
                    }
                }
                var currentUser = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);
                if (CoreContext.Configuration.Standalone)
                {
                    currentUser = CoreContext.UserManager.GetUsers(CoreContext.TenantManager.GetCurrentTenant().OwnerId);
                    var cookie = SecurityContext.AuthenticateMe(currentUser.ID);
                    CookiesManager.SetCookies(CookiesType.AuthKey, cookie);
                }

                if (!currentUser.IsOwner())
                {
                    return(new { Status = 0, Message = Resources.Resource.EmailAndPasswordNotOwner });
                }
                if (!UserManagerWrapper.ValidateEmail(email))
                {
                    return(new { Status = 0, Message = Resources.Resource.EmailAndPasswordIncorrectEmail });
                }

                UserManagerWrapper.SetUserPassword(currentUser.ID, pwd);

                email = email.Trim();
                if (currentUser.Email != email)
                {
                    currentUser.Email            = email;
                    currentUser.ActivationStatus = EmployeeActivationStatus.NotActivated;
                }
                CoreContext.UserManager.SaveUserInfo(currentUser);

                if (!string.IsNullOrWhiteSpace(promocode))
                {
                    try
                    {
                        CoreContext.PaymentManager.ActivateKey(promocode);
                    }
                    catch (Exception err)
                    {
                        LogManager.GetLogger("ASC.Web.FirstTime").ErrorFormat("Incorrect Promo: {0}\r\n{1}", promocode, err);
                        return(new { Status = 0, Message = Resources.Resource.EmailAndPasswordIncorrectPromocode });
                    }
                }

                settings.Completed = true;
                SettingsManager.Instance.SaveSettings(settings, tenant.TenantId);

                TrySetLanguage(tenant, lng);
                FirstTimeTenantSettings.SetDefaultTenantSettings();
                FirstTimeTenantSettings.SendInstallInfo(currentUser);

                return(new { Status = 1, Message = Resources.Resource.EmailAndPasswordSaved });
            }
            catch (Exception ex)
            {
                return(new { Status = 0, Message = ex.Message });
            }
        }