protected void Page_Load(object sender, EventArgs e)
        {
            var accountLink = (AccountLinkControl)LoadControl(AccountLinkControl.Location);

            accountLink.ClientCallback = "loginJoinCallback";
            accountLink.SettingsView   = false;
            ThirdPartyList.Controls.Add(accountLink);

            var loginProfile = Request.Url.GetProfile();

            if (loginProfile == null && !IsPostBack || SecurityContext.IsAuthenticated)
            {
                return;
            }

            string cookiesKey;

            try
            {
                if (loginProfile == null)
                {
                    if (string.IsNullOrEmpty(Request["__EVENTARGUMENT"]) || Request["__EVENTTARGET"] != "thirdPartyLogin")
                    {
                        return;
                    }

                    loginProfile = new LoginProfile(Request["__EVENTARGUMENT"]);
                }

                var userInfo = GetUserByThirdParty(loginProfile);
                if (!CoreContext.UserManager.UserExists(userInfo.ID))
                {
                    return;
                }

                cookiesKey = SecurityContext.AuthenticateMe(userInfo.ID);
                CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey);
                MessageService.Send(HttpContext.Current.Request, MessageAction.LoginSuccessViaSocialAccount);
            }
            catch (System.Security.SecurityException)
            {
                LoginMessage = Resource.InvalidUsernameOrPassword;
                MessageService.Send(HttpContext.Current.Request, loginProfile != null ? loginProfile.EMail : AuditResource.EmailNotSpecified, MessageAction.LoginFailDisabledProfile);
                return;
            }
            catch (Exception exception)
            {
                LoginMessage = exception.Message;
                MessageService.Send(HttpContext.Current.Request, AuditResource.EmailNotSpecified, MessageAction.LoginFail);
                return;
            }

            var refererURL = (string)Session["refererURL"];

            if (String.IsNullOrEmpty(refererURL))
            {
                refererURL = CommonLinkUtility.GetDefault();
            }
            if (Request.DesktopApp())
            {
                refererURL += (refererURL.Contains("?") ? "&" : "?") + "token=" + HttpUtility.HtmlEncode(cookiesKey);
            }

            Session["refererURL"] = null;
            Response.Redirect(refererURL);
        }
        public ActionResult SignIn(LoginModel login)
        {
            //First try federated
            UserInfo user         = null;
            var      byThirdParty = false;

            if (!StudioSmsNotificationSettings.IsVisibleSettings ||
                !StudioSmsNotificationSettings.Enable)
            {
                if (ModelState.IsValid)
                {
                    //Validate login password
                    try
                    {
                        var key = SecurityContext.AuthenticateMe(login.Email, login.Password);
                        CookiesManager.SetCookies(CookiesType.AuthKey, key);
                        MessageService.Send(System.Web.HttpContext.Current.Request, MessageAction.LoginSuccess);
                        return(RedirectAuthorized());
                    }
                    catch (Exception e)
                    {
                        _log.Error(string.Format("Error authentificating by password. email:{0}", login.Email), e);
                        MessageService.Send(System.Web.HttpContext.Current.Request, login.Email, MessageAction.LoginFail);
                        ModelState.AddModelError("InvalidPassword", MobileResource.ErrPasswordInvalid);
                    }
                }
            }
            else
            {
                var profile = Request.Url.GetProfile();
                if (profile != null)
                {
                    try
                    {
                        Guid userId;
                        TryByHashId(profile.HashId, out userId);

                        user         = CoreContext.UserManager.GetUsers(userId);
                        byThirdParty = true;
                    }
                    catch (Exception e)
                    {
                        user = null;
                        _log.Error("Error authentificating by profile", e);
                    }
                    finally
                    {
                        //If we got here than no token associated. add error
                        ModelState.AddModelError("InvalidPassword", MobileResource.ErrNoToken);
                    }
                }
                else if (ModelState.IsValid)
                {
                    user = CoreContext.UserManager.GetUsers(CoreContext.TenantManager.GetCurrentTenant(false).TenantId, login.Email, Hasher.Base64Hash(login.Password, HashAlg.SHA256));
                }

                if (user != null)
                {
                    if (!string.IsNullOrEmpty(Request.Form["Resend"] + Request.Form["SendCode"]))
                    {
                        if (string.IsNullOrEmpty(user.MobilePhone) || user.MobilePhoneActivationStatus == MobilePhoneActivationStatus.NotActivated)
                        {
                            user = null;
                            ModelState.AddModelError("InvalidPassword", MobileResource.ErrMobileNotActivate);
                        }
                        else
                        {
                            try
                            {
                                SmsManager.PutAuthCode(user, !string.IsNullOrEmpty(Request.Form["Resend"]));
                            }
                            catch (Exception e)
                            {
                                ModelState.AddModelError("InvalidCode", e.Message);
                            }
                        }
                    }
                    else
                    {
                        try
                        {
                            SmsManager.ValidateSmsCode(user, login.Code);

                            var key = SecurityContext.AuthenticateMe(user.ID);
                            CookiesManager.SetCookies(CookiesType.AuthKey, key);
                            MessageService.Send(System.Web.HttpContext.Current.Request, MessageAction.LoginSuccessViaSms);
                            return(RedirectAuthorized());
                        }
                        catch (Exception e)
                        {
                            _log.Error(string.Format("Error authentificating by sms code. email:{0}", login.Email), e);
                            MessageService.Send(System.Web.HttpContext.Current.Request, user.DisplayUserName(false), MessageAction.LoginFailViaSms);
                            ModelState.AddModelError("InvalidCode", e.Message);
                        }
                    }
                }
            }
            return(LoginView(user, byThirdParty, login.Email, login.Password));
        }
Esempio n. 3
0
        public void RunJob()
        {
            using (var smtpClient = GetSmtpClient())
            {
                CoreContext.TenantManager.SetCurrentTenant(_tenantID);
                SecurityContext.AuthenticateMe(CoreContext.Authentication.GetAccountByID(_currUser));

                using (var scope = DIHelper.Resolve())
                {
                    var _daoFactory = scope.Resolve <DaoFactory>();
                    var userCulture = CoreContext.UserManager.GetUsers(_currUser).GetCulture();

                    Thread.CurrentThread.CurrentCulture   = userCulture;
                    Thread.CurrentThread.CurrentUICulture = userCulture;

                    var contactCount = _contactID.Count;

                    if (contactCount == 0)
                    {
                        Complete();
                        return;
                    }

                    MailSenderDataCache.Insert((SendBatchEmailsOperation)Clone());

                    var from      = new MailboxAddress(_smtpSetting.SenderDisplayName, _smtpSetting.SenderEmailAddress);
                    var filePaths = new List <string>();
                    using (var fileDao = FilesIntegration.GetFileDao())
                    {
                        foreach (var fileID in _fileID)
                        {
                            var fileObj = fileDao.GetFile(fileID);
                            if (fileObj == null)
                            {
                                continue;
                            }
                            using (var fileStream = fileDao.GetFileStream(fileObj))
                            {
                                var directoryPath = Path.Combine(Path.GetTempPath(), "teamlab", _tenantID.ToString(),
                                                                 "crm/files/mailsender/");
                                if (!Directory.Exists(directoryPath))
                                {
                                    Directory.CreateDirectory(directoryPath);
                                }
                                var filePath = Path.Combine(directoryPath, fileObj.Title);
                                using (var newFileStream = File.Create(filePath))
                                {
                                    fileStream.StreamCopyTo(newFileStream);
                                }
                                filePaths.Add(filePath);
                            }
                        }
                    }

                    var templateManager = new MailTemplateManager(_daoFactory);
                    var deliveryCount   = 0;

                    try
                    {
                        Error = string.Empty;
                        foreach (var contactID in _contactID)
                        {
                            _exactPercentageValue += 100.0 / contactCount;
                            Percentage             = Math.Round(_exactPercentageValue);

                            if (IsCompleted)
                            {
                                break;              // User selected cancel
                            }
                            var contactInfoDao = _daoFactory.ContactInfoDao;
                            var startDate      = DateTime.Now;

                            var contactEmails = contactInfoDao.GetList(contactID, ContactInfoType.Email, null, true);
                            if (contactEmails.Count == 0)
                            {
                                continue;
                            }

                            var recipientEmail = contactEmails[0].Data;

                            if (!recipientEmail.TestEmailRegex())
                            {
                                Error += string.Format(CRMCommonResource.MailSender_InvalidEmail, recipientEmail) +
                                         "<br/>";
                                continue;
                            }

                            var to = new MailboxAddress(recipientEmail);

                            var mimeMessage = new MimeMessage
                            {
                                Subject = _subject
                            };

                            mimeMessage.From.Add(from);
                            mimeMessage.To.Add(to);

                            var bodyBuilder = new BodyBuilder
                            {
                                HtmlBody = templateManager.Apply(_bodyTempate, contactID)
                            };

                            foreach (var filePath in filePaths)
                            {
                                bodyBuilder.Attachments.Add(filePath);
                            }

                            mimeMessage.Body = bodyBuilder.ToMessageBody();

                            mimeMessage.Headers.Add("Auto-Submitted", "auto-generated");

                            _log.Debug(GetLoggerRow(mimeMessage));

                            var success = false;

                            try
                            {
                                smtpClient.Send(mimeMessage);

                                success = true;
                            }
                            catch (SmtpCommandException ex)
                            {
                                _log.Error(Error, ex);

                                if (ex.ErrorCode == SmtpErrorCode.RecipientNotAccepted)
                                {
                                    if (ex.StatusCode == SmtpStatusCode.MailboxBusy ||
                                        ex.StatusCode == SmtpStatusCode.MailboxUnavailable)
                                    {
                                        Error = string.Format(CRMCommonResource.MailSender_MailboxBusyException, 5);

                                        Thread.Sleep(TimeSpan.FromSeconds(5));

                                        smtpClient.Send(mimeMessage);

                                        success = true;
                                    }
                                    else
                                    {
                                        Error +=
                                            string.Format(CRMCommonResource.MailSender_FailedDeliverException,
                                                          ex.Mailbox.Address) + "<br/>";
                                    }
                                }
                            }

                            if (success)
                            {
                                if (_storeInHistory)
                                {
                                    AddToHistory(contactID, string.Format(CRMCommonResource.MailHistoryEventTemplate, mimeMessage.Subject), _daoFactory);
                                }

                                var endDate      = DateTime.Now;
                                var waitInterval = endDate.Subtract(startDate);

                                deliveryCount++;

                                var estimatedTime =
                                    TimeSpan.FromTicks(waitInterval.Ticks * (_contactID.Count - deliveryCount));

                                Status = new
                                {
                                    RecipientCount = _contactID.Count,
                                    EstimatedTime  = estimatedTime.ToString(),
                                    DeliveryCount  = deliveryCount
                                };
                            }

                            if (MailSenderDataCache.CheckCancelFlag())
                            {
                                MailSenderDataCache.ResetAll();

                                throw new OperationCanceledException();
                            }

                            MailSenderDataCache.Insert((SendBatchEmailsOperation)Clone());

                            if (Percentage > 100)
                            {
                                Percentage = 100;

                                if (MailSenderDataCache.CheckCancelFlag())
                                {
                                    MailSenderDataCache.ResetAll();

                                    throw new OperationCanceledException();
                                }

                                MailSenderDataCache.Insert((SendBatchEmailsOperation)Clone());
                            }
                        }
                    }
                    catch (OperationCanceledException)
                    {
                        _log.Debug("cancel mail sender");
                    }
                    finally
                    {
                        foreach (var filePath in filePaths)
                        {
                            if (File.Exists(filePath))
                            {
                                File.Delete(filePath);
                            }
                        }
                    }

                    Status = new
                    {
                        RecipientCount = _contactID.Count,
                        EstimatedTime  = TimeSpan.Zero.ToString(),
                        DeliveryCount  = deliveryCount
                    };
                }
                Complete();
            }
        }
Esempio n. 4
0
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                _context = context;

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

                if (!CheckPermission())
                {
                    throw new Exception(CRMSettingResource.WebToLeadsForm_InvalidKeyException);
                }

                var productInfo = WebItemSecurity.GetSecurityInfo(ProductEntryPoint.ID.ToString());
                if (!productInfo.Enabled)
                {
                    throw new Exception(CRMCommonResource.CRMProductIsDisabled);
                }

                Contact contact;

                var fieldCollector = new NameValueCollection();

                var addressTemplate = new JObject();
                foreach (String addressPartName in Enum.GetNames(typeof(AddressPart)))
                {
                    addressTemplate.Add(addressPartName.ToLower(), "");
                }
                var addressTemplateStr = addressTemplate.ToString();

                var isCompany = false;

                var isCompanyString = GetValue("is_company");
                var firstName       = GetValue("firstName");
                var lastName        = GetValue("lastName");
                var companyName     = GetValue("companyName");

                if (!String.IsNullOrEmpty(isCompanyString))
                {
                    if (!Boolean.TryParse(isCompanyString, out isCompany))
                    {
                        throw new ArgumentException();
                    }
                }
                else//old scheme
                {
                    if (!(String.IsNullOrEmpty(firstName) || String.IsNullOrEmpty(lastName)))
                    {
                        isCompany = false;
                    }
                    else if (!String.IsNullOrEmpty(companyName))
                    {
                        isCompany = true;
                    }
                    else
                    {
                        throw new ArgumentException();
                    }
                }


                if (isCompany)
                {
                    contact = new Company();

                    ((Company)contact).CompanyName = companyName;

                    fieldCollector.Add(CRMContactResource.CompanyName, companyName);
                }
                else
                {
                    contact = new Person();

                    ((Person)contact).FirstName = firstName;
                    ((Person)contact).LastName  = lastName;
                    ((Person)contact).JobTitle  = GetValue("jobTitle");

                    fieldCollector.Add(CRMContactResource.FirstName, firstName);
                    fieldCollector.Add(CRMContactResource.LastName, lastName);

                    if (!String.IsNullOrEmpty(GetValue("jobTitle")))
                    {
                        fieldCollector.Add(CRMContactResource.JobTitle, ((Person)contact).JobTitle);
                    }
                }

                contact.About = GetValue("about");

                if (!String.IsNullOrEmpty(contact.About))
                {
                    fieldCollector.Add(CRMContactResource.About, contact.About);
                }

                contact.IsShared = Convert.ToBoolean(GetValue("is_shared"));

                contact.ID = Global.DaoFactory.GetContactDao().SaveContact(contact);

                var contactInfos = new List <ContactInfo>();

                foreach (var key in _context.Request.Form.AllKeys)
                {
                    if (key.StartsWith("customField_"))
                    {
                        var    fieldID    = Convert.ToInt32(key.Split(new[] { '_' })[1]);
                        String fieldValue = GetValue(key);

                        if (String.IsNullOrEmpty(fieldValue))
                        {
                            continue;
                        }

                        var customField = Global.DaoFactory.GetCustomFieldDao().GetFieldDescription(fieldID);

                        if (customField == null)
                        {
                            continue;
                        }

                        fieldCollector.Add(customField.Label, fieldValue);

                        Global.DaoFactory.GetCustomFieldDao().SetFieldValue(EntityType.Contact, contact.ID, fieldID, fieldValue);
                    }
                    else if (key.StartsWith("contactInfo_"))
                    {
                        var nameParts       = key.Split(new[] { '_' }).Skip(1).ToList();
                        var contactInfoType = (ContactInfoType)Enum.Parse(typeof(ContactInfoType), nameParts[0]);
                        var category        = Convert.ToInt32(nameParts[1]);

                        bool categoryIsExists = Enum.GetValues(ContactInfo.GetCategory(contactInfoType)).Cast <object>()
                                                .Any(categoryEnum => (int)categoryEnum == category);
                        if (!categoryIsExists)
                        {
                            throw new ArgumentException(String.Format("Category for {0} not found", nameParts[0]));
                        }

                        if (contactInfoType == ContactInfoType.Address)
                        {
                            var addressPart = (AddressPart)Enum.Parse(typeof(AddressPart), nameParts[2]);

                            var findedAddress = contactInfos.Find(item => (category == item.Category) && (item.InfoType == ContactInfoType.Address));

                            if (findedAddress == null)
                            {
                                findedAddress = new ContactInfo
                                {
                                    Category  = category,
                                    InfoType  = contactInfoType,
                                    Data      = addressTemplateStr,
                                    ContactID = contact.ID
                                };

                                contactInfos.Add(findedAddress);
                            }

                            var addressParts = JObject.Parse(findedAddress.Data);

                            addressParts[addressPart.ToString().ToLower()] = GetValue(key);

                            findedAddress.Data = addressParts.ToString();

                            continue;
                        }

                        var fieldValue = GetValue(key);

                        if (String.IsNullOrEmpty(fieldValue))
                        {
                            continue;
                        }

                        contactInfos.Add(new ContactInfo
                        {
                            Category  = category,
                            InfoType  = contactInfoType,
                            Data      = fieldValue,
                            ContactID = contact.ID,
                            IsPrimary = true
                        });
                    }
                    else if (String.Compare(key, "tag", true) == 0)
                    {
                        var tags = _context.Request.Form.GetValues("tag");

                        Global.DaoFactory.GetTagDao().SetTagToEntity(EntityType.Contact, contact.ID, tags);
                    }
                }

                contactInfos.ForEach(item => fieldCollector[item.InfoType.ToLocalizedString()] = PrepareteDataToView(item.InfoType, item.Data));

                Global.DaoFactory.GetContactInfoDao().SaveList(contactInfos);

                var notifyList = GetValue("notify_list");

                if (!String.IsNullOrEmpty(notifyList))
                {
                    NotifyClient.Instance.SendAboutCreateNewContact(
                        notifyList
                        .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                        .Select(item => new Guid(item)).ToList(), contact.ID, contact.GetTitle(), fieldCollector);
                }

                var managersList = GetValue("managers_list");
                SetPermission(contact, managersList);

                if (contact is Person && !String.IsNullOrEmpty(companyName))
                {
                    AssignPersonToCompany((Person)contact, companyName, managersList);
                }

                if (contact is Company && !String.IsNullOrEmpty(firstName) && !String.IsNullOrEmpty(lastName))
                {
                    AssignCompanyToPerson((Company)contact, firstName, lastName, managersList);
                }

                SecurityContext.Logout();

                var newURL = new UriBuilder(GetValue("return_url")).Uri.AbsoluteUri;
                context.Response.Buffer = true;
                context.Response.Status = "302 Object moved";
                context.Response.AddHeader("Location", newURL);
                context.Response.Write("<HTML><Head>");
                context.Response.Write(String.Format("<META HTTP-EQUIV=Refresh CONTENT=\"0;URL={0}\">", newURL));
                context.Response.Write(String.Format("<Script>window.location='{0}';</Script>", newURL));
                context.Response.Write("</Head>");
                context.Response.Write("</HTML>");
            }
            catch (Exception error)
            {
                LogManager.GetLogger("ASC.CRM").Error(error);
                context.Response.StatusCode = 400;
                context.Response.Write(HttpUtility.HtmlEncode(error.Message));
            }
        }
Esempio n. 5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var accountLink = (AccountLinkControl)LoadControl(AccountLinkControl.Location);

            accountLink.ClientCallback = "loginJoinCallback";
            accountLink.SettingsView   = false;
            ThirdPartyList.Controls.Add(accountLink);

            _loginMessage = Request["m"];

            var thirdPartyProfile = Request.Url.GetProfile();

            if (thirdPartyProfile == null && !IsPostBack || SecurityContext.IsAuthenticated)
            {
                return;
            }

            try
            {
                if (thirdPartyProfile == null)
                {
                    if (string.IsNullOrEmpty(Request["__EVENTARGUMENT"]) || Request["__EVENTTARGET"] != "thirdPartyLogin")
                    {
                        LoginMessage = "<div class=\"errorBox\">" + HttpUtility.HtmlEncode(Resources.Resource.InvalidUsernameOrPassword) + "</div>";
                        return;
                    }

                    thirdPartyProfile = new LoginProfile(Request["__EVENTARGUMENT"]);
                }

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

                if (string.IsNullOrEmpty(thirdPartyProfile.EMail))
                {
                    _loginMessage = Resources.Resource.ErrorNotCorrectEmail;
                    return;
                }

                var cookiesKey = string.Empty;
                var accounts   = accountLink.GetLinker().GetLinkedObjectsByHashId(thirdPartyProfile.HashId);

                foreach (var account in accounts.Select(x =>
                {
                    try
                    {
                        return(new Guid(x));
                    }
                    catch
                    {
                        return(Guid.Empty);
                    }
                }))
                {
                    if (account == Guid.Empty || !CoreContext.UserManager.UserExists(account))
                    {
                        continue;
                    }

                    var coreAcc = CoreContext.UserManager.GetUsers(account);
                    cookiesKey = SecurityContext.AuthenticateMe(coreAcc.ID);
                }

                if (string.IsNullOrEmpty(cookiesKey))
                {
                    var emailAcc = CoreContext.UserManager.GetUserByEmail(thirdPartyProfile.EMail);
                    if (CoreContext.UserManager.UserExists(emailAcc.ID))
                    {
                        cookiesKey = SecurityContext.AuthenticateMe(emailAcc.ID);
                    }
                }

                if (CoreContext.Configuration.Personal && string.IsNullOrEmpty(cookiesKey))
                {
                    cookiesKey = JoinByThirdPartyAccount(thirdPartyProfile);

                    UserHelpTourHelper.IsNewUser = true;
                    PersonalSettings.IsNewUser   = true;
                }

                CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey);
            }
            catch (System.Security.SecurityException)
            {
                Auth.ProcessLogout();
                _loginMessage = Resources.Resource.InvalidUsernameOrPassword;
                return;
            }
            catch (Exception exception)
            {
                Auth.ProcessLogout();
                _loginMessage = exception.Message;
                return;
            }

            var refererURL = (string)Session["refererURL"];

            var addMember = Request.Form["additionalMember"];

            if (!string.IsNullOrEmpty(addMember))
            {
                refererURL = addMember;
            }

            if (String.IsNullOrEmpty(refererURL))
            {
                Response.Redirect(CommonLinkUtility.GetDefault());
            }
            else
            {
                Session["refererURL"] = null;
                Response.Redirect(refererURL);
            }
        }
Esempio n. 6
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Page.RegisterBodyScripts("~/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(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)
                {
                    var cookiesKey = SecurityContext.AuthenticateMe(user.ID);
                    CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey);
                    MessageService.Send(HttpContext.Current.Request, MessageAction.LoginSuccess);
                    Response.Redirect(CommonLinkUtility.GetDefault());
                    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 = IPRestrictionsSettings.Load();
                if (settings.Enable && !IPSecurity.IPSecurity.Verify(tenant))
                {
                    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, MessageTarget.Create(newUser.ID), 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, 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)
                {
                    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);
                        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 (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(CommonLinkUtility.GetDefault());
        }
        private static string ProcessSave(string fileId, bool isNew, TrackerData fileData)
        {
            Guid userId;
            var  comments = new List <string>();

            if (fileData.Status == TrackerStatus.Corrupted)
            {
                comments.Add(FilesCommonResource.ErrorMassage_SaveCorrupted);
            }

            if (fileData.Users == null || fileData.Users.Count == 0 || !Guid.TryParse(fileData.Users[0], out userId))
            {
                userId = FileTracker.GetEditingBy(fileId).FirstOrDefault();
            }

            try
            {
                SecurityContext.AuthenticateMe(userId);
            }
            catch (Exception ex)
            {
                Global.Logger.Info("DocService save error: anonymous author - " + userId, ex);
                if (!userId.Equals(ASC.Core.Configuration.Constants.Guest.ID))
                {
                    comments.Add(FilesCommonResource.ErrorMassage_SaveAnonymous);
                }
            }

            File file  = null;
            var  saved = false;

            if (string.IsNullOrEmpty(fileData.Url))
            {
                try
                {
                    comments.Add(FilesCommonResource.ErrorMassage_SaveUrlLost);

                    FileTracker.Remove(fileId);

                    file = EntryManager.CompleteVersionFile(fileId, 0, false, false);

                    using (var fileDao = Global.DaoFactory.GetFileDao())
                    {
                        fileDao.UpdateComment(file.ID, file.Version, string.Join("; ", comments));
                    }
                }
                catch (Exception ex)
                {
                    Global.Logger.Error(string.Format("DocService save error. Version update. File id: '{0}'. UserId: {1}. DocKey '{2}'", fileId, userId, fileData.Key), ex);
                }
            }
            else
            {
                try
                {
                    file  = EntryManager.SaveEditing(fileId, -1, userId, null, fileData.Url, null, isNew, string.Empty, string.Join("; ", comments), false);
                    saved = fileData.Status == TrackerStatus.MustSave;
                }
                catch (Exception ex)
                {
                    Global.Logger.Error(string.Format("DocService save error. File id: '{0}'. UserId: {1}. DocKey '{2}'. DownloadUri: {3}", fileId, userId, fileData.Key, fileData.Url), ex);

                    StoringFileAfterError(fileId, userId.ToString(), fileData.Url);
                }
            }

            if (file != null)
            {
                var user = CoreContext.UserManager.GetUsers(userId);
                if (user != null)
                {
                    FilesMessageService.Send(file, MessageInitiator.DocsService, MessageAction.UserFileUpdated, user.DisplayUserName(false), file.Title);
                }

                SaveHistory(file, fileData.ChangesHistory, fileData.ChangesUrl);
            }

            FileTracker.Remove(fileId);

            DocumentServiceConnector.Command(CommandMethod.Saved, fileData.Key, fileId, null, userId.ToString(), saved ? "1" : "0");

            return(saved
                       ? "0"   //error:0 - saved
                       : "1"); //error:1 - some error
        }
        public string PortalRemove(string email, string key)
        {
            email = (email ?? "").Trim();
            if (!string.IsNullOrEmpty(email) && !email.TestEmailRegex())
            {
                throw new ArgumentException(Resource.ErrorNotCorrectEmail);
            }

            var checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(email + ConfirmType.PortalRemove, key, SetupInfo.ValidEmailKeyInterval);

            if (checkKeyResult == EmailValidationKeyProvider.ValidationResult.Expired)
            {
                throw new ExpiredTokenException(Resource.ErrorExpiredActivationLink);
            }

            if (checkKeyResult == EmailValidationKeyProvider.ValidationResult.Invalid)
            {
                throw new SecurityAccessDeniedException(Resource.ErrorConfirmURLError);
            }

            var tenant = CoreContext.TenantManager.GetCurrentTenant();

            CoreContext.TenantManager.RemoveTenant(tenant.TenantId);

            if (!String.IsNullOrEmpty(ApiSystemHelper.ApiCacheUrl))
            {
                ApiSystemHelper.RemoveTenantFromCache(tenant.TenantAlias);
            }

            var owner        = CoreContext.UserManager.GetUsers(tenant.OwnerId);
            var redirectLink = SetupInfo.TeamlabSiteRedirect + "/remove-portal-feedback-form.aspx#" +
                               Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("{\"firstname\":\"" + owner.FirstName +
                                                                                         "\",\"lastname\":\"" + owner.LastName +
                                                                                         "\",\"alias\":\"" + tenant.TenantAlias +
                                                                                         "\",\"email\":\"" + owner.Email + "\"}"));

            var authed = false;

            try
            {
                if (!SecurityContext.IsAuthenticated)
                {
                    SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
                    authed = true;
                }

                MessageService.Send(HttpContext.Current.Request, MessageAction.PortalDeleted);
            }
            finally
            {
                if (authed)
                {
                    SecurityContext.Logout();
                }
            }

            _successMessage = string.Format(Resource.DeletePortalSuccessMessage, "<br/>", "<a href=\"{0}\">", "</a>");
            _successMessage = string.Format(_successMessage, redirectLink);

            StudioNotifyService.Instance.SendMsgPortalDeletionSuccess(owner, redirectLink);

            return(JsonConvert.SerializeObject(new
            {
                successMessage = _successMessage,
                redirectLink
            }));
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            var dns   = Request["dns"];
            var alias = Request["alias"];

            _type = GetConfirmType();
            switch (_type)
            {
            case ConfirmType.PortalContinue:
                if (TenantExtra.Enterprise)
                {
                    var countPortals  = TenantExtra.GetTenantQuota().CountPortals;
                    var activePortals = CoreContext.TenantManager.GetTenants().Count();
                    if (countPortals <= activePortals)
                    {
                        _successMessage = UserControlsCommonResource.TariffPortalLimitHeaer;
                        _confirmContentHolder.Visible = false;
                        return;
                    }
                }

                _buttonTitle = Resource.ReactivatePortalButton;
                _title       = Resource.ConfirmReactivatePortalTitle;
                break;

            case ConfirmType.PortalRemove:
                _buttonTitle = Resource.DeletePortalButton;
                _title       = Resource.ConfirmDeletePortalTitle;
                AjaxPro.Utility.RegisterTypeForAjax(GetType());
                break;

            case ConfirmType.PortalSuspend:
                _buttonTitle = Resource.DeactivatePortalButton;
                _title       = Resource.ConfirmDeactivatePortalTitle;
                break;

            case ConfirmType.DnsChange:
                _buttonTitle = Resource.SaveButton;
                var portalAddress = GenerateLink(GetTenantBasePath(alias));
                if (!string.IsNullOrEmpty(dns))
                {
                    portalAddress += string.Format(" ({0})", GenerateLink(dns));
                }
                _title = string.Format(Resource.ConfirmDnsUpdateTitle, portalAddress);
                break;
            }


            if (IsPostBack && _type != ConfirmType.PortalRemove)
            {
                _successMessage = "";

                var curTenant   = CoreContext.TenantManager.GetCurrentTenant();
                var updatedFlag = false;

                var messageAction = MessageAction.None;
                switch (_type)
                {
                case ConfirmType.PortalContinue:
                    curTenant.SetStatus(TenantStatus.Active);
                    _successMessage = string.Format(Resource.ReactivatePortalSuccessMessage, "<br/>", "<a href=\"{0}\">", "</a>");
                    break;

                case ConfirmType.PortalSuspend:
                    curTenant.SetStatus(TenantStatus.Suspended);
                    _successMessage = string.Format(Resource.DeactivatePortalSuccessMessage, "<br/>", "<a href=\"{0}\">", "</a>");
                    messageAction   = MessageAction.PortalDeactivated;
                    break;

                case ConfirmType.DnsChange:
                    if (!string.IsNullOrEmpty(dns))
                    {
                        dns = dns.Trim().TrimEnd('/', '\\');
                    }
                    if (curTenant.MappedDomain != dns)
                    {
                        updatedFlag = true;
                    }
                    curTenant.MappedDomain = dns;
                    if (!string.IsNullOrEmpty(alias))
                    {
                        if (curTenant.TenantAlias != alias)
                        {
                            updatedFlag = true;
                        }
                        curTenant.TenantAlias = alias;
                    }
                    _successMessage = string.Format(Resource.DeactivatePortalSuccessMessage, "<br/>", "<a href=\"{0}\">", "</a>");
                    break;
                }

                bool authed = false;
                try
                {
                    if (!SecurityContext.IsAuthenticated)
                    {
                        SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
                        authed = true;
                    }

                    #region Alias or dns update

                    if (IsChangeDnsMode)
                    {
                        if (updatedFlag)
                        {
                            CoreContext.TenantManager.SaveTenant(curTenant);
                        }
                        var redirectUrl = dns;
                        if (string.IsNullOrEmpty(redirectUrl))
                        {
                            redirectUrl = GetTenantBasePath(curTenant);
                        }
                        Response.Redirect(AddHttpToUrl(redirectUrl));
                        return;
                    }

                    #endregion


                    CoreContext.TenantManager.SaveTenant(curTenant);
                    if (messageAction != MessageAction.None)
                    {
                        MessageService.Send(HttpContext.Current.Request, messageAction);
                    }
                }
                catch (Exception err)
                {
                    _successMessage = err.Message;
                    LogManager.GetLogger("ASC.Web.Confirm").Error(err);
                }
                finally
                {
                    if (authed)
                    {
                        SecurityContext.Logout();
                    }
                }

                var redirectLink = CommonLinkUtility.GetDefault();
                _successMessage = string.Format(_successMessage, redirectLink);

                _messageHolder.Visible        = true;
                _confirmContentHolder.Visible = false;
            }
            else
            {
                _messageHolder.Visible        = false;
                _confirmContentHolder.Visible = true;

                if (_type == ConfirmType.PortalRemove)
                {
                    _messageHolderPortalRemove.Visible = true;
                }
                else
                {
                    _messageHolderPortalRemove.Visible = false;
                }
            }
        }
Esempio n. 10
0
        public void SendMsgWhatsNew(DateTime scheduleDate, INotifyClient client)
        {
            var log = LogManager.GetLogger("ASC.Notify.WhatsNew");

            if (WebItemManager.Instance.GetItemsAll <IProduct>().Count == 0)
            {
                log.Info("No products. Return from function");
                return;
            }

            log.Info("Start send whats new.");

            var products = WebItemManager.Instance.GetItemsAll().ToDictionary(p => p.GetSysName());

            foreach (var tenantid in GetChangedTenants(scheduleDate))
            {
                try
                {
                    var tenant = CoreContext.TenantManager.GetTenant(tenantid);
                    if (tenant == null ||
                        tenant.Status != TenantStatus.Active ||
                        !TimeToSendWhatsNew(TenantUtil.DateTimeFromUtc(tenant.TimeZone, scheduleDate)) ||
                        TariffState.NotPaid <= CoreContext.PaymentManager.GetTariff(tenantid).State)
                    {
                        continue;
                    }

                    CoreContext.TenantManager.SetCurrentTenant(tenant);

                    log.InfoFormat("Start send whats new in {0} ({1}).", tenant.TenantDomain, tenantid);
                    foreach (var user in CoreContext.UserManager.GetUsers())
                    {
                        if (!IsSubscribeToWhatsNew(user))
                        {
                            continue;
                        }

                        SecurityContext.AuthenticateMe(CoreContext.Authentication.GetAccountByID(user.ID));

                        var culture = string.IsNullOrEmpty(user.CultureName) ? tenant.GetCulture() : user.GetCulture();

                        Thread.CurrentThread.CurrentCulture   = culture;
                        Thread.CurrentThread.CurrentUICulture = culture;

                        var feeds = FeedAggregateDataProvider.GetFeeds(new FeedApiFilter
                        {
                            From = scheduleDate.Date.AddDays(-1),
                            To   = scheduleDate.Date.AddSeconds(-1),
                            Max  = 100,
                        });

                        var feedMinWrappers = feeds.ConvertAll(f => f.ToFeedMin());

                        var feedMinGroupedWrappers = feedMinWrappers
                                                     .Where(f =>
                                                            (f.CreatedDate == DateTime.MaxValue || f.CreatedDate >= scheduleDate.Date.AddDays(-1)) && //'cause here may be old posts with new comments
                                                            products.ContainsKey(f.Product) &&
                                                            !f.Id.StartsWith("participant")
                                                            )
                                                     .GroupBy(f => products[f.Product]);

                        var ProjectsProductName = products["projects"].Name; //from ASC.Feed.Aggregator.Modules.ModulesHelper.ProjectsProductName

                        var activities = feedMinGroupedWrappers
                                         .Where(f => f.Key.Name != ProjectsProductName) //not for project product
                                         .ToDictionary(
                            g => g.Key.Name,
                            g => g.Select(f => new WhatsNewUserActivity
                        {
                            Date            = f.CreatedDate,
                            UserName        = f.Author != null && f.Author.UserInfo != null ? f.Author.UserInfo.DisplayUserName() : string.Empty,
                            UserAbsoluteURL = f.Author != null && f.Author.UserInfo != null ? CommonLinkUtility.GetFullAbsolutePath(f.Author.UserInfo.GetUserProfilePageURL()) : string.Empty,
                            Title           = HtmlUtil.GetText(f.Title, 512),
                            URL             = CommonLinkUtility.GetFullAbsolutePath(f.ItemUrl),
                            BreadCrumbs     = new string[0],
                            Action          = getWhatsNewActionText(f)
                        }).ToList());


                        var projectActivities = feedMinGroupedWrappers
                                                .Where(f => f.Key.Name == ProjectsProductName) // for project product
                                                .SelectMany(f => f);

                        var projectActivitiesWithoutBreadCrumbs = projectActivities.Where(p => String.IsNullOrEmpty(p.ExtraLocation));

                        var whatsNewUserActivityGroupByPrjs = new List <WhatsNewUserActivity>();

                        foreach (var prawbc in projectActivitiesWithoutBreadCrumbs)
                        {
                            whatsNewUserActivityGroupByPrjs.Add(
                                new WhatsNewUserActivity
                            {
                                Date            = prawbc.CreatedDate,
                                UserName        = prawbc.Author != null && prawbc.Author.UserInfo != null ? prawbc.Author.UserInfo.DisplayUserName() : string.Empty,
                                UserAbsoluteURL = prawbc.Author != null && prawbc.Author.UserInfo != null ? CommonLinkUtility.GetFullAbsolutePath(prawbc.Author.UserInfo.GetUserProfilePageURL()) : string.Empty,
                                Title           = HtmlUtil.GetText(prawbc.Title, 512),
                                URL             = CommonLinkUtility.GetFullAbsolutePath(prawbc.ItemUrl),
                                BreadCrumbs     = new string[0],
                                Action          = getWhatsNewActionText(prawbc)
                            });
                        }

                        var groupByPrjs = projectActivities.Where(p => !String.IsNullOrEmpty(p.ExtraLocation)).GroupBy(f => f.ExtraLocation);
                        foreach (var gr in groupByPrjs)
                        {
                            var grlist = gr.ToList();
                            for (var i = 0; i < grlist.Count(); i++)
                            {
                                var ls = grlist[i];
                                whatsNewUserActivityGroupByPrjs.Add(
                                    new WhatsNewUserActivity
                                {
                                    Date            = ls.CreatedDate,
                                    UserName        = ls.Author != null && ls.Author.UserInfo != null ? ls.Author.UserInfo.DisplayUserName() : string.Empty,
                                    UserAbsoluteURL = ls.Author != null && ls.Author.UserInfo != null ? CommonLinkUtility.GetFullAbsolutePath(ls.Author.UserInfo.GetUserProfilePageURL()) : string.Empty,
                                    Title           = HtmlUtil.GetText(ls.Title, 512),
                                    URL             = CommonLinkUtility.GetFullAbsolutePath(ls.ItemUrl),
                                    BreadCrumbs     = i == 0 ? new string[1] {
                                        gr.Key
                                    } : new string[0],
                                    Action = getWhatsNewActionText(ls)
                                });
                            }
                        }

                        if (whatsNewUserActivityGroupByPrjs.Count > 0)
                        {
                            activities.Add(ProjectsProductName, whatsNewUserActivityGroupByPrjs);
                        }

                        if (0 < activities.Count)
                        {
                            log.InfoFormat("Send whats new to {0}", user.Email);
                            client.SendNoticeAsync(
                                Constants.ActionSendWhatsNew, null, user, null,
                                new TagValue(Constants.TagActivities, activities),
                                new TagValue(Constants.TagDate, DateToString(scheduleDate.AddDays(-1), culture)),
                                new TagValue(CommonTags.Priority, 1)
                                );
                        }
                    }
                }
                catch (Exception error)
                {
                    log.Error(error);
                }
            }
        }
        protected override void Do()
        {
            try
            {
                SetProgress((int?)MailOperationCheckDomainDnsProgress.Init, "Setup tenant and user");

                CoreContext.TenantManager.SetCurrentTenant(CurrentTenant);

                try
                {
                    SecurityContext.AuthenticateMe(CurrentUser);
                }
                catch
                {
                    // User was removed
                    SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
                }

                ServerDomain domain;

                using (var daoFactory = new DaoFactory())
                {
                    var serverDomainDao = daoFactory.CreateServerDomainDao(CurrentTenant.TenantId);

                    var domains = serverDomainDao.GetDomains();

                    domain =
                        domains.FirstOrDefault(
                            d => d.Name.Equals(_domainName, StringComparison.InvariantCultureIgnoreCase));

                    if (domain == null)
                    {
                        throw new Exception(string.Format("Domain '{0}' not found", _domainName));
                    }
                }

                var hasChanges = false;

                SetProgress((int?)MailOperationCheckDomainDnsProgress.CheckMx, "Check DNS MX record");

                if (_dns.UpdateMx(domain.Name))
                {
                    hasChanges = true;
                }

                SetProgress((int?)MailOperationCheckDomainDnsProgress.CheckSpf, "Check DNS SPF record");

                if (_dns.UpdateSpf(domain.Name))
                {
                    hasChanges = true;
                }

                SetProgress((int?)MailOperationCheckDomainDnsProgress.CheckDkim, "Check DNS DKIM record");

                if (_dns.UpdateDkim(domain.Name))
                {
                    hasChanges = true;
                }

                if (!hasChanges)
                {
                    return;
                }

                SetProgress((int?)MailOperationCheckDomainDnsProgress.UpdateResults,
                            "Update domain dns check results");

                using (var daoFactory = new DaoFactory())
                {
                    var serverDnsDao = daoFactory.CreateServerDnsDao(CurrentTenant.TenantId, CurrentUser.ID.ToString());
                    serverDnsDao.Save(_dns);
                }
            }
            catch (Exception e)
            {
                Logger.ErrorFormat("Mail operation error -> Domain '{0}' dns check failed. Error: {1}", _domainName, e);
                Error = "InternalServerError";
            }
        }
Esempio n. 12
0
        private void SendMessage(ApiRequest requestInfo)
        {
            try
            {
                _log.DebugFormat("begin send request {0}", requestInfo);

                CoreContext.TenantManager.SetCurrentTenant(requestInfo.Tenant);
                var authKey = SecurityContext.AuthenticateMe(requestInfo.User.ID);

                if (string.IsNullOrEmpty(authKey))
                {
                    _log.ErrorFormat("can't obtain authorization cookie for user {0}", requestInfo.User.ID);
                    return;
                }

                var uri = BuildUri(requestInfo);
                _log.Debug(uri);

                _log.DebugFormat("builded uri for request {0}", uri);

                var request = (HttpWebRequest)WebRequest.Create(uri);
                request.Method                   = requestInfo.Method;
                request.AllowAutoRedirect        = true;
                request.Headers["Authorization"] = authKey;

                using (var requestStream = request.GetRequestStream())
                {
                    if (requestInfo.FilesToPost != null && requestInfo.FilesToPost.Any())
                    {
                        WriteMultipartRequest(request, requestStream, requestInfo);
                    }
                    else
                    {
                        WriteFormEncoded(request, requestStream, requestInfo, authKey);
                    }
                }

                try
                {
                    using (var response = request.GetResponse())
                        using (var responseStream = response.GetResponseStream())
                        {
                            if (responseStream != null)
                            {
                                using (var readStream = new StreamReader(responseStream))
                                {
                                    _log.DebugFormat("response from server: {0}", readStream.ReadToEnd());
                                }
                            }
                        }
                }
                catch (Exception error)
                {
                    _log.Error("error while getting the response", error);
                }

                _log.DebugFormat("end send request {0}", requestInfo);
            }
            catch (Exception x)
            {
                _log.Error("error while sending request", x);
                throw;
            }
        }
Esempio n. 13
0
        private void RemoveMailboxData(MailBox mailbox, bool totalMailRemove, ILogger log)
        {
            log.Info("RemoveMailboxData(id: {0} address: {1})", mailbox.MailBoxId, mailbox.EMail.ToString());

            try
            {
                if (!mailbox.IsRemoved)
                {
                    log.Info("Mailbox is't removed.");

                    var needRecalculateFolders = !totalMailRemove;

                    if (!mailbox.IsTeamlab)
                    {
                        log.Info("RemoveMailBox()");

                        _mailBoxManager.RemoveMailBox(mailbox, needRecalculateFolders);
                    }
                    else
                    {
                        log.Info("RemoveTeamlabMailbox()");

                        CoreContext.TenantManager.SetCurrentTenant(mailbox.TenantId);

                        SecurityContext.AuthenticateMe(Core.Configuration.Constants.CoreSystem);

                        RemoveTeamlabMailbox(mailbox);

                        _mailBoxManager.RemoveMailBox(mailbox, needRecalculateFolders);
                    }

                    mailbox.IsRemoved = true;
                }

                log.Debug("MailDataStore.GetDataStore(Tenant = {0})", mailbox.TenantId);

                var dataStorage = MailDataStore.GetDataStore(mailbox.TenantId);

                log.Debug("GetMailboxAttachsCount()");

                var countAttachs = _garbageManager.GetMailboxAttachsCount(mailbox);

                log.Info("Found {0} garbage attachments", countAttachs);

                if (countAttachs > 0)
                {
                    var sumCount = 0;

                    log.Debug("GetMailboxAttachsGarbage(limit = {0})", Config.MaxFilesToRemoveAtOnce);

                    var attachGrbgList = _garbageManager.GetMailboxAttachs(mailbox, Config.MaxFilesToRemoveAtOnce);

                    sumCount += attachGrbgList.Count;

                    log.Info("Clearing {0} garbage attachments ({1}/{2})", attachGrbgList.Count, sumCount, countAttachs);

                    while (attachGrbgList.Any())
                    {
                        dataStorage.QuotaController = null;

                        log.Debug("dataStorage.DeleteFiles()");

                        foreach (var attachGrbg in attachGrbgList)
                        {
                            try
                            {
                                dataStorage.Delete(string.Empty, attachGrbg.Path);
                            }
                            catch (Exception ex)
                            {
                                _log.Error("dataStorage.DeleteFiles(path: {0}) failed. Error: {1}", attachGrbg.Path, ex.ToString());
                            }
                        }

                        log.Debug("RemoveMailboxAttachsGarbage()");

                        _garbageManager.CleanupMailboxAttachs(attachGrbgList);

                        log.Debug("GetMailboxAttachsGarbage()");

                        attachGrbgList = _garbageManager.GetMailboxAttachs(mailbox, Config.MaxFilesToRemoveAtOnce);

                        if (!attachGrbgList.Any())
                        {
                            continue;
                        }

                        sumCount += attachGrbgList.Count;

                        log.Info("Found {0} garbage attachments ({1}/{2})", attachGrbgList.Count, sumCount,
                                 countAttachs);
                    }
                }

                log.Debug("GetMailboxMessagesCount()");

                var countMessages = _garbageManager.GetMailboxMessagesCount(mailbox);

                log.Info("Found {0} garbage messages", countMessages);

                if (countMessages > 0)
                {
                    var sumCount = 0;

                    log.Debug("GetMailboxMessagesGarbage(limit = {0})", Config.MaxFilesToRemoveAtOnce);

                    var messageGrbgList = _garbageManager.GetMailboxMessages(mailbox, Config.MaxFilesToRemoveAtOnce);

                    sumCount += messageGrbgList.Count;

                    log.Info("Clearing {0} garbage messages ({1}/{2})", messageGrbgList.Count, sumCount, countMessages);

                    while (messageGrbgList.Any())
                    {
                        dataStorage.QuotaController = null;

                        log.Debug("dataStorage.DeleteFiles()");

                        foreach (var mailMessageGarbage in messageGrbgList)
                        {
                            try
                            {
                                dataStorage.Delete(string.Empty, mailMessageGarbage.Path);
                            }
                            catch (Exception ex)
                            {
                                _log.Error("dataStorage.DeleteFiles(path: {0}) failed. Error: {1}", mailMessageGarbage.Path, ex.ToString());
                            }
                        }

                        log.Debug("RemoveMailboxMessagesGarbage()");

                        _garbageManager.CleanupMailboxMessages(messageGrbgList);

                        log.Debug("GetMailboxMessagesGarbage()");

                        messageGrbgList = _garbageManager.GetMailboxMessages(mailbox, Config.MaxFilesToRemoveAtOnce);

                        if (!messageGrbgList.Any())
                        {
                            continue;
                        }

                        sumCount += messageGrbgList.Count;

                        log.Info("Found {0} garbage messages ({1}/{2})", messageGrbgList.Count, sumCount,
                                 countMessages);
                    }
                }

                log.Debug("ClearMailboxData()");

                _garbageManager.CleanupMailboxData(mailbox, totalMailRemove);

                log.Debug("Garbage mailbox '{0}' was totaly removed.", mailbox.EMail.Address);
            }
            catch (Exception ex)
            {
                log.Error("RemoveMailboxData(mailboxId = {0}) Failure\r\nException: {1}", mailbox.MailBoxId, ex.ToString());
            }
        }
        public List <int> GetCrmContactIds(string email)
        {
            var ids = new List <int>();

            if (string.IsNullOrEmpty(email))
            {
                return(ids);
            }
            try
            {
                var q = new SqlQuery(CrmContactTable.TABLE_NAME.Alias(CC_ALIAS))
                        .Select(CrmContactTable.Columns.Id.Prefix(CC_ALIAS),
                                CrmContactTable.Columns.IsCompany.Prefix(CC_ALIAS),
                                CrmContactTable.Columns.IsShared.Prefix(CC_ALIAS))
                        .InnerJoin(CrmContactInfoTable.TABLE_NAME.Alias(CCI_ALIAS),
                                   Exp.EqColumns(CrmContactTable.Columns.Tenant.Prefix(CC_ALIAS),
                                                 CrmContactInfoTable.Columns.Tenant.Prefix(CCI_ALIAS)) &
                                   Exp.EqColumns(CrmContactTable.Columns.Id.Prefix(CC_ALIAS),
                                                 CrmContactInfoTable.Columns.ContactId.Prefix(CCI_ALIAS)))
                        .Where(CrmContactTable.Columns.Tenant.Prefix(CC_ALIAS), Tenant)
                        .Where(CrmContactInfoTable.Columns.Type.Prefix(CCI_ALIAS), (int)ContactInfoType.Email)
                        .Where(CrmContactInfoTable.Columns.Data.Prefix(CCI_ALIAS), email);

                var contactList = Db.ExecuteList(q)
                                  .ConvertAll(
                    r =>
                    new
                {
                    Id        = Convert.ToInt32(r[0]),
                    Company   = Convert.ToBoolean(r[1]),
                    ShareType = (ShareType)Convert.ToInt32(r[2])
                });

                if (!contactList.Any())
                {
                    return(ids);
                }

                CoreContext.TenantManager.SetCurrentTenant(Tenant);
                SecurityContext.AuthenticateMe(new Guid(CurrentUserId));

                foreach (var info in contactList)
                {
                    var contact = info.Company
                        ? new Company()
                        : (Contact) new Person();

                    contact.ID        = info.Id;
                    contact.ShareType = info.ShareType;

                    if (CRMSecurity.CanAccessTo(contact))
                    {
                        ids.Add(info.Id);
                    }
                }
            }
            catch (Exception e)
            {
                Log.WarnFormat("GetCrmContactsId(tenandId='{0}', userId='{1}', email='{2}') Exception:\r\n{3}\r\n",
                               Tenant, CurrentUserId, email, e.ToString());
            }

            return(ids);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            LoginMessage = Request["m"];

            Page.RegisterStyle("~/usercontrols/common/authorizedocs/css/authorizedocs.less");
            Page.RegisterBodyScripts("~/usercontrols/common/authorizedocs/js/authorizedocs.js", "~/usercontrols/common/authorize/js/authorize.js");

            Page.Title           = Resource.AuthDocsTitlePage;
            Page.MetaDescription = Resource.AuthDocsMetaDescription.HtmlEncode();
            Page.MetaKeywords    = Resource.AuthDocsMetaKeywords;

            PersonalFooterHolder.Controls.Add(LoadControl(PersonalFooter.PersonalFooter.Location));
            if (AccountLinkControl.IsNotEmpty)
            {
                HolderLoginWithThirdParty.Controls.Add(LoadControl(LoginWithThirdParty.Location));
                LoginSocialNetworks.Controls.Add(LoadControl(LoginWithThirdParty.Location));
            }
            pwdReminderHolder.Controls.Add(LoadControl(PwdTool.Location));

            if (IsPostBack)
            {
                try
                {
                    Login = Request["login"].Trim();
                    var password = Request["pwd"];
                    if (string.IsNullOrEmpty(Login) || string.IsNullOrEmpty(password))
                    {
                        throw new InvalidCredentialException(Resource.InvalidUsernameOrPassword);
                    }

                    // защита от перебора: на 5-ый неправильный ввод делать Sleep
                    var counter = 0;

                    int.TryParse(cache.Get <string>("loginsec/" + Login), out counter);

                    if (++counter % 5 == 0)
                    {
                        Thread.Sleep(TimeSpan.FromSeconds(10));
                    }
                    cache.Insert("loginsec/" + Login, counter, DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));

                    var session = string.IsNullOrEmpty(Request["remember"]);

                    var cookiesKey = SecurityContext.AuthenticateMe(Login, password);
                    CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey, session);
                    MessageService.Send(HttpContext.Current.Request, MessageAction.LoginSuccess);
                }
                catch (InvalidCredentialException)
                {
                    Auth.ProcessLogout();
                    LoginMessage = Resource.InvalidUsernameOrPassword;

                    var loginName = string.IsNullOrWhiteSpace(Login) ? AuditResource.EmailNotSpecified : Login;

                    MessageService.Send(HttpContext.Current.Request, loginName, MessageAction.LoginFailInvalidCombination);

                    return;
                }
                catch (System.Security.SecurityException)
                {
                    Auth.ProcessLogout();
                    LoginMessage = Resource.ErrorDisabledProfile;
                    MessageService.Send(HttpContext.Current.Request, Login, MessageAction.LoginFailDisabledProfile);
                    return;
                }
                catch (Exception ex)
                {
                    Auth.ProcessLogout();
                    LoginMessage = ex.Message;
                    MessageService.Send(HttpContext.Current.Request, Login, MessageAction.LoginFail);
                    return;
                }

                var refererURL = (string)Session["refererURL"];

                if (string.IsNullOrEmpty(refererURL))
                {
                    Response.Redirect(CommonLinkUtility.GetDefault());
                }
                else
                {
                    Session["refererURL"] = null;
                    Response.Redirect(refererURL);
                }
            }
            else
            {
                var confirmedEmail = Request.QueryString["confirmed-email"];

                if (String.IsNullOrEmpty(confirmedEmail) || !confirmedEmail.TestEmailRegex())
                {
                    return;
                }

                Login            = confirmedEmail;
                LoginMessage     = Resource.MessageEmailConfirmed + " " + Resource.MessageAuthorize;
                LoginMessageType = 1;
            }
        }
Esempio n. 16
0
 protected void ChangeProjectPrivate(bool @private)
 {
     SecurityContext.AuthenticateMe(Owner);
     Project.Private = @private;
     SaveOrUpdate(Project);
 }
Esempio n. 17
0
        private TrackResponse ProcessSave <T>(T fileId, TrackerData fileData)
        {
            var comments = new List <string>();

            if (fileData.Status == TrackerStatus.Corrupted ||
                fileData.Status == TrackerStatus.CorruptedForceSave)
            {
                comments.Add(FilesCommonResource.ErrorMassage_SaveCorrupted);
            }

            var forcesave = fileData.Status == TrackerStatus.ForceSave || fileData.Status == TrackerStatus.CorruptedForceSave;

            if (fileData.Users == null || fileData.Users.Count == 0 || !Guid.TryParse(fileData.Users[0], out var userId))
            {
                userId = FileTracker.GetEditingBy(fileId).FirstOrDefault();
            }

            var app = ThirdPartySelector.GetAppByFileId(fileId.ToString());

            if (app == null)
            {
                File <T> fileStable;
                fileStable = DaoFactory.GetFileDao <T>().GetFileStable(fileId);

                var docKey = DocumentServiceHelper.GetDocKey(fileStable);
                if (!fileData.Key.Equals(docKey))
                {
                    Logger.ErrorFormat("DocService saving file {0} ({1}) with key {2}", fileId, docKey, fileData.Key);

                    StoringFileAfterError(fileId, userId.ToString(), DocumentServiceConnector.ReplaceDocumentAdress(fileData.Url));
                    return(new TrackResponse {
                        Message = "Expected key " + docKey
                    });
                }
            }

            UserInfo user = null;

            try
            {
                SecurityContext.AuthenticateMe(userId);

                user = UserManager.GetUsers(userId);
                var culture = string.IsNullOrEmpty(user.CultureName) ? TenantManager.GetCurrentTenant().GetCulture() : CultureInfo.GetCultureInfo(user.CultureName);
                Thread.CurrentThread.CurrentCulture   = culture;
                Thread.CurrentThread.CurrentUICulture = culture;
            }
            catch (Exception ex)
            {
                Logger.Info("DocService save error: anonymous author - " + userId, ex);
                if (!userId.Equals(ASC.Core.Configuration.Constants.Guest.ID))
                {
                    comments.Add(FilesCommonResource.ErrorMassage_SaveAnonymous);
                }
            }

            File <T> file        = null;
            var      saveMessage = "Not saved";

            if (string.IsNullOrEmpty(fileData.Url))
            {
                try
                {
                    comments.Add(FilesCommonResource.ErrorMassage_SaveUrlLost);

                    file = EntryManager.CompleteVersionFile(fileId, 0, false, false);

                    DaoFactory.GetFileDao <T>().UpdateComment(file.ID, file.Version, string.Join("; ", comments));

                    file = null;
                    Logger.ErrorFormat("DocService save error. Empty url. File id: '{0}'. UserId: {1}. DocKey '{2}'", fileId, userId, fileData.Key);
                }
                catch (Exception ex)
                {
                    Logger.Error(string.Format("DocService save error. Version update. File id: '{0}'. UserId: {1}. DocKey '{2}'", fileId, userId, fileData.Key), ex);
                }
            }
            else
            {
                if (fileData.Encrypted)
                {
                    comments.Add(FilesCommonResource.CommentEditEncrypt);
                }

                var forcesaveType = ForcesaveType.None;
                if (forcesave)
                {
                    switch (fileData.ForceSaveType)
                    {
                    case TrackerData.ForceSaveInitiator.Command:
                        forcesaveType = ForcesaveType.Command;
                        break;

                    case TrackerData.ForceSaveInitiator.Timer:
                        forcesaveType = ForcesaveType.Timer;
                        break;

                    case TrackerData.ForceSaveInitiator.User:
                        forcesaveType = ForcesaveType.User;
                        break;
                    }
                    comments.Add(fileData.ForceSaveType == TrackerData.ForceSaveInitiator.User
                                     ? FilesCommonResource.CommentForcesave
                                     : FilesCommonResource.CommentAutosave);
                }

                try
                {
                    file        = EntryManager.SaveEditing(fileId, null, DocumentServiceConnector.ReplaceDocumentAdress(fileData.Url), null, string.Empty, string.Join("; ", comments), false, fileData.Encrypted, forcesaveType);
                    saveMessage = fileData.Status == TrackerStatus.MustSave || fileData.Status == TrackerStatus.ForceSave ? null : "Status " + fileData.Status;
                }
                catch (Exception ex)
                {
                    Logger.Error(string.Format("DocService save error. File id: '{0}'. UserId: {1}. DocKey '{2}'. DownloadUri: {3}", fileId, userId, fileData.Key, fileData.Url), ex);
                    saveMessage = ex.Message;

                    StoringFileAfterError(fileId, userId.ToString(), DocumentServiceConnector.ReplaceDocumentAdress(fileData.Url));
                }
            }

            if (!forcesave)
            {
                FileTracker.Remove(fileId);
            }

            if (file != null)
            {
                if (user != null)
                {
                    FilesMessageService.Send(file, MessageInitiator.DocsService, MessageAction.UserFileUpdated, user.DisplayUserName(false, DisplayUserSettingsHelper), file.Title);
                }

                if (!forcesave)
                {
                    SaveHistory(file, (fileData.History ?? "").ToString(), DocumentServiceConnector.ReplaceDocumentAdress(fileData.ChangesUrl));
                }
            }

            SocketManager.FilesChangeEditors(fileId, !forcesave);

            var result = new TrackResponse {
                Message = saveMessage
            };

            return(result);
        }
Esempio n. 18
0
 protected void ChangeProjectStatus(ProjectStatus status)
 {
     SecurityContext.AuthenticateMe(Owner);
     Project.Status = status;
     SaveOrUpdate(Project);
 }
Esempio n. 19
0
        public void UploadIcsToCalendar(MailBox mailBox, int calendarId, string calendarEventUid, string calendarIcs,
                                        string calendarCharset, string calendarContentType, string calendarEventReceiveEmail, string httpContextScheme, ILogger log)
        {
            try
            {
                if (string.IsNullOrEmpty(calendarEventUid) ||
                    string.IsNullOrEmpty(calendarIcs) ||
                    calendarContentType != "text/calendar")
                {
                    return;
                }

                var calendar = MailUtil.ParseValidCalendar(calendarIcs, log);

                if (calendar == null)
                {
                    return;
                }

                var alienEvent = true;

                var organizer = calendar.Events[0].Organizer;

                if (organizer != null)
                {
                    var orgEmail = calendar.Events[0].Organizer.Value.ToString()
                                   .ToLowerInvariant()
                                   .Replace("mailto:", "");

                    if (orgEmail.Equals(calendarEventReceiveEmail))
                    {
                        alienEvent = false;
                    }
                }
                else
                {
                    throw new ArgumentException("calendarIcs.organizer is null");
                }

                if (alienEvent)
                {
                    if (calendar.Events[0].Attendees.Any(
                            a =>
                            a.Value.ToString()
                            .ToLowerInvariant()
                            .Replace("mailto:", "")
                            .Equals(calendarEventReceiveEmail)))
                    {
                        alienEvent = false;
                    }
                }

                if (alienEvent)
                {
                    return;
                }

                CoreContext.TenantManager.SetCurrentTenant(mailBox.TenantId);
                SecurityContext.AuthenticateMe(new Guid(mailBox.UserId));

                using (var ms = new MemoryStream(EncodingTools.GetEncodingByCodepageName(calendarCharset).GetBytes(calendarIcs)))
                {
                    var apiHelper = new ApiHelper(httpContextScheme);
                    apiHelper.UploadIcsToCalendar(calendarId, ms, "calendar.ics", calendarContentType);
                }
            }
            catch (Exception ex)
            {
                log.Error("UploadIcsToCalendar with \r\n" +
                          "calendarId: {0}\r\n" +
                          "calendarEventUid: '{1}'\r\n" +
                          "calendarIcs: '{2}'\r\n" +
                          "calendarCharset: '{3}'\r\n" +
                          "calendarContentType: '{4}'\r\n" +
                          "calendarEventReceiveEmail: '{5}'\r\n" +
                          "Exception:\r\n{6}\r\n",
                          calendarId, calendarEventUid, calendarIcs, calendarCharset, calendarContentType,
                          calendarEventReceiveEmail, ex.ToString());
            }
        }
Esempio n. 20
0
 protected void RestrictAccess(Guid userID, ProjectTeamSecurity projectTeamSecurity, bool visible)
 {
     SecurityContext.AuthenticateMe(Owner);
     ProjectEngine.SetTeamSecurity(Project, ParticipantEngine.GetByID(userID), projectTeamSecurity, visible);
 }
        private static void ProcessMailMerge(string fileId, TrackerData fileData)
        {
            Guid userId;

            if (fileData.Users == null || fileData.Users.Count == 0 || !Guid.TryParse(fileData.Users[0], out userId))
            {
                userId = FileTracker.GetEditingBy(fileId).FirstOrDefault();
            }

            try
            {
                SecurityContext.AuthenticateMe(userId);

                if (string.IsNullOrEmpty(fileData.Url))
                {
                    throw new ArgumentException("emptry url");
                }

                if (fileData.MailMerge == null)
                {
                    throw new ArgumentException("MailMerge is null");
                }

                var    message = fileData.MailMerge.Message;
                Stream attach  = null;
                switch (fileData.MailMerge.Type)
                {
                case MailMergeType.AttachDocx:
                case MailMergeType.AttachPdf:
                    var downloadRequest = (HttpWebRequest)WebRequest.Create(fileData.Url);

                    // hack. http://ubuntuforums.org/showthread.php?t=1841740
                    if (WorkContext.IsMono)
                    {
                        ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
                    }

                    using (var downloadStream = new ResponseStream(downloadRequest.GetResponse()))
                    {
                        const int bufferSize = 2048;
                        var       buffer     = new byte[bufferSize];
                        int       readed;
                        attach = new MemoryStream();
                        while ((readed = downloadStream.Read(buffer, 0, bufferSize)) > 0)
                        {
                            attach.Write(buffer, 0, readed);
                        }
                        attach.Position = 0;
                    }

                    if (string.IsNullOrEmpty(fileData.MailMerge.Title))
                    {
                        fileData.MailMerge.Title = "Attach";
                    }

                    var attachExt = fileData.MailMerge.Type == MailMergeType.AttachDocx ? ".docx" : ".pdf";
                    var curExt    = FileUtility.GetFileExtension(fileData.MailMerge.Title);
                    if (curExt != attachExt)
                    {
                        fileData.MailMerge.Title += attachExt;
                    }

                    break;

                case MailMergeType.Html:
                    var httpWebRequest = (HttpWebRequest)WebRequest.Create(fileData.Url);

                    // hack. http://ubuntuforums.org/showthread.php?t=1841740
                    if (WorkContext.IsMono)
                    {
                        ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
                    }

                    using (var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
                        using (var stream = httpWebResponse.GetResponseStream())
                            if (stream != null)
                            {
                                using (var reader = new StreamReader(stream, Encoding.GetEncoding(Encoding.UTF8.WebName)))
                                {
                                    message = reader.ReadToEnd();
                                }
                            }
                    break;
                }

                using (var mailMergeTask =
                           new MailMergeTask
                {
                    From = fileData.MailMerge.From,
                    Subject = fileData.MailMerge.Subject,
                    To = fileData.MailMerge.To,
                    Message = message,
                    AttachTitle = fileData.MailMerge.Title,
                    Attach = attach
                })
                {
                    var response = mailMergeTask.Run();
                    Global.Logger.InfoFormat("DocService mailMerge {0}/{1} send: {2}",
                                             fileData.MailMerge.RecordIndex, fileData.MailMerge.RecordCount, response);
                }
            }
            catch (Exception ex)
            {
                Global.Logger.Error(
                    string.Format("DocService mailMerge{0} error: userId - {1}, url - {2}",
                                  (fileData.MailMerge == null ? "" : " " + fileData.MailMerge.RecordIndex + "/" + fileData.MailMerge.RecordCount),
                                  userId, fileData.Url),
                    ex);
            }

            if (fileData.MailMerge != null &&
                fileData.MailMerge.RecordIndex == fileData.MailMerge.RecordCount - 1)
            {
                NotifyClient.SendMailMergeEnd(userId, fileData.MailMerge.RecordCount);
            }
        }
        protected override void Do()
        {
            try
            {
                SetProgress((int?)MailOperationRemoveDomainProgress.Init, "Setup tenant and user");

                CoreContext.TenantManager.SetCurrentTenant(CurrentTenant);

                try
                {
                    SecurityContext.AuthenticateMe(CurrentUser);
                }
                catch
                {
                    // User was removed
                    SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
                }

                SetProgress((int?)MailOperationRemoveDomainProgress.RemoveFromDb, "Remove domain from Db");

                var tenant = CurrentTenant.TenantId;

                var mailboxes = new List <MailBoxData>();

                var engine = new EngineFactory(tenant);

                using (var db = DbManager.FromHttpContext(Defines.CONNECTION_STRING_NAME, Defines.RemoveDomainTimeout))
                {
                    var daoFactory = new DaoFactory(db);

                    using (var tx = daoFactory.DbManager.BeginTransaction(IsolationLevel.ReadUncommitted))
                    {
                        var serverGroupDao = daoFactory.CreateServerGroupDao(tenant);

                        var serverAddressDao = daoFactory.CreateServerAddressDao(tenant);

                        var groups = serverGroupDao.GetList(_domain.Id);

                        foreach (var serverGroup in groups)
                        {
                            serverAddressDao.DeleteAddressesFromMailGroup(serverGroup.Id);
                            serverAddressDao.Delete(serverGroup.AddressId);
                            serverGroupDao.Delete(serverGroup.Id);
                        }

                        var serverAddresses = serverAddressDao.GetDomainAddresses(_domain.Id);

                        var serverMailboxAddresses = serverAddresses.Where(a => a.MailboxId > -1 && !a.IsAlias);

                        foreach (var serverMailboxAddress in serverMailboxAddresses)
                        {
                            var mailbox =
                                engine.MailboxEngine.GetMailboxData(
                                    new ConcreteTenantServerMailboxExp(serverMailboxAddress.MailboxId, tenant, false));

                            if (mailbox == null)
                            {
                                continue;
                            }

                            mailboxes.Add(mailbox);

                            engine.MailboxEngine.RemoveMailBox(daoFactory, mailbox, false);
                        }

                        serverAddressDao.Delete(serverAddresses.Select(a => a.Id).ToList());

                        var serverDomainDao = daoFactory.CreateServerDomainDao(tenant);

                        serverDomainDao.Delete(_domain.Id);

                        var serverDao = daoFactory.CreateServerDao();
                        var server    = serverDao.Get(tenant);

                        var serverEngine = new Server.Core.ServerEngine(server.Id, server.ConnectionString);

                        serverEngine.RemoveDomain(_domain.Name);

                        tx.Commit();
                    }
                }

                SetProgress((int?)MailOperationRemoveDomainProgress.ClearCache, "Clear accounts cache");

                CacheEngine.ClearAll();

                SetProgress((int?)MailOperationRemoveDomainProgress.RemoveIndex, "Remove Elastic Search index by messages");

                foreach (var mailbox in mailboxes)
                {
                    engine.IndexEngine.Remove(mailbox);
                }
            }
            catch (Exception e)
            {
                Logger.Error("Mail operation error -> Remove mailbox: {0}", e);
                Error = "InternalServerError";
            }
        }
Esempio n. 23
0
            public void RunJob()
            {
                Status = (int)Operation.Success;
                CoreContext.TenantManager.SetCurrentTenant((int)Id);
                SecurityContext.AuthenticateMe(UserId);

                if (!SecurityContext.CheckPermissions(Constants.Action_AddRemoveUser))
                {
                    Error       = Resources.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 = Resources.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 = Resources.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;
            }
Esempio n. 24
0
        private bool CheckValidationKey()
        {
            var key      = Request["key"] ?? "";
            var emplType = Request["emplType"] ?? "";
            var social   = Request["social"] ?? "";

            var validInterval = SetupInfo.ValidEmailKeyInterval;
            var authInterval  = SetupInfo.ValidAuthKeyInterval;

            EmailValidationKeyProvider.ValidationResult checkKeyResult;
            switch (_type)
            {
            case ConfirmType.PortalContinue:
                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_email + _type, key);
                break;

            case ConfirmType.PhoneActivation:
            case ConfirmType.PhoneAuth:
            case ConfirmType.TfaActivation:
            case ConfirmType.TfaAuth:
                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_email + _type, key, authInterval);
                break;

            case ConfirmType.Auth:
            {
                var first      = Request["first"] ?? "";
                var module     = Request["module"] ?? "";
                var smsConfirm = Request["sms"] ?? "";

                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_email + _type + first + module + smsConfirm, key, authInterval);

                if (checkKeyResult == EmailValidationKeyProvider.ValidationResult.Ok)
                {
                    var user = _email.Contains("@")
                                           ? CoreContext.UserManager.GetUserByEmail(_email)
                                           : CoreContext.UserManager.GetUsers(new Guid(_email));

                    if (SecurityContext.IsAuthenticated && SecurityContext.CurrentAccount.ID != user.ID)
                    {
                        Auth.ProcessLogout();
                    }

                    if (!SecurityContext.IsAuthenticated)
                    {
                        if (!CoreContext.UserManager.UserExists(user.ID) || user.Status != EmployeeStatus.Active)
                        {
                            ShowError(Auth.MessageKey.ErrorUserNotFound);
                            return(false);
                        }

                        if (StudioSmsNotificationSettings.IsVisibleSettings && StudioSmsNotificationSettings.Enable && smsConfirm.ToLower() != "true")
                        {
                            //todo: think about 'first' & 'module'
                            Response.Redirect(SmsConfirmUrl(user), true);
                        }

                        if (TfaAppAuthSettings.IsVisibleSettings && TfaAppAuthSettings.Enable)
                        {
                            //todo: think about 'first' & 'module'
                            Response.Redirect(TfaConfirmUrl(user), true);
                        }

                        var authCookie = SecurityContext.AuthenticateMe(user.ID);
                        CookiesManager.SetCookies(CookiesType.AuthKey, authCookie);

                        var messageAction = social == "true" ? MessageAction.LoginSuccessViaSocialAccount : MessageAction.LoginSuccess;
                        MessageService.Send(HttpContext.Current.Request, messageAction);
                    }

                    SetDefaultModule(module);

                    AuthRedirect(first.ToLower() == "true");
                }
            }
            break;

            case ConfirmType.DnsChange:
            {
                var dnsChangeKey = string.Join(string.Empty, new[] { _email, _type.ToString(), Request["dns"], Request["alias"] });
                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(dnsChangeKey, key, validInterval);
            }
            break;

            case ConfirmType.PortalOwnerChange:
            {
                Guid uid;
                try
                {
                    uid = new Guid(Request["uid"]);
                }
                catch
                {
                    uid = Guid.Empty;
                }
                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_email + _type + uid, key, validInterval);
            }
            break;

            case ConfirmType.EmpInvite:
                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_email + _type + emplType, key, validInterval);
                break;

            case ConfirmType.LinkInvite:
                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_type + emplType, key, validInterval);
                break;

            case ConfirmType.EmailChange:
                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_email + _type + SecurityContext.CurrentAccount.ID, key, validInterval);
                break;

            case ConfirmType.PasswordChange:
                var hash = CoreContext.Authentication.GetUserPasswordStamp(CoreContext.UserManager.GetUserByEmail(_email).ID).ToString("s");

                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_email + _type + hash, key, validInterval);
                break;

            default:
                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_email + _type, key, validInterval);
                break;
            }

            if (checkKeyResult == EmailValidationKeyProvider.ValidationResult.Expired)
            {
                ShowError(Auth.MessageKey.ErrorExpiredActivationLink);
                return(false);
            }

            if (checkKeyResult == EmailValidationKeyProvider.ValidationResult.Invalid)
            {
                ShowError(_type == ConfirmType.LinkInvite
                              ? Auth.MessageKey.ErrorInvalidActivationLink
                              : Auth.MessageKey.ErrorConfirmURLError);
                return(false);
            }

            if (!string.IsNullOrEmpty(_email) && !_email.TestEmailRegex())
            {
                ShowError(Auth.MessageKey.ErrorNotCorrectEmail);
                return(false);
            }

            return(true);
        }
Esempio n. 25
0
        public void RunJob()
        {
            var logger = log4net.LogManager.GetLogger("ASC.Web");

            try
            {
                Percentage = 0;
                Status     = ProgressStatus.Started;

                CoreContext.TenantManager.SetCurrentTenant(_tenantId);
                SecurityContext.AuthenticateMe(Core.Configuration.Constants.CoreSystem);

                long docsSpace, crmSpace, mailSpace, talkSpace;
                GetUsageSpace(out docsSpace, out mailSpace, out talkSpace);

                logger.InfoFormat("deleting user data for {0} ", _userId);

                logger.Info("deleting of data from documents");

                Percentage = 25;
                _docService.DeleteStorage(_userId);

                logger.Info("deleting of data from crm");

                Percentage = 50;
                using (var scope = DIHelper.Resolve(_tenantId))
                {
                    var crmDaoFactory = scope.Resolve <CrmDaoFactory>();
                    crmSpace = crmDaoFactory.ReportDao.GetFiles(_userId).Sum(file => file.ContentLength);
                    crmDaoFactory.ReportDao.DeleteFiles(_userId);
                }

                logger.Info("deleting of data from mail");

                Percentage = 75;
                _mailEraser.ClearUserMail(_userId);

                logger.Info("deleting of data from talk");

                Percentage = 99;
                DeleteTalkStorage();

                SendSuccessNotify(docsSpace, crmSpace, mailSpace, talkSpace);

                Percentage = 100;
                Status     = ProgressStatus.Done;
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Status = ProgressStatus.Failed;
                Error  = ex.Message;
                SendErrorNotify(ex.Message);
            }
            finally
            {
                logger.Info("data deletion is complete");
                IsCompleted = true;
                SecurityContext.AuthenticateMe(_currentUserId);
            }
        }
        public List <MailTag> GetTagsList(int id_tenant, string id_user, bool mail_only)
        {
            var tags = new Dictionary <int, MailTag>();

            using (var db = GetDb())
            {
                db.ExecuteList(new SqlQuery(MAIL_TAG)
                               .Select(TagFields.id, TagFields.name, TagFields.style, TagFields.addresses, TagFields.count, TagFields.crm_id)
                               .Where(GetUserWhere(id_user, id_tenant)))
                .ForEach(r =>
                         tags.Add(0 < Convert.ToInt32(r[5]) ? -Convert.ToInt32(r[5]) : Convert.ToInt32(r[0]),
                                  new MailTag((0 < Convert.ToInt32(r[5]) && !mail_only) ? -Convert.ToInt32(r[5]) : Convert.ToInt32(r[0])
                                              , (string)r[1]
                                              , !string.IsNullOrEmpty(r[3].ToString()) ? r[3].ToString().Split(';').ToList() : new List <string>()
                                              , ConvertToString(r[2])
                                              , Convert.ToInt32(r[4])))
                         );
            }

            if (mail_only)
            {
                return(tags.Values.Where(p => p.Name != "").OrderByDescending(p => p.Id).ToList());
            }

            #region Set up connection to CRM sequrity
            CoreContext.TenantManager.SetCurrentTenant(id_tenant);
            SecurityContext.AuthenticateMe(CoreContext.Authentication.GetAccountByID(new Guid(id_user)));

            if (!WebItemSecurity.IsAvailableForUser(WebItemManager.CRMProductID.ToString(),
                                                    SecurityContext.CurrentAccount.ID))
            {
                return(tags.Values.Where(p => p.Name != "").OrderByDescending(p => p.Id).ToList());
            }

            #endregion

            using (var db = new DbManager("crm"))
            {
                var q = new SqlQuery(CRM_TAG + " t")
                        .Select("t." + CrmTagFields.id, "t." + CrmTagFields.title)
                        .Where(Exp.Eq("t." + CrmTagFields.tenant_id, id_tenant))
                        .Where(Exp.Eq("t." + CrmTagFields.entity_type, CRM_CONTACT_ENTITY_TYPE));

                var crm_tags = db.ExecuteList(q)
                               .ConvertAll(r =>
                                           new MailTag(-Convert.ToInt32(r[0])
                                                       , (string)r[1]
                                                       , new List <string>()
                                                       , ""
                                                       , 0));

                foreach (var tag in crm_tags)
                {
                    if (tags.ContainsKey(tag.Id))
                    {
                        tags[tag.Id].Name = tag.Name;
                    }
                    else
                    {
                        tags.Add(tag.Id, tag);
                    }
                }
            }

            return(tags.Values.Where(t => t.Name != "").OrderByDescending(p => p.Id).ToList());
        }
Esempio n. 27
0
        private static void RemoveMailboxData(MailBoxData mailbox, bool totalMailRemove, ILog log)
        {
            log.InfoFormat("RemoveMailboxData(id: {0} address: {1})", mailbox.MailBoxId, mailbox.EMail.ToString());

            try
            {
                if (!mailbox.IsRemoved)
                {
                    log.Info("Mailbox is't removed.");

                    var needRecalculateFolders = !totalMailRemove;

                    if (mailbox.IsTeamlab)
                    {
                        log.Info("RemoveTeamlabMailbox()");

                        CoreContext.TenantManager.SetCurrentTenant(mailbox.TenantId);
                        SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);

                        RemoveTeamlabMailbox(mailbox, log);
                    }

                    log.Info("SetMailboxRemoved()");
                    var engine = new EngineFactory(mailbox.TenantId, mailbox.UserId);
                    engine.MailboxEngine.RemoveMailBox(mailbox, needRecalculateFolders);

                    mailbox.IsRemoved = true;
                }

                log.DebugFormat("MailDataStore.GetDataStore(Tenant = {0})", mailbox.TenantId);

                var dataStorage = MailDataStore.GetDataStore(mailbox.TenantId);

                dataStorage.QuotaController = null;

                log.Debug("GetMailboxAttachsCount()");

                var mailGarbageDao = new MailGarbageDao();

                var countAttachs = mailGarbageDao.GetMailboxAttachsCount(mailbox);

                log.InfoFormat("Found {0} garbage attachments", countAttachs);

                if (countAttachs > 0)
                {
                    var sumCount = 0;

                    log.DebugFormat("GetMailboxAttachsGarbage(limit = {0})", Config.MaxFilesToRemoveAtOnce);

                    var attachGrbgList = mailGarbageDao.GetMailboxAttachs(mailbox, Config.MaxFilesToRemoveAtOnce);

                    sumCount += attachGrbgList.Count;

                    log.InfoFormat("Clearing {0} garbage attachments ({1}/{2})", attachGrbgList.Count, sumCount, countAttachs);

                    while (attachGrbgList.Any())
                    {
                        foreach (var attachGrbg in attachGrbgList)
                        {
                            RemoveFile(dataStorage, attachGrbg.Path, log);
                        }

                        log.Debug("CleanupMailboxAttachs()");

                        mailGarbageDao.CleanupMailboxAttachs(attachGrbgList);

                        log.Debug("GetMailboxAttachs()");

                        attachGrbgList = mailGarbageDao.GetMailboxAttachs(mailbox, Config.MaxFilesToRemoveAtOnce);

                        if (!attachGrbgList.Any())
                        {
                            continue;
                        }

                        sumCount += attachGrbgList.Count;

                        log.InfoFormat("Found {0} garbage attachments ({1}/{2})", attachGrbgList.Count, sumCount,
                                       countAttachs);
                    }
                }

                log.Debug("GetMailboxMessagesCount()");

                var countMessages = mailGarbageDao.GetMailboxMessagesCount(mailbox);

                log.InfoFormat("Found {0} garbage messages", countMessages);

                if (countMessages > 0)
                {
                    var sumCount = 0;

                    log.DebugFormat("GetMailboxMessagesGarbage(limit = {0})", Config.MaxFilesToRemoveAtOnce);

                    var messageGrbgList = mailGarbageDao.GetMailboxMessages(mailbox, Config.MaxFilesToRemoveAtOnce);

                    sumCount += messageGrbgList.Count;

                    log.InfoFormat("Clearing {0} garbage messages ({1}/{2})", messageGrbgList.Count, sumCount, countMessages);

                    while (messageGrbgList.Any())
                    {
                        foreach (var mailMessageGarbage in messageGrbgList)
                        {
                            RemoveFile(dataStorage, mailMessageGarbage.Path, log);
                        }

                        log.Debug("CleanupMailboxMessages()");

                        mailGarbageDao.CleanupMailboxMessages(messageGrbgList);

                        log.Debug("GetMailboxMessages()");

                        messageGrbgList = mailGarbageDao.GetMailboxMessages(mailbox, Config.MaxFilesToRemoveAtOnce);

                        if (!messageGrbgList.Any())
                        {
                            continue;
                        }

                        sumCount += messageGrbgList.Count;

                        log.InfoFormat("Found {0} garbage messages ({1}/{2})", messageGrbgList.Count, sumCount,
                                       countMessages);
                    }
                }

                log.Debug("ClearMailboxData()");

                mailGarbageDao.CleanupMailboxData(mailbox, totalMailRemove);

                log.DebugFormat("Garbage mailbox '{0}' was totaly removed.", mailbox.EMail.Address);
            }
            catch (Exception ex)
            {
                log.ErrorFormat("RemoveMailboxData(mailboxId = {0}) Failure\r\nException: {1}", mailbox.MailBoxId, ex.ToString());

                throw;
            }
        }
Esempio n. 28
0
        private string AttachToMail()
        {
            if (Attach == null)
            {
                return(string.Empty);
            }

            if (string.IsNullOrEmpty(AttachTitle))
            {
                AttachTitle = "attach.pdf";
            }

            var apiUrlAttach = string.Format("{0}mail/messages/attachment/add?id_message={1}&name={2}",
                                             SetupInfo.WebApiBaseUrl,
                                             MessageId,
                                             AttachTitle);

            var request = (HttpWebRequest)WebRequest.Create(CommonLinkUtility.GetFullAbsolutePath(apiUrlAttach));

            request.Method        = "POST";
            request.ContentType   = MimeMapping.GetMimeMapping(AttachTitle);
            request.ContentLength = Attach.Length;
            request.Headers.Add("Authorization", SecurityContext.AuthenticateMe(SecurityContext.CurrentAccount.ID));

            const int bufferSize = 2048;
            var       buffer     = new byte[bufferSize];
            int       readed;

            while ((readed = Attach.Read(buffer, 0, bufferSize)) > 0)
            {
                request.GetRequestStream().Write(buffer, 0, readed);
            }

            // hack. http://ubuntuforums.org/showthread.php?t=1841740
            if (WorkContext.IsMono)
            {
                ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
            }

            string responseAttachString;

            using (var response = request.GetResponse())
                using (var stream = response.GetResponseStream())
                {
                    if (stream == null)
                    {
                        throw new WebException("Could not get an answer");
                    }
                    using (var reader = new StreamReader(stream))
                    {
                        responseAttachString = reader.ReadToEnd();
                    }
                }

            var responseAttach = JObject.Parse(responseAttachString);

            if (responseAttach["statusCode"].Value <int>() != (int)HttpStatusCode.Created)
            {
                throw new Exception("Attach failed: " + responseAttach["error"]["message"].Value <string>());
            }

            var bodySendAttach =
                "&attachments%5B0%5D%5BfileId%5D=" + HttpUtility.UrlEncode(responseAttach["response"]["fileId"].Value <string>())
                + "&attachments%5B0%5D%5BfileName%5D=" + HttpUtility.UrlEncode(responseAttach["response"]["fileName"].Value <string>())
                + "&attachments%5B0%5D%5Bsize%5D=" + HttpUtility.UrlEncode(responseAttach["response"]["size"].Value <string>())
                + "&attachments%5B0%5D%5BcontentType%5D=" + HttpUtility.UrlEncode(responseAttach["response"]["contentType"].Value <string>())
                + "&attachments%5B0%5D%5BfileNumber%5D=" + HttpUtility.UrlEncode(responseAttach["response"]["fileNumber"].Value <string>())
                + "&attachments%5B0%5D%5BstoredName%5D=" + HttpUtility.UrlEncode(responseAttach["response"]["storedName"].Value <string>())
                + "&attachments%5B0%5D%5BstreamId%5D=" + HttpUtility.UrlEncode(responseAttach["response"]["streamId"].Value <string>())
            ;

            return(bodySendAttach);
        }
Esempio n. 29
0
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            JsonMediaTypeFormatter jsonMediaTypeFormatter = new JsonMediaTypeFormatter();

            try
            {
                log.Debug("HealthCheckAuthorizationFilterAttribute OnActionExecuted");

                /*
                 * var healthCheckSettingsAccessor = new HealthCheckSettingsAccessor();
                 * var healthCheckSettings = healthCheckSettingsAccessor.GetHealthCheckSettings();
                 *
                 * var tenants = CoreContext.TenantManager.GetTenants().Where(t => t.TenantId != healthCheckSettings.FakeTenantId).ToList();
                 *
                 * if (!CoreContext.TenantManager.GetTenantQuota(tenants.First().TenantId).HealthCheck)
                 * {
                 *  log.Debug("There is no correct license for HealthCheck.");
                 *
                 *  actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden)
                 *  {
                 *      Content = new ObjectContent<object>(HealthCheckResource.ErrorNotAllowedOption, jsonMediaTypeFormatter)
                 *  };
                 *
                 *  return;
                 * }
                 */
                string authorizationHeaderValue = null;
                foreach (var header in actionContext.Request.Headers)
                {
                    if (header.Key == "Authorization")
                    {
                        if (header.Value == null)
                        {
                            log.Error("User Unauthorized, Authorization header.Value is null");
                            actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
                            return;
                        }
                        foreach (var headerValue in header.Value)
                        {
                            authorizationHeaderValue = headerValue;
                        }
                        break;
                    }
                }
                if (authorizationHeaderValue == null)
                {
                    log.Error("User Unauthorized, authorizationHeaderValue is null");
                    actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
                    return;
                }
                var authorization = authorizationHeaderValue.Split(',');
                if (authorization.Length != 2)
                {
                    log.ErrorFormat("User Unauthorized, authorization is null or authorization.Length = {0}", authorization.Length);
                    actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
                    return;
                }
                var portalInfo = authorization[0].Split(' ');
                if (portalInfo.Length == 2)
                {
                    authorization[0] = portalInfo[1];
                }
                CoreContext.TenantManager.SetCurrentTenant(authorization[0]);
                SecurityContext.AuthenticateMe(authorization[1]);
                ResolveUserCulture();
            }
            catch (Exception ex)
            {
                log.ErrorFormat("Unexpected error on HealthCheckAuthorizationFilterAttribute: {0} {1}",
                                ex.ToString(), ex.InnerException != null ? ex.InnerException.Message : string.Empty);
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
                {
                    Content = new ObjectContent <object>(ex.ToString(), jsonMediaTypeFormatter)
                };
            }
        }
        public static UserInfo GetUserByThirdParty(LoginProfile loginProfile)
        {
            try
            {
                if (!string.IsNullOrEmpty(loginProfile.AuthorizationError))
                {
                    // ignore cancellation
                    if (loginProfile.AuthorizationError != "Canceled at provider")
                    {
                        throw new Exception(loginProfile.AuthorizationError);
                    }
                    return(Constants.LostUser);
                }

                var userInfo = Constants.LostUser;

                Guid userId;
                if (TryGetUserByHash(loginProfile.HashId, out userId))
                {
                    userInfo = CoreContext.UserManager.GetUsers(userId);
                }

                var isNew = false;
                if (CoreContext.Configuration.Personal)
                {
                    if (CoreContext.UserManager.UserExists(userInfo.ID) && SetupInfo.IsSecretEmail(userInfo.Email))
                    {
                        try
                        {
                            SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
                            CoreContext.UserManager.DeleteUser(userInfo.ID);
                            userInfo = Constants.LostUser;
                        }
                        finally
                        {
                            SecurityContext.Logout();
                        }
                    }

                    if (!CoreContext.UserManager.UserExists(userInfo.ID))
                    {
                        userInfo = JoinByThirdPartyAccount(loginProfile);

                        isNew = true;
                    }
                }

                if (isNew)
                {
                    var spam = HttpContext.Current.Request["spam"];
                    if (spam != "on")
                    {
                        try
                        {
                            const string _databaseID = "com";
                            using (var db = DbManager.FromHttpContext(_databaseID))
                            {
                                db.ExecuteNonQuery(new SqlInsert("template_unsubscribe", false)
                                                   .InColumnValue("email", userInfo.Email.ToLowerInvariant())
                                                   .InColumnValue("reason", "personal")
                                                   );
                                LogManager.GetLogger("ASC.Web").Debug(String.Format("Write to template_unsubscribe {0}", userInfo.Email.ToLowerInvariant()));
                            }
                        }
                        catch (Exception ex)
                        {
                            LogManager.GetLogger("ASC.Web").Debug(String.Format("ERROR write to template_unsubscribe {0}, email:{1}", ex.Message, userInfo.Email.ToLowerInvariant()));
                        }
                    }

                    var analytics = HttpContext.Current.Request["analytics"] == "on";
                    var settings  = TenantAnalyticsSettings.LoadForCurrentUser();
                    settings.Analytics = analytics;
                    settings.SaveForCurrentUser();

                    StudioNotifyService.Instance.UserHasJoin();
                    UserHelpTourHelper.IsNewUser = true;
                    PersonalSettings.IsNewUser   = true;
                }

                return(userInfo);
            }
            catch (Exception)
            {
                Auth.ProcessLogout();
                throw;
            }
        }