[Create(@"{code}", false, false)] //NOTE: this method doesn't requires auth!!!  //NOTE: this method doesn't check payment!!!
        public AuthenticationTokenData AuthenticateMe(string userName, string password, string provider, string accessToken, string code)
        {
            bool viaEmail;
            var  user = GetUser(userName, password, provider, accessToken, out viaEmail);

            try
            {
                SmsManager.ValidateSmsCode(user, code);

                var token = SecurityContext.AuthenticateMe(user.ID);

                MessageService.Send(Request, MessageAction.LoginSuccessViaApiSms);

                var tenant  = CoreContext.TenantManager.GetCurrentTenant().TenantId;
                var expires = TenantCookieSettings.GetExpiresTime(tenant);

                return(new AuthenticationTokenData
                {
                    Token = token,
                    Expires = new ApiDateTime(expires),
                    Sms = true,
                    PhoneNoise = SmsSender.BuildPhoneNoise(user.MobilePhone)
                });
            }
            catch
            {
                MessageService.Send(Request, user.DisplayUserName(false), MessageAction.LoginFailViaApiSms, MessageTarget.Create(user.ID));
                throw new AuthenticationException("User authentication failed");
            }
            finally
            {
                SecurityContext.Logout();
            }
        }
        public static void SetLifeTime(int lifeTime)
        {
            if (!CoreContext.UserManager.IsUserInGroup(SecurityContext.CurrentAccount.ID, Constants.GroupAdmin.ID))
            {
                throw new SecurityException();
            }

            var tenant   = TenantProvider.CurrentTenantID;
            var settings = TenantCookieSettings.GetForTenant(tenant);

            if (lifeTime > 0)
            {
                settings.Index    = settings.Index + 1;
                settings.LifeTime = lifeTime;
            }
            else
            {
                settings.LifeTime = 0;
            }

            TenantCookieSettings.SetForTenant(tenant, settings);

            var cookie = SecurityContext.AuthenticateMe(SecurityContext.CurrentAccount.ID);

            SetCookies(CookiesType.AuthKey, cookie);
        }
        public static string AuthenticateMeAndSetCookies(int tenantId, Guid userId, MessageAction action, bool session = false)
        {
            bool       isSuccess      = true;
            var        cookies        = string.Empty;
            Func <int> funcLoginEvent = () => { return(GetLoginEventId(action)); };

            try
            {
                cookies = SecurityContext.AuthenticateMe(userId, funcLoginEvent);
            }
            catch (Exception)
            {
                isSuccess = false;
                throw;
            }
            finally
            {
                if (isSuccess)
                {
                    SetCookies(CookiesType.AuthKey, cookies, session);
                    DbLoginEventsManager.ResetCache(tenantId, userId);
                }
            }

            return(cookies);
        }
Example #4
0
        private void RequestCode(HttpContext context)
        {
            var token = GetToken(context.Request.Query["code"]);

            if (token == null)
            {
                Logger.Error("BoxApp: token is null");
                throw new SecurityException("Access token is null");
            }

            var boxUserId = context.Request.Query["userId"];

            if (AuthContext.IsAuthenticated)
            {
                if (!CurrentUser(boxUserId))
                {
                    Logger.Debug("BoxApp: logout for " + boxUserId);
                    CookiesManager.ClearCookies(CookiesType.AuthKey);
                    AuthContext.Logout();
                }
            }

            if (!AuthContext.IsAuthenticated)
            {
                var userInfo = GetUserInfo(token, out var isNew);

                if (userInfo == null)
                {
                    Logger.Error("BoxApp: UserInfo is null");
                    throw new Exception("Profile is null");
                }

                var cookiesKey = SecurityContext.AuthenticateMe(userInfo.ID);
                CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey);
                MessageService.Send(MessageAction.LoginSuccessViaSocialApp);

                if (isNew)
                {
                    var userHelpTourSettings = SettingsManager.LoadForCurrentUser <UserHelpTourSettings>();
                    userHelpTourSettings.IsNewUser = true;
                    SettingsManager.SaveForCurrentUser(userHelpTourSettings);

                    PersonalSettingsHelper.IsNewUser      = true;
                    PersonalSettingsHelper.IsNotActivated = true;
                }

                if (!string.IsNullOrEmpty(boxUserId) && !CurrentUser(boxUserId))
                {
                    AddLinker(boxUserId);
                }
            }

            TokenHelper.SaveToken(token);

            var fileId = context.Request.Query["id"];

            context.Response.Redirect(FilesLinkUtility.GetFileWebEditorUrl(ThirdPartySelector.BuildAppFileId(AppAttr, fileId)), true);
        }
        public void RunJob(DistributedTask _, CancellationToken cancellationToken)
        {
            try
            {
                CancellationToken = cancellationToken;

                CoreContext.TenantManager.SetCurrentTenant(CurrentTenant);

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

                Thread.CurrentThread.CurrentCulture   = CultureInfo.GetCultureInfo(_culture);
                Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(_culture);

                Logger = LogManager.GetLogger("ASC.Mail.Operation");

                Do();
            }
            catch (AuthorizingException authError)
            {
                Error = "ErrorAccessDenied";
                Logger.Error(Error, new SecurityException(Error, authError));
            }
            catch (AggregateException ae)
            {
                ae.Flatten().Handle(e => e is TaskCanceledException || e is OperationCanceledException);
            }
            catch (TenantQuotaException e)
            {
                Error = "TenantQuotaSettled";
                Logger.Error("TenantQuotaException. {0}", e);
            }
            catch (FormatException e)
            {
                Error = "CantCreateUsers";
                Logger.Error("FormatException error. {0}", e);
            }
            catch (Exception e)
            {
                Error = "InternalServerError";
                Logger.Error("Internal server error. {0}", e);
            }
            finally
            {
                try
                {
                    TaskInfo.SetProperty(FINISHED, true);
                    PublishTaskInfo();
                }
                catch
                {
                    /* ignore */
                }
            }
        }
Example #6
0
        private static void RequestCode(HttpContext context)
        {
            var token = GetToken(context.Request["code"]);

            if (token == null)
            {
                Global.Logger.Error("BoxApp: token is null");
                throw new SecurityException("Access token is null");
            }

            var boxUserId = context.Request["userId"];

            if (SecurityContext.IsAuthenticated)
            {
                if (!CurrentUser(boxUserId))
                {
                    Global.Logger.Debug("BoxApp: logout for " + boxUserId);
                    CookiesManager.ClearCookies(CookiesType.AuthKey);
                    SecurityContext.Logout();
                }
            }

            if (!SecurityContext.IsAuthenticated)
            {
                bool isNew;
                var  userInfo = GetUserInfo(token, out isNew);

                if (userInfo == null)
                {
                    Global.Logger.Error("BoxApp: UserInfo is null");
                    throw new Exception("Profile is null");
                }

                var cookiesKey = SecurityContext.AuthenticateMe(userInfo.ID);
                CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey);

                if (isNew)
                {
                    UserHelpTourHelper.IsNewUser = true;
                    PersonalSettings.IsNewUser   = true;
                }

                if (!string.IsNullOrEmpty(boxUserId) && !CurrentUser(boxUserId))
                {
                    AddLinker(boxUserId);
                }
            }

            Token.SaveToken(AppAttr, token);

            var fileId = context.Request["id"];

            context.Response.Redirect(FilesLinkUtility.GetFileWebEditorUrl(ThirdPartySelector.BuildAppFileId(AppAttr, fileId)), true);
        }
        private static void BulkDownloadFile(HttpContext context)
        {
            if (!SecurityContext.AuthenticateMe(CookiesManager.GetCookies(CookiesType.AuthKey)))
            {
                context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                return;
            }

            var store = Global.GetStore();
            var path  = string.Format(@"{0}\{1}.zip", SecurityContext.CurrentAccount.ID, FileConstant.DownloadTitle);

            if (!store.IsFile(FileConstant.StorageDomainTmp, path))
            {
                Global.Logger.ErrorFormat("BulkDownload file error. File is not exist on storage. UserId: {0}.", SecurityContext.CurrentAccount.ID);
                context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                return;
            }

            if (store.IsSupportedPreSignedUri)
            {
                var url = store.GetPreSignedUri(FileConstant.StorageDomainTmp, path, TimeSpan.FromHours(1), null).ToString();
                context.Response.Redirect(url);
                return;
            }

            context.Response.Clear();

            try
            {
                bool flushed = false;
                using (var readStream = store.GetReadStream(FileConstant.StorageDomainTmp, path))
                {
                    long offset = 0;
                    long length = readStream.Length;
                    if (readStream.CanSeek)
                    {
                        length = ProcessRangeHeader(context, readStream.Length, ref offset);
                        readStream.Seek(offset, SeekOrigin.Begin);
                    }

                    SendStreamByChunks(context, length, FileConstant.DownloadTitle + ".zip", readStream, ref flushed);
                }

                context.Response.Flush();
                context.Response.SuppressContent = true;
                context.ApplicationInstance.CompleteRequest();
            }
            catch (Exception e)
            {
                Global.Logger.ErrorFormat("BulkDownloadFile failed for user {0} with error: ", SecurityContext.CurrentAccount.ID, e.Message);
                throw new HttpException((int)HttpStatusCode.BadRequest, e.Message);
            }
        }
        [Create(@"", false, false)] //NOTE: this method doesn't requires auth!!!  //NOTE: this method doesn't check payment!!!
        public AuthenticationTokenData AuthenticateMe(string userName, string password, string provider, string accessToken)
        {
            bool viaEmail;
            var  user = GetUser(userName, password, provider, accessToken, out viaEmail);

            if (!StudioSmsNotificationSettings.IsVisibleSettings || !StudioSmsNotificationSettings.Enable)
            {
                try
                {
                    var token = SecurityContext.AuthenticateMe(user.ID);

                    MessageService.Send(Request, viaEmail ? MessageAction.LoginSuccessViaApi : MessageAction.LoginSuccessViaApiSocialAccount);

                    var tenant  = CoreContext.TenantManager.GetCurrentTenant().TenantId;
                    var expires = TenantCookieSettings.GetExpiresTime(tenant);

                    return(new AuthenticationTokenData
                    {
                        Token = token,
                        Expires = new ApiDateTime(expires)
                    });
                }
                catch
                {
                    MessageService.Send(Request, user.DisplayUserName(false), viaEmail ? MessageAction.LoginFailViaApi : MessageAction.LoginFailViaApiSocialAccount);
                    throw new AuthenticationException("User authentication failed");
                }
                finally
                {
                    SecurityContext.Logout();
                }
            }

            if (string.IsNullOrEmpty(user.MobilePhone) || user.MobilePhoneActivationStatus == MobilePhoneActivationStatus.NotActivated)
            {
                return new AuthenticationTokenData
                       {
                           Sms = true
                       }
            }
            ;

            SmsManager.PutAuthCode(user, false);

            return(new AuthenticationTokenData
            {
                Sms = true,
                PhoneNoise = SmsSender.BuildPhoneNoise(user.MobilePhone),
                Expires = new ApiDateTime(DateTime.UtcNow.Add(SmsKeyStorage.StoreInterval))
            });
        }
Example #9
0
        protected static bool AutoAuthByPromo()
        {
            try
            {
                SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.Demo);
                WebItemManager.Instance.ItemGlobalHandlers.Login(SecurityContext.CurrentAccount.ID);
                return(true);
            }
            catch
            {
            }

            return(false);
        }
        public static void ResetUserCookie(Guid?userId = null)
        {
            var settings = TenantCookieSettings.GetForUser(userId ?? SecurityContext.CurrentAccount.ID);

            settings.Index = settings.Index + 1;
            TenantCookieSettings.SetForUser(userId ?? SecurityContext.CurrentAccount.ID, settings);

            if (!userId.HasValue)
            {
                var cookie = SecurityContext.AuthenticateMe(SecurityContext.CurrentAccount.ID);

                SetCookies(CookiesType.AuthKey, cookie);
            }
        }
Example #11
0
        private static void Redirect(HttpContext context)
        {
            if (!SecurityContext.AuthenticateMe(CookiesManager.GetCookies(CookiesType.AuthKey)))
            {
                context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                return;
            }
            var urlRedirect = string.Empty;
            int id;
            var folderId = context.Request[FilesLinkUtility.FolderId];

            if (!string.IsNullOrEmpty(folderId) && int.TryParse(folderId, out id))
            {
                try
                {
                    urlRedirect = PathProvider.GetFolderUrl(id);
                }
                catch (ArgumentNullException e)
                {
                    throw new HttpException((int)HttpStatusCode.BadRequest, e.Message);
                }
            }

            var fileId = context.Request[FilesLinkUtility.FileId];

            if (!string.IsNullOrEmpty(fileId) && int.TryParse(fileId, out id))
            {
                using (var fileDao = Global.DaoFactory.GetFileDao())
                {
                    var file = fileDao.GetFile(id);
                    if (file == null)
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                        return;
                    }

                    urlRedirect = FilesLinkUtility.GetFileWebPreviewUrl(file.Title, file.ID);
                }
            }

            if (string.IsNullOrEmpty(urlRedirect))
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, FilesCommonResource.ErrorMassage_BadRequest);
            }
            context.Response.Redirect(urlRedirect);
        }
Example #12
0
        private static void BulkDownloadFile(HttpContext context)
        {
            if (!SecurityContext.AuthenticateMe(CookiesManager.GetCookies(CookiesType.AuthKey)))
            {
                context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                return;
            }

            var store = Global.GetStore();
            var path  = string.Format(@"{0}\{1}.zip", SecurityContext.CurrentAccount.ID, FileConstant.DownloadTitle);

            if (!store.IsFile(FileConstant.StorageDomainTmp, path))
            {
                Global.Logger.ErrorFormat("BulkDownload file error. File is not exist on storage. UserId: {0}.", SecurityContext.CurrentAccount.ID);
                context.Response.StatusCode = (int)HttpStatusCode.NotFound;
            }
            else
            {
                if (store is S3Storage)
                {
                    var url = store.GetPreSignedUri(FileConstant.StorageDomainTmp, path, TimeSpan.FromHours(1), null).ToString();
                    context.Response.Redirect(url);
                }
                else
                {
                    context.Response.Clear();
                    context.Response.ContentType = "application/zip";
                    context.Response.AddHeader("Content-Disposition", ContentDispositionUtil.GetHeaderValue(FileConstant.DownloadTitle + ".zip"));

                    using (var readStream = store.IronReadStream(FileConstant.StorageDomainTmp, path, 40))
                    {
                        context.Response.AddHeader("Content-Length", readStream.Length.ToString());
                        readStream.StreamCopyTo(context.Response.OutputStream);
                    }
                    try
                    {
                        context.Response.Flush();
                        context.Response.End();
                    }
                    catch (HttpException)
                    {
                    }
                }
            }
        }
Example #13
0
        protected static bool AuthByCookies(string cookiesKey)
        {
            var result = false;

            if (!string.IsNullOrEmpty(cookiesKey))
            {
                try
                {
                    if (SecurityContext.AuthenticateMe(cookiesKey))
                    {
                        result = true;
                        WebItemManager.Instance.ItemGlobalHandlers.Login(SecurityContext.CurrentAccount.ID);
                    }
                }
                catch (Exception ex)
                {
                    LogManager.GetLogger("ASC.Web").ErrorFormat("AutoAuthByCookies Error {0}", ex);
                }
            }

            return(result);
        }
Example #14
0
        public static void AuthenticateMeAndSetCookies(string login, string passwordHash, MessageAction action, bool session = false)
        {
            bool       isSuccess      = true;
            var        cookies        = string.Empty;
            Func <int> funcLoginEvent = () => { return(GetLoginEventId(action)); };

            try
            {
                cookies = SecurityContext.AuthenticateMe(login, passwordHash, funcLoginEvent);
            }
            catch (Exception)
            {
                isSuccess = false;
                throw;
            }
            finally
            {
                if (isSuccess)
                {
                    SetCookies(CookiesType.AuthKey, cookies, session);
                    DbLoginEventsManager.ResetCache();
                }
            }
        }
        private static void CheckConvertFilesStatus(Object obj)
        {
            lock (LockerTimer)
            {
                _timer.Change(Timeout.Infinite, Timeout.Infinite);
            }
            try
            {
                List <File> filesIsConverting;

                lock (LockerStatus)
                {
                    ConversionFileStatus.Where(x => ((!String.IsNullOrEmpty(x.Value.Processed) &&
                                                      DateTime.Now.Subtract(x.Value.StopDateTime) > TimeSpan.FromMinutes(30))))
                    .ToList().ForEach(x => ConversionFileStatus.Remove(x));

                    filesIsConverting = ConversionFileStatus.Where(x => String.IsNullOrEmpty(x.Value.Processed)).Select(x => x.Key).ToList();
                }

                if (filesIsConverting.Count == 0)
                {
                    lock (LockerTimer)
                    {
                        _timer.Dispose();
                        _timer = null;
                    }
                    return;
                }

                foreach (var file in filesIsConverting)
                {
                    var    fileUri = file.ID.ToString();
                    string convetedFileUrl;
                    int    operationResultProgress;
                    object folderId;
                    var    currentFolder = false;

                    try
                    {
                        int      tenantId;
                        IAccount account;

                        lock (LockerStatus)
                        {
                            var operationResult = ConversionFileStatus[file];
                            if (operationResult == null)
                            {
                                continue;
                            }
                            tenantId = operationResult.TenantId;
                            account  = operationResult.Account;
                        }

                        CoreContext.TenantManager.SetCurrentTenant(tenantId);
                        SecurityContext.AuthenticateMe(account);

                        var user    = CoreContext.UserManager.GetUsers(account.ID);
                        var culture = string.IsNullOrEmpty(user.CultureName)
                                          ? CoreContext.TenantManager.GetCurrentTenant().GetCulture()
                                          : CultureInfo.GetCultureInfo(user.CultureName);
                        Thread.CurrentThread.CurrentCulture   = culture;
                        Thread.CurrentThread.CurrentUICulture = culture;

                        var fileSecurity = Global.GetFilesSecurity();
                        if (!fileSecurity.CanRead(file) &&
                            file.RootFolderType != FolderType.BUNCH)    //No rights in CRM after upload before attach
                        {
                            throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFile);
                        }
                        if (file.ContentLength > SetupInfo.AvailableFileSize)
                        {
                            throw new Exception(string.Format(FilesCommonResource.ErrorMassage_FileSizeConvert, FileSizeComment.FilesSizeToString(SetupInfo.AvailableFileSize)));
                        }

                        folderId = Global.FolderMy;
                        using (var folderDao = Global.DaoFactory.GetFolderDao())
                        {
                            var parent = folderDao.GetFolder(file.FolderID);
                            if (parent != null &&
                                fileSecurity.CanCreate(parent))
                            {
                                folderId      = parent.ID;
                                currentFolder = true;
                            }
                        }
                        if (Equals(folderId, 0))
                        {
                            throw new SecurityException(FilesCommonResource.ErrorMassage_FolderNotFound);
                        }

                        fileUri = PathProvider.GetFileStreamUrl(file);

                        var toExtension   = FileUtility.GetInternalExtension(file.Title);
                        var fileExtension = file.ConvertedType ?? FileUtility.GetFileExtension(file.Title);
                        var docKey        = DocumentServiceHelper.GetDocKey(file.ID, file.Version, file.ModifiedOn);

                        operationResultProgress = DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, docKey, true, out convetedFileUrl);
                    }
                    catch (Exception exception)
                    {
                        lock (LockerStatus)
                        {
                            var operationResult = ConversionFileStatus[file];
                            if (operationResult != null)
                            {
                                if (operationResult.Delete)
                                {
                                    ConversionFileStatus.Remove(file);
                                }
                                else
                                {
                                    operationResult.Result       = FileJsonSerializer(file);
                                    operationResult.Processed    = "1";
                                    operationResult.StopDateTime = DateTime.Now;
                                    operationResult.Error        = exception.Message;
                                }
                            }
                        }

                        var strExc = exception.Message + " in file " + fileUri;
                        Global.Logger.Error(strExc, exception);

                        continue;
                    }

                    if (operationResultProgress < 100)
                    {
                        lock (LockerStatus)
                        {
                            var operationResult = ConversionFileStatus[file];
                            if (operationResult != null)
                            {
                                operationResult.Progress = operationResultProgress;
                            }
                        }
                        continue;
                    }

                    using (var fileDao = Global.DaoFactory.GetFileDao())
                        using (var folderDao = Global.DaoFactory.GetFolderDao())
                        {
                            var newFileTitle = FileUtility.ReplaceFileExtension(file.Title, FileUtility.GetInternalExtension(file.Title));

                            File newFile = null;
                            if (FilesSettings.UpdateIfExist && (!currentFolder || !file.ProviderEntry))
                            {
                                newFile = fileDao.GetFile(folderId, newFileTitle);
                                if (newFile != null &&
                                    Global.GetFilesSecurity().CanEdit(newFile) &&
                                    !EntryManager.FileLockedForMe(newFile.ID) &&
                                    !FileTracker.IsEditing(newFile.ID))
                                {
                                    newFile.Version++;
                                }
                                else
                                {
                                    newFile = null;
                                }
                            }

                            if (newFile == null)
                            {
                                newFile = new File {
                                    FolderID = folderId
                                }
                            }
                            ;

                            newFile.Title         = newFileTitle;
                            newFile.ConvertedType = FileUtility.GetInternalExtension(file.Title);

                            var operationResultError = string.Empty;
                            try
                            {
                                var req = (HttpWebRequest)WebRequest.Create(convetedFileUrl);

                                using (var convertedFileStream = new ResponseStream(req.GetResponse()))
                                {
                                    newFile.ContentLength = convertedFileStream.Length;
                                    newFile.Comment       = string.Empty;
                                    newFile = fileDao.SaveFile(newFile, convertedFileStream);
                                }

                                FileMarker.MarkAsNew(newFile);

                                using (var tagDao = Global.DaoFactory.GetTagDao())
                                {
                                    var tags = tagDao.GetTags(file.ID, FileEntryType.File, TagType.System).ToList();
                                    if (tags.Any())
                                    {
                                        tags.ForEach(r => r.EntryId = newFile.ID);
                                        tagDao.SaveTags(tags.ToArray());
                                    }
                                }

                                operationResultProgress = 100;
                            }
                            catch (WebException e)
                            {
                                using (var response = e.Response)
                                {
                                    var httpResponse = (HttpWebResponse)response;
                                    var errorString  = String.Format("Error code: {0}", httpResponse.StatusCode);

                                    if (httpResponse.StatusCode != HttpStatusCode.NotFound)
                                    {
                                        using (var data = response.GetResponseStream())
                                        {
                                            var text = new StreamReader(data).ReadToEnd();
                                            errorString += String.Format(" Error message: {0}", text);
                                        }
                                    }

                                    operationResultError = errorString;

                                    Global.Logger.Error(errorString + "  ConvertUrl : " + convetedFileUrl + "    fromUrl : " + fileUri, e);
                                    throw new Exception(errorString);
                                }
                            }
                            finally
                            {
                                var fileSecurity   = Global.GetFilesSecurity();
                                var removeOriginal = !FilesSettings.StoreOriginalFiles &&
                                                     fileSecurity.CanDelete(file) &&
                                                     currentFolder &&
                                                     !EntryManager.FileLockedForMe(file.ID);

                                var folderTitle = folderDao.GetFolder(newFile.FolderID).Title;

                                lock (LockerStatus)
                                {
                                    var operationResult = ConversionFileStatus[file];

                                    if (operationResult.Delete)
                                    {
                                        ConversionFileStatus.Remove(file);
                                    }
                                    else
                                    {
                                        operationResult.Result       = FileJsonSerializer(newFile, removeOriginal, folderTitle);
                                        operationResult.Processed    = "1";
                                        operationResult.StopDateTime = DateTime.Now;
                                        operationResult.Progress     = operationResultProgress;
                                        if (!string.IsNullOrEmpty(operationResultError))
                                        {
                                            operationResult.Error = operationResultError;
                                        }
                                    }
                                }

                                if (removeOriginal)
                                {
                                    FileMarker.RemoveMarkAsNewForAll(file);
                                    fileDao.DeleteFile(file.ID);
                                }
                            }
                        }
                }

                lock (LockerTimer)
                {
                    _timer.Change(0, TimerConvertPeriod);
                }
            }
            catch (Exception exception)
            {
                Global.Logger.Error(exception.Message, exception);
                lock (LockerTimer)
                {
                    _timer.Dispose();
                    _timer = null;
                }
            }
        }
Example #16
0
        public void RunJob(DistributedTask _, CancellationToken cancellationToken)
        {
            try
            {
                CancellationToken = cancellationToken;

                CoreContext.TenantManager.SetCurrentTenant(CurrentTenant);

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

                Thread.CurrentThread.CurrentCulture   = CultureInfo.GetCultureInfo(_culture);
                Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(_culture);

                Logger = LogManager.GetLogger(typeof(LDAPOperation));

                if (LDAPSettings == null)
                {
                    Error = Resource.LdapSettingsErrorCantGetLdapSettings;
                    Logger.Error("Can't save default LDAP settings.");
                    return;
                }

                if (OperationType == LDAPOperationType.Save)
                {
                    SetProgress(1, Resource.LdapSettingsStatusCheckingLdapSettings);

                    PrepareSettings(LDAPSettings);

                    if (!string.IsNullOrEmpty(Error))
                    {
                        return;
                    }

                    Importer = new LDAPUserImporter(LDAPSettings);

                    SetProgress(5, Resource.LdapSettingsStatusLoadingBaseInfo);

                    var acceptCertificate = TaskInfo.GetProperty <bool>(CERT_ALLOW);

                    var result = _ldapSettingsChecker.CheckSettings(Importer, acceptCertificate);

                    if (result == LdapSettingsChecker.CERTIFICATE_REQUEST)
                    {
                        TaskInfo.SetProperty(FINISHED, true);

                        TaskInfo.SetProperty(CERT_REQUEST, ((NovellLdapSettingsChecker)_ldapSettingsChecker).CertificateConfirmRequest);

                        SetProgress(0, Resource.LdapSettingsStatusCertificateVerification);

                        return;
                    }

                    var error = GetError(result);
                    if (!string.IsNullOrEmpty(error))
                    {
                        Error = error;
                        return;
                    }

                    SetProgress(10, Resource.LdapSettingsStatusSavingSettings);

                    LDAPSettings.IsDefault = LDAPSettings.Equals(LDAPSettings.GetDefault());

                    if (!SettingsManager.Instance.SaveSettings(LDAPSettings, CurrentTenant.TenantId))
                    {
                        Logger.Error("Can't save LDAP settings.");
                        Error = Resource.LdapSettingsErrorCantSaveLdapSettings;
                        return;
                    }
                }
                else if (OperationType == LDAPOperationType.Sync)
                {
                    Importer = new LDAPUserImporter(LDAPSettings);
                }

                Do();
            }
            catch (AuthorizingException authError)
            {
                Error = Resource.ErrorAccessDenied;
                Logger.Error(Error, new SecurityException(Error, authError));
            }
            catch (AggregateException ae)
            {
                ae.Flatten().Handle(e => e is TaskCanceledException || e is OperationCanceledException);
            }
            catch (TenantQuotaException e)
            {
                Error = Resource.LdapSettingsTenantQuotaSettled;
                Logger.ErrorFormat("TenantQuotaException. {0}", e);
            }
            catch (FormatException e)
            {
                Error = Resource.LdapSettingsErrorCantCreateUsers;
                Logger.ErrorFormat("FormatException error. {0}", e);
            }
            catch (Exception e)
            {
                Error = Resource.LdapSettingsInternalServerError;
                Logger.ErrorFormat("Internal server error. {0}", e);
            }
            finally
            {
                try
                {
                    TaskInfo.SetProperty(FINISHED, true);
                    PublishTaskInfo();
                }
                catch { /* ignore */ }
            }
        }
Example #17
0
        internal static void RequestCode(HttpContext context)
        {
            var state = context.Request["state"];

            Global.Logger.Debug("GoogleDriveApp: state - " + state);
            if (string.IsNullOrEmpty(state))
            {
                Global.Logger.Info("GoogleDriveApp: empty state");
                throw new Exception("Empty state");
            }

            var token = GetToken(context.Request["code"]);

            if (token == null)
            {
                Global.Logger.Info("GoogleDriveApp: token is null");
                throw new SecurityException("Access token is null");
            }

            var stateJson = JObject.Parse(state);

            if (SecurityContext.IsAuthenticated)
            {
                Global.Logger.Debug("GoogleDriveApp: is authenticated");

                if (!CurrentUser(stateJson.Value <string>("userId")))
                {
                    Global.Logger.Debug("GoogleDriveApp: logout");
                    CookiesManager.ClearCookies(CookiesType.AuthKey);
                    SecurityContext.Logout();
                }
            }

            if (!SecurityContext.IsAuthenticated)
            {
                var userInfo = GetUserInfo(token);

                if (userInfo == null)
                {
                    Global.Logger.Error("GoogleDriveApp: UserInfo is null");
                    throw new Exception("Profile is null");
                }

                var cookiesKey = SecurityContext.AuthenticateMe(userInfo.ID);
                CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey);
            }

            Token.SaveToken(token);

            var action = stateJson.Value <string>("action");

            switch (action)
            {
            case "create":
                var folderId = stateJson.Value <string>("folderId");

                context.Response.Redirect(App.Location + "?" + FilesLinkUtility.FolderId + "=" + folderId, true);
                return;

            case "open":
                var idsArray = stateJson.Value <JArray>("ids") ?? stateJson.Value <JArray>("exportIds");
                if (idsArray == null)
                {
                    Global.Logger.Error("GoogleDriveApp: ids is empty");
                    throw new Exception("File id is null");
                }
                var fileId = idsArray.ToObject <List <string> >().FirstOrDefault();

                var driveFile = GetDriveFile(fileId, token);
                if (driveFile == null)
                {
                    Global.Logger.Error("GoogleDriveApp: file is null");
                    throw new Exception("File not found");
                }

                var jsonFile = JObject.Parse(driveFile);
                var ext      = GetCorrectExt(jsonFile);
                var mimeType = (jsonFile.Value <string>("mimeType") ?? "").ToLower();
                if (FileUtility.ExtsMustConvert.Contains(ext) ||
                    GoogleMimeTypes.Keys.Contains(mimeType))
                {
                    Global.Logger.Debug("GoogleDriveApp: file must be converted");
                    if (FilesSettings.ConvertNotify)
                    {
                        context.Response.Redirect(App.Location + "?" + FilesLinkUtility.FileId + "=" + fileId, true);
                        return;
                    }

                    fileId = CreateConvertedFile(driveFile, token);
                }

                context.Response.Redirect(FilesLinkUtility.GetFileWebEditorUrl(fileId) + "&" + FilesLinkUtility.Action + "=app", true);
                return;
            }
            Global.Logger.Error("GoogleDriveApp: Action not identified");
            throw new Exception("Action not identified");
        }
Example #18
0
        public void RunJob(DistributedTask _, CancellationToken cancellationToken)
        {
            try
            {
                CancellationToken = cancellationToken;

                SetProgress(5, "Setup tenant");

                CoreContext.TenantManager.SetCurrentTenant(CurrentTenant);

                SetProgress(10, "Setup user");

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

                SetProgress(15, "Find user data");

                var currentUser = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);

                SetProgress(20, "Create mime message");

                var toAddress = new MailboxAddress(currentUser.UserName, currentUser.Email);

                var fromAddress = new MailboxAddress(SmtpSettings.SenderDisplayName, SmtpSettings.SenderAddress);

                var mimeMessage = new MimeMessage
                {
                    Subject = messageSubject
                };

                mimeMessage.From.Add(fromAddress);

                mimeMessage.To.Add(toAddress);

                var bodyBuilder = new BodyBuilder
                {
                    TextBody = messageBody
                };

                mimeMessage.Body = bodyBuilder.ToMessageBody();

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

                using (var client = GetSmtpClient())
                {
                    SetProgress(40, "Connect to host");

                    client.Connect(SmtpSettings.Host, SmtpSettings.Port.GetValueOrDefault(25),
                                   SmtpSettings.EnableSSL ? SecureSocketOptions.Auto : SecureSocketOptions.None, cancellationToken);

                    if (SmtpSettings.EnableAuth)
                    {
                        SetProgress(60, "Authenticate");

                        client.Authenticate(SmtpSettings.CredentialsUserName,
                                            SmtpSettings.CredentialsUserPassword, cancellationToken);
                    }

                    SetProgress(80, "Send test message");

                    client.Send(FormatOptions.Default, mimeMessage, cancellationToken);
                }
            }
            catch (AuthorizingException authError)
            {
                Error = Resources.Resource.ErrorAccessDenied; // "No permissions to perform this action";
                Logger.Error(Error, new SecurityException(Error, authError));
            }
            catch (AggregateException ae)
            {
                ae.Flatten().Handle(e => e is TaskCanceledException || e is OperationCanceledException);
            }
            catch (SocketException ex)
            {
                Error = ex.Message; //TODO: Add translates of ordinary cases
                Logger.Error(ex.ToString());
            }
            catch (AuthenticationException ex)
            {
                Error = ex.Message; //TODO: Add translates of ordinary cases
                Logger.Error(ex.ToString());
            }
            catch (Exception ex)
            {
                Error = ex.Message; //TODO: Add translates of ordinary cases
                Logger.Error(ex.ToString());
            }
            finally
            {
                try
                {
                    TaskInfo.SetProperty(FINISHED, true);
                    PublishTaskInfo();

                    SecurityContext.Logout();
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("LdapOperation finalization problem. {0}", ex);
                }
            }
        }
        private static void CheckConvertFilesStatus(object _)
        {
            if (Monitor.TryEnter(singleThread))
            {
                try
                {
                    List <File> filesIsConverting;
                    lock (locker)
                    {
                        timer.Change(Timeout.Infinite, Timeout.Infinite);

                        conversionQueue.Where(x => !string.IsNullOrEmpty(x.Value.Processed) &&
                                              (x.Value.Progress == 100 && DateTime.UtcNow - x.Value.StopDateTime > TimeSpan.FromMinutes(1) ||
                                               DateTime.UtcNow - x.Value.StopDateTime > TimeSpan.FromMinutes(10)))
                        .ToList()
                        .ForEach(x =>
                        {
                            conversionQueue.Remove(x);
                            cache.Remove(GetKey(x.Key));
                        });

                        Global.Logger.DebugFormat("Run CheckConvertFilesStatus: count {0}", conversionQueue.Count);

                        if (conversionQueue.Count == 0)
                        {
                            return;
                        }

                        filesIsConverting = conversionQueue
                                            .Where(x => String.IsNullOrEmpty(x.Value.Processed))
                                            .Select(x => x.Key)
                                            .ToList();
                    }

                    var fileSecurity = Global.GetFilesSecurity();
                    foreach (var file in filesIsConverting)
                    {
                        var    fileUri = file.ID.ToString();
                        string convertedFileUrl;
                        int    operationResultProgress;

                        try
                        {
                            int      tenantId;
                            IAccount account;

                            lock (locker)
                            {
                                if (!conversionQueue.Keys.Contains(file))
                                {
                                    continue;
                                }

                                var operationResult = conversionQueue[file];
                                if (!string.IsNullOrEmpty(operationResult.Processed))
                                {
                                    continue;
                                }

                                operationResult.Processed = "1";
                                tenantId = operationResult.TenantId;
                                account  = operationResult.Account;

                                if (HttpContext.Current == null && !WorkContext.IsMono)
                                {
                                    HttpContext.Current = new HttpContext(
                                        new HttpRequest("hack", operationResult.Url, string.Empty),
                                        new HttpResponse(new StringWriter()));
                                }

                                cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(10));
                            }

                            CoreContext.TenantManager.SetCurrentTenant(tenantId);
                            SecurityContext.AuthenticateMe(account);

                            var user    = CoreContext.UserManager.GetUsers(account.ID);
                            var culture = string.IsNullOrEmpty(user.CultureName) ? CoreContext.TenantManager.GetCurrentTenant().GetCulture() : CultureInfo.GetCultureInfo(user.CultureName);
                            Thread.CurrentThread.CurrentCulture   = culture;
                            Thread.CurrentThread.CurrentUICulture = culture;

                            if (!fileSecurity.CanRead(file) && file.RootFolderType != FolderType.BUNCH)
                            {
                                //No rights in CRM after upload before attach
                                throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFile);
                            }
                            if (file.ContentLength > SetupInfo.AvailableFileSize)
                            {
                                throw new Exception(string.Format(FilesCommonResource.ErrorMassage_FileSizeConvert, FileSizeComment.FilesSizeToString(SetupInfo.AvailableFileSize)));
                            }

                            fileUri = PathProvider.GetFileStreamUrl(file);

                            var toExtension   = FileUtility.GetInternalExtension(file.Title);
                            var fileExtension = file.ConvertedExtension;
                            var docKey        = DocumentServiceHelper.GetDocKey(file);

                            fileUri = DocumentServiceConnector.ReplaceCommunityAdress(fileUri);
                            operationResultProgress = DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, docKey, true, out convertedFileUrl);
                        }
                        catch (Exception exception)
                        {
                            Global.Logger.Error(string.Format("Error convert {0} with url {1}", file.ID, fileUri), exception);
                            lock (locker)
                            {
                                if (conversionQueue.Keys.Contains(file))
                                {
                                    var operationResult = conversionQueue[file];
                                    if (operationResult.Delete)
                                    {
                                        conversionQueue.Remove(file);
                                        cache.Remove(GetKey(file));
                                    }
                                    else
                                    {
                                        operationResult.Progress     = 100;
                                        operationResult.StopDateTime = DateTime.UtcNow;
                                        operationResult.Error        = exception.Message;
                                        cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(10));
                                    }
                                }
                            }
                            continue;
                        }

                        operationResultProgress = Math.Min(operationResultProgress, 100);
                        if (operationResultProgress < 100)
                        {
                            lock (locker)
                            {
                                if (conversionQueue.Keys.Contains(file))
                                {
                                    var operationResult = conversionQueue[file];

                                    if (DateTime.Now - operationResult.StartDateTime > TimeSpan.FromMinutes(10))
                                    {
                                        operationResult.StopDateTime = DateTime.UtcNow;
                                        operationResult.Error        = FilesCommonResource.ErrorMassage_ConvertTimeout;
                                        Global.Logger.ErrorFormat("CheckConvertFilesStatus timeout: {0} ({1})", file.ID, file.ContentLengthString);
                                    }
                                    else
                                    {
                                        operationResult.Processed = "";
                                    }
                                    operationResult.Progress = operationResultProgress;
                                    cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(10));
                                }
                            }

                            Global.Logger.Debug("CheckConvertFilesStatus iteration continue");
                            continue;
                        }

                        File newFile = null;
                        var  operationResultError = string.Empty;

                        try
                        {
                            newFile = SaveConvertedFile(file, convertedFileUrl);
                        }
                        catch (Exception e)
                        {
                            operationResultError = e.Message;

                            Global.Logger.ErrorFormat("{0} ConvertUrl: {1} fromUrl: {2}: {3}", operationResultError, convertedFileUrl, fileUri, e);
                            continue;
                        }
                        finally
                        {
                            lock (locker)
                            {
                                if (conversionQueue.Keys.Contains(file))
                                {
                                    var operationResult = conversionQueue[file];
                                    if (operationResult.Delete)
                                    {
                                        conversionQueue.Remove(file);
                                        cache.Remove(GetKey(file));
                                    }
                                    else
                                    {
                                        if (newFile != null)
                                        {
                                            using (var folderDao = Global.DaoFactory.GetFolderDao())
                                            {
                                                var folder      = folderDao.GetFolder(newFile.FolderID);
                                                var folderTitle = fileSecurity.CanRead(folder) ? folder.Title : null;
                                                operationResult.Result = FileJsonSerializer(newFile, folderTitle);
                                            }
                                        }

                                        operationResult.Progress     = 100;
                                        operationResult.StopDateTime = DateTime.UtcNow;
                                        operationResult.Processed    = "1";
                                        if (!string.IsNullOrEmpty(operationResultError))
                                        {
                                            operationResult.Error = operationResultError;
                                        }
                                        cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(10));
                                    }
                                }
                            }
                        }

                        Global.Logger.Debug("CheckConvertFilesStatus iteration end");
                    }

                    lock (locker)
                    {
                        timer.Change(TIMER_PERIOD, TIMER_PERIOD);
                    }
                }
                catch (Exception exception)
                {
                    Global.Logger.Error(exception.Message, exception);
                    lock (locker)
                    {
                        timer.Change(Timeout.Infinite, Timeout.Infinite);
                    }
                }
                finally
                {
                    Monitor.Exit(singleThread);
                }
            }
        }
Example #20
0
        public void RunJob(DistributedTask _, CancellationToken cancellationToken)
        {
            try
            {
                CancellationToken = cancellationToken;

                CoreContext.TenantManager.SetCurrentTenant(CurrentTenant);

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

                Thread.CurrentThread.CurrentCulture   = CultureInfo.GetCultureInfo(_culture);
                Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(_culture);

                Logger = LogManager.GetLogger("ASC");

                if (LDAPSettings == null)
                {
                    Error = Resource.LdapSettingsErrorCantGetLdapSettings;
                    Logger.Error("Can't save default LDAP settings.");
                    return;
                }

                switch (OperationType)
                {
                case LdapOperationType.Save:
                case LdapOperationType.SaveTest:

                    Logger.InfoFormat("Start '{0}' operation",
                                      Enum.GetName(typeof(LdapOperationType), OperationType));

                    SetProgress(1, Resource.LdapSettingsStatusCheckingLdapSettings);

                    Logger.Debug("PrepareSettings()");

                    PrepareSettings(LDAPSettings);

                    if (!string.IsNullOrEmpty(Error))
                    {
                        Logger.DebugFormat("PrepareSettings() Error: {0}", Error);
                        return;
                    }

                    Importer = new NovellLdapUserImporter(LDAPSettings, Resource);

                    if (LDAPSettings.EnableLdapAuthentication)
                    {
                        var ldapSettingsChecker = new NovellLdapSettingsChecker(Importer);

                        SetProgress(5, Resource.LdapSettingsStatusLoadingBaseInfo);

                        var result = ldapSettingsChecker.CheckSettings();

                        if (result != LdapSettingsStatus.Ok)
                        {
                            if (result == LdapSettingsStatus.CertificateRequest)
                            {
                                TaskInfo.SetProperty(CERT_REQUEST,
                                                     ldapSettingsChecker.CertificateConfirmRequest);
                            }

                            Error = GetError(result);

                            Logger.DebugFormat("ldapSettingsChecker.CheckSettings() Error: {0}", Error);

                            return;
                        }
                    }

                    break;

                case LdapOperationType.Sync:
                case LdapOperationType.SyncTest:
                    Logger.InfoFormat("Start '{0}' operation",
                                      Enum.GetName(typeof(LdapOperationType), OperationType));

                    Importer = new NovellLdapUserImporter(LDAPSettings, Resource);
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }

                Do();
            }
            catch (AuthorizingException authError)
            {
                Error = Resource.ErrorAccessDenied;
                Logger.Error(Error, new SecurityException(Error, authError));
            }
            catch (AggregateException ae)
            {
                ae.Flatten().Handle(e => e is TaskCanceledException || e is OperationCanceledException);
            }
            catch (TenantQuotaException e)
            {
                Error = Resource.LdapSettingsTenantQuotaSettled;
                Logger.ErrorFormat("TenantQuotaException. {0}", e);
            }
            catch (FormatException e)
            {
                Error = Resource.LdapSettingsErrorCantCreateUsers;
                Logger.ErrorFormat("FormatException error. {0}", e);
            }
            catch (Exception e)
            {
                Error = Resource.LdapSettingsInternalServerError;
                Logger.ErrorFormat("Internal server error. {0}", e);
            }
            finally
            {
                try
                {
                    TaskInfo.SetProperty(FINISHED, true);
                    PublishTaskInfo();
                    Dispose();
                    SecurityContext.Logout();
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("LdapOperation finalization problem. {0}", ex);
                }
            }
        }
Example #21
0
        private static UserInfo GetUserInfo(Token token, out bool isNew)
        {
            isNew = false;
            if (token == null)
            {
                Global.Logger.Error("BoxApp: token is null");
                throw new SecurityException("Access token is null");
            }

            var resultResponse = string.Empty;

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

            var boxUserInfo = JObject.Parse(resultResponse);

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

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

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

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

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

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

                isNew = true;

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

            return(userInfo);
        }
Example #22
0
        private static UserInfo GetUserInfo(Token token, out bool isNew)
        {
            isNew = false;
            if (token == null)
            {
                Global.Logger.Error("GoogleDriveApp: token is null");
                throw new SecurityException("Access token is null");
            }

            var resultResponse = RequestHelper.PerformRequest(GoogleUrlUserInfo.Replace("{access_token}", token.AccessToken));

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

            var googleUserInfo = JObject.Parse(resultResponse);

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

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

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

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

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

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

                var pwd = UserManagerWrapper.GeneratePassword();

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

                isNew = true;

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

            return(userInfo);
        }
Example #23
0
        private static UserInfo GetUserInfo(Token token, out bool isNew)
        {
            isNew = false;
            if (token == null)
            {
                Global.Logger.Error("GoogleDriveApp: token is null");
                throw new SecurityException("Access token is null");
            }

            LoginProfile loginProfile = null;

            try
            {
                loginProfile = new GoogleLoginProvider().GetLoginProfile(token.ToString());
            }
            catch (Exception ex)
            {
                Global.Logger.Error("GoogleDriveApp: userinfo request", ex);
            }

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

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

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

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

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

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

                isNew = true;

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

            return(userInfo);
        }
Example #24
0
        public object SaveData(string email, string pwd, string lng, string promocode, string licenseKey)
        {
            try
            {
                var tenant   = CoreContext.TenantManager.GetCurrentTenant();
                var settings = SettingsManager.Instance.LoadSettings <WizardSettings>(tenant.TenantId);
                if (settings.Completed)
                {
                    throw new Exception("Wizard passed.");
                }

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

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

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

                UserManagerWrapper.SetUserPassword(currentUser.ID, pwd);

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

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

                if (Enterprise)
                {
                    if (string.IsNullOrEmpty(licenseKey))
                    {
                        throw new ArgumentNullException("licenseKey", UserControlsCommonResource.LicenseKeyNotFound);
                    }

                    TariffSettings.LicenseAccept = true;

                    var licenseKeys = licenseKey.Split('|');

                    MessageService.Send(HttpContext.Current.Request, MessageAction.LicenseKeyUploaded);

                    LicenseClient.SetLicenseKeys(licenseKeys[0], licenseKeys.Length > 1 ? licenseKeys[1] : null);
                }

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

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

                return(new { Status = 1, Message = Resource.EmailAndPasswordSaved });
            }
            catch (BillingNotConfiguredException)
            {
                return(new { Status = 0, Message = UserControlsCommonResource.LicenseKeyNotCorrect });
            }
            catch (BillingNotFoundException)
            {
                return(new { Status = 0, Message = UserControlsCommonResource.LicenseKeyNotCorrect });
            }
            catch (BillingException)
            {
                return(new { Status = 0, Message = UserControlsCommonResource.LicenseException });
            }
            catch (Exception ex)
            {
                return(new { Status = 0, Message = ex.Message });
            }
        }
Example #25
0
        private bool AuthProcess(LoginProfile thirdPartyProfile, bool withAccountLink)
        {
            var authMethod   = AuthMethod.Login;
            var tfaLoginUrl  = string.Empty;
            var loginCounter = 0;

            try
            {
                if (thirdPartyProfile != null)
                {
                    if (string.IsNullOrEmpty(thirdPartyProfile.AuthorizationError))
                    {
                        HashId = thirdPartyProfile.HashId;
                        Login  = thirdPartyProfile.EMail;
                    }
                    else
                    {
                        // ignore cancellation
                        if (thirdPartyProfile.AuthorizationError != "Canceled at provider")
                        {
                            ErrorMessage = thirdPartyProfile.AuthorizationError;
                        }
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(Request["__EVENTARGUMENT"]) && Request["__EVENTTARGET"] == "signInLogin" && withAccountLink)
                    {
                        HashId = ASC.Common.Utils.Signature.Read <string>(Request["__EVENTARGUMENT"]);
                    }
                }

                if (!string.IsNullOrEmpty(Request["login"]))
                {
                    Login = Request["login"].Trim();
                }
                else if (string.IsNullOrEmpty(HashId))
                {
                    IsLoginInvalid = true;
                    throw new InvalidCredentialException("login");
                }

                if (!string.IsNullOrEmpty(Request["pwd"]))
                {
                    Password = Request["pwd"];
                }
                else if (string.IsNullOrEmpty(HashId))
                {
                    IsPasswordInvalid = true;
                    throw new InvalidCredentialException("password");
                }

                if (string.IsNullOrEmpty(HashId))
                {
                    int.TryParse(cache.Get <String>("loginsec/" + Login), out loginCounter);
                    if (++loginCounter > 5)
                    {
                        throw new BruteForceCredentialException();
                    }
                    cache.Insert("loginsec/" + Login, loginCounter.ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));
                }

                var userInfo = GetUser(out authMethod);
                if (!CoreContext.UserManager.UserExists(userInfo.ID) || userInfo.Status != EmployeeStatus.Active)
                {
                    IsLoginInvalid    = true;
                    IsPasswordInvalid = true;
                    throw new InvalidCredentialException();
                }

                var tenant   = CoreContext.TenantManager.GetCurrentTenant();
                var settings = IPRestrictionsSettings.Load();
                if (settings.Enable && userInfo.ID != tenant.OwnerId && !IPSecurity.IPSecurity.Verify(tenant))
                {
                    throw new IPSecurityException();
                }

                if (StudioSmsNotificationSettings.IsVisibleSettings &&
                    StudioSmsNotificationSettings.Enable)
                {
                    tfaLoginUrl = Studio.Confirm.SmsConfirmUrl(userInfo);
                }
                else if (TfaAppAuthSettings.IsVisibleSettings &&
                         TfaAppAuthSettings.Enable)
                {
                    tfaLoginUrl = Studio.Confirm.TfaConfirmUrl(userInfo);
                }
                else
                {
                    var session = EnableSession && string.IsNullOrEmpty(Request["remember"]);

                    var cookiesKey = SecurityContext.AuthenticateMe(userInfo.ID);
                    CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey, session);
                    MessageService.Send(HttpContext.Current.Request,
                                        authMethod == AuthMethod.ThirdParty
                                            ? MessageAction.LoginSuccessViaSocialAccount
                                            : MessageAction.LoginSuccess
                                        );
                }
            }
            catch (InvalidCredentialException ex)
            {
                Auth.ProcessLogout();
                var isBruteForce = (ex is BruteForceCredentialException);

                ErrorMessage = isBruteForce
                                   ? Resource.LoginWithBruteForce
                                   : authMethod == AuthMethod.ThirdParty ? Resource.LoginWithAccountNotFound : Resource.InvalidUsernameOrPassword;

                var loginName = !string.IsNullOrWhiteSpace(Login)
                                    ? Login
                                    : authMethod == AuthMethod.ThirdParty && !string.IsNullOrWhiteSpace(HashId)
                                          ? HashId
                                          : AuditResource.EmailNotSpecified;

                var messageAction = isBruteForce
                                        ? MessageAction.LoginFailBruteForce
                                        : authMethod == AuthMethod.ThirdParty
                                              ? MessageAction.LoginFailSocialAccountNotFound
                                              : MessageAction.LoginFailInvalidCombination;

                MessageService.Send(HttpContext.Current.Request, loginName, messageAction);

                if (authMethod == AuthMethod.ThirdParty && thirdPartyProfile != null)
                {
                    Response.Redirect("~/auth.aspx?m=" + HttpUtility.UrlEncode(_errorMessage), true);
                }
                return(false);
            }
            catch (SecurityException)
            {
                Auth.ProcessLogout();
                ErrorMessage = Resource.ErrorDisabledProfile;
                MessageService.Send(HttpContext.Current.Request, Login, MessageAction.LoginFailDisabledProfile);
                return(false);
            }
            catch (IPSecurityException)
            {
                Auth.ProcessLogout();
                ErrorMessage = Resource.ErrorIpSecurity;
                MessageService.Send(HttpContext.Current.Request, Login, MessageAction.LoginFailIpSecurity);
                return(false);
            }
            catch (Exception ex)
            {
                Auth.ProcessLogout();
                ErrorMessage = ex.Message;
                MessageService.Send(HttpContext.Current.Request, Login, MessageAction.LoginFail);
                return(false);
            }

            if (loginCounter > 0)
            {
                cache.Insert("loginsec/" + Login, (--loginCounter).ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));
            }

            if (!string.IsNullOrEmpty(tfaLoginUrl))
            {
                Response.Redirect(tfaLoginUrl, true);
            }
            return(true);
        }
Example #26
0
        public void RunJob(DistributedTask _, CancellationToken cancellationToken)
        {
            try
            {
                CancellationToken = cancellationToken;

                CoreContext.TenantManager.SetCurrentTenant(CurrentTenant);

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

                Thread.CurrentThread.CurrentCulture   = CultureInfo.GetCultureInfo(_culture);
                Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(_culture);

                Logger = LoggerFactory.GetLogger(LoggerFactory.LoggerType.Log4Net, "MailOperation");

                //TODO: Check any settings
                switch (OperationType)
                {
                case MailOperationType.RecalculateFolders:
                    break;

                case MailOperationType.RemoveMailbox:
                    break;

                default:
                    throw new InvalidOperationException();
                }

                Do();
            }
            catch (AuthorizingException authError)
            {
                Error = "ErrorAccessDenied";
                Logger.Error(Error, new SecurityException(Error, authError));
            }
            catch (AggregateException ae)
            {
                ae.Flatten().Handle(e => e is TaskCanceledException || e is OperationCanceledException);
            }
            catch (TenantQuotaException e)
            {
                Error = "TenantQuotaSettled";
                Logger.Error("TenantQuotaException. {0}", e);
            }
            catch (FormatException e)
            {
                Error = "CantCreateUsers";
                Logger.Error("FormatException error. {0}", e);
            }
            catch (Exception e)
            {
                Error = "InternalServerError";
                Logger.Error("Internal server error. {0}", e);
            }
            finally
            {
                try
                {
                    TaskInfo.SetProperty(FINISHED, true);
                    PublishTaskInfo();
                }
                catch
                {
                    /* ignore */
                }
            }
        }
Example #27
0
        private static void RequestCode(HttpContext context)
        {
            var state = context.Request["state"];

            Global.Logger.Debug("GoogleDriveApp: state - " + state);
            if (string.IsNullOrEmpty(state))
            {
                Global.Logger.Error("GoogleDriveApp: empty state");
                throw new Exception("Empty state");
            }

            var token = GetToken(context.Request["code"]);

            if (token == null)
            {
                Global.Logger.Error("GoogleDriveApp: token is null");
                throw new SecurityException("Access token is null");
            }

            var stateJson = JObject.Parse(state);

            var googleUserId = stateJson.Value <string>("userId");

            if (SecurityContext.IsAuthenticated)
            {
                if (!CurrentUser(googleUserId))
                {
                    Global.Logger.Debug("GoogleDriveApp: logout for " + googleUserId);
                    CookiesManager.ClearCookies(CookiesType.AuthKey);
                    SecurityContext.Logout();
                }
            }

            if (!SecurityContext.IsAuthenticated)
            {
                bool isNew;
                var  userInfo = GetUserInfo(token, out isNew);

                if (userInfo == null)
                {
                    Global.Logger.Error("GoogleDriveApp: UserInfo is null");
                    throw new Exception("Profile is null");
                }

                var cookiesKey = SecurityContext.AuthenticateMe(userInfo.ID);
                CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey);
                MessageService.Send(HttpContext.Current.Request, MessageAction.LoginSuccessViaSocialAccount);

                if (isNew)
                {
                    UserHelpTourHelper.IsNewUser    = true;
                    PersonalSettings.IsNewUser      = true;
                    PersonalSettings.IsNotActivated = true;
                }

                if (!string.IsNullOrEmpty(googleUserId) && !CurrentUser(googleUserId))
                {
                    AddLinker(googleUserId);
                }
            }

            Token.SaveToken(token);

            var action = stateJson.Value <string>("action");

            switch (action)
            {
            case "create":
                var folderId = stateJson.Value <string>("folderId");

                context.Response.Redirect(App.Location + "?" + FilesLinkUtility.FolderId + "=" + HttpUtility.UrlEncode(folderId), true);
                return;

            case "open":
                var idsArray = stateJson.Value <JArray>("ids") ?? stateJson.Value <JArray>("exportIds");
                if (idsArray == null)
                {
                    Global.Logger.Error("GoogleDriveApp: ids is empty");
                    throw new Exception("File id is null");
                }
                var fileId = idsArray.ToObject <List <string> >().FirstOrDefault();

                var driveFile = GetDriveFile(fileId, token);
                if (driveFile == null)
                {
                    Global.Logger.Error("GoogleDriveApp: file is null");
                    throw new Exception("File not found");
                }

                var jsonFile = JObject.Parse(driveFile);
                var ext      = GetCorrectExt(jsonFile);
                if (FileUtility.ExtsMustConvert.Contains(ext) ||
                    GoogleLoginProvider.GoogleDriveExt.Contains(ext))
                {
                    Global.Logger.Debug("GoogleDriveApp: file must be converted");
                    if (FilesSettings.ConvertNotify)
                    {
                        context.Response.Redirect(App.Location + "?" + FilesLinkUtility.FileId + "=" + HttpUtility.UrlEncode(fileId), true);
                        return;
                    }

                    fileId = CreateConvertedFile(driveFile, token);
                }

                context.Response.Redirect(FilesLinkUtility.GetFileWebEditorUrl(ThirdPartySelector.BuildAppFileId(AppAttr, fileId)), true);
                return;
            }
            Global.Logger.Error("GoogleDriveApp: Action not identified");
            throw new Exception("Action not identified");
        }
Example #28
0
        private bool AuthProcess(LoginProfile thirdPartyProfile, bool withAccountLink)
        {
            var authMethod   = AuthMethod.Login;
            var tfaLoginUrl  = string.Empty;
            var loginCounter = 0;

            ShowRecaptcha = false;
            try
            {
                if (thirdPartyProfile != null)
                {
                    if (string.IsNullOrEmpty(thirdPartyProfile.AuthorizationError))
                    {
                        HashId = thirdPartyProfile.HashId;
                        Login  = thirdPartyProfile.EMail;
                    }
                    else
                    {
                        // ignore cancellation
                        if (thirdPartyProfile.AuthorizationError != "Canceled at provider")
                        {
                            ErrorMessage = thirdPartyProfile.AuthorizationError;
                        }
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(Request["__EVENTARGUMENT"]) && Request["__EVENTTARGET"] == "signInLogin" && withAccountLink)
                    {
                        HashId = ASC.Common.Utils.Signature.Read <string>(Request["__EVENTARGUMENT"]);
                    }
                }

                if (!string.IsNullOrEmpty(Request["login"]))
                {
                    Login = Request["login"].Trim();
                }
                else if (string.IsNullOrEmpty(HashId))
                {
                    IsLoginInvalid = true;
                    throw new InvalidCredentialException("login");
                }

                if (!string.IsNullOrEmpty(Request["passwordHash"]))
                {
                    PasswordHash = Request["passwordHash"];
                }
                else if (string.IsNullOrEmpty(HashId))
                {
                    IsPasswordInvalid = true;
                    throw new InvalidCredentialException("password");
                }

                if (string.IsNullOrEmpty(HashId) && !SetupInfo.IsSecretEmail(Login))
                {
                    int.TryParse(cache.Get <String>("loginsec/" + Login), out loginCounter);

                    loginCounter++;

                    if (!RecaptchaEnable)
                    {
                        if (loginCounter > SetupInfo.LoginThreshold)
                        {
                            throw new BruteForceCredentialException();
                        }
                    }
                    else
                    {
                        if (loginCounter > SetupInfo.LoginThreshold - 1)
                        {
                            ShowRecaptcha = true;
                        }
                        if (loginCounter > SetupInfo.LoginThreshold)
                        {
                            var ip = Request.Headers["X-Forwarded-For"] ?? Request.UserHostAddress;

                            var recaptchaResponse = Request["g-recaptcha-response"];
                            if (String.IsNullOrEmpty(recaptchaResponse) ||
                                !ValidateRecaptcha(recaptchaResponse, ip))
                            {
                                throw new RecaptchaException();
                            }
                        }
                    }

                    cache.Insert("loginsec/" + Login, loginCounter.ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));
                }

                var userInfo = GetUser(out authMethod);
                if (!CoreContext.UserManager.UserExists(userInfo.ID) || userInfo.Status != EmployeeStatus.Active)
                {
                    IsLoginInvalid    = true;
                    IsPasswordInvalid = true;
                    throw new InvalidCredentialException();
                }

                var tenant   = CoreContext.TenantManager.GetCurrentTenant();
                var settings = IPRestrictionsSettings.Load();
                if (settings.Enable && userInfo.ID != tenant.OwnerId && !IPSecurity.IPSecurity.Verify(tenant))
                {
                    throw new IPSecurityException();
                }

                if (StudioSmsNotificationSettings.IsVisibleSettings &&
                    StudioSmsNotificationSettings.Enable)
                {
                    tfaLoginUrl = Studio.Confirm.SmsConfirmUrl(userInfo);
                }
                else if (TfaAppAuthSettings.IsVisibleSettings &&
                         TfaAppAuthSettings.Enable)
                {
                    tfaLoginUrl = Studio.Confirm.TfaConfirmUrl(userInfo);
                }
                else
                {
                    var session = EnableSession && string.IsNullOrEmpty(Request["remember"]);

                    var cookiesKey = SecurityContext.AuthenticateMe(userInfo.ID);
                    CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey, session);
                    MessageService.Send(HttpContext.Current.Request,
                                        authMethod == AuthMethod.ThirdParty
                                            ? MessageAction.LoginSuccessViaSocialAccount
                                            : MessageAction.LoginSuccess
                                        );
                }
            }
            catch (InvalidCredentialException ex)
            {
                Auth.ProcessLogout();

                Auth.MessageKey messageKey;
                MessageAction   messageAction;

                if (ex is BruteForceCredentialException)
                {
                    messageKey    = Auth.MessageKey.LoginWithBruteForce;
                    messageAction = MessageAction.LoginFailBruteForce;
                }
                else if (ex is RecaptchaException)
                {
                    messageKey    = Auth.MessageKey.RecaptchaInvalid;
                    messageAction = MessageAction.LoginFailRecaptcha;
                }
                else if (authMethod == AuthMethod.ThirdParty)
                {
                    messageKey    = Auth.MessageKey.LoginWithAccountNotFound;
                    messageAction = MessageAction.LoginFailSocialAccountNotFound;
                }
                else
                {
                    messageKey    = Auth.MessageKey.InvalidUsernameOrPassword;
                    messageAction = MessageAction.LoginFailInvalidCombination;
                }

                var loginName = !string.IsNullOrWhiteSpace(Login)
                                    ? Login
                                    : authMethod == AuthMethod.ThirdParty && !string.IsNullOrWhiteSpace(HashId)
                                          ? HashId
                                          : AuditResource.EmailNotSpecified;

                MessageService.Send(HttpContext.Current.Request, loginName, messageAction);

                if (authMethod == AuthMethod.ThirdParty && thirdPartyProfile != null)
                {
                    Response.Redirect("~/Auth.aspx?am=" + (int)messageKey + (Request.DesktopApp() ? "&desktop=true" : ""), true);
                }
                else
                {
                    ErrorMessage = Auth.GetAuthMessage(messageKey);
                }

                return(false);
            }
            catch (SecurityException)
            {
                Auth.ProcessLogout();
                ErrorMessage = Resource.ErrorDisabledProfile;
                MessageService.Send(HttpContext.Current.Request, Login, MessageAction.LoginFailDisabledProfile);
                return(false);
            }
            catch (IPSecurityException)
            {
                Auth.ProcessLogout();
                ErrorMessage = Resource.ErrorIpSecurity;
                MessageService.Send(HttpContext.Current.Request, Login, MessageAction.LoginFailIpSecurity);
                return(false);
            }
            catch (Exception ex)
            {
                Auth.ProcessLogout();
                ErrorMessage = ex.Message;
                MessageService.Send(HttpContext.Current.Request, Login, MessageAction.LoginFail);
                return(false);
            }

            if (loginCounter > 0)
            {
                cache.Insert("loginsec/" + Login, (--loginCounter).ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));
            }

            if (!string.IsNullOrEmpty(tfaLoginUrl))
            {
                if (Request.DesktopApp())
                {
                    tfaLoginUrl += "&desktop=true";
                }

                Response.Redirect(tfaLoginUrl, true);
            }

            return(true);
        }
        public object SaveData(string email, string pwd, string lng, string promocode, string amiid, bool analytics)
        {
            try
            {
                var tenant   = CoreContext.TenantManager.GetCurrentTenant();
                var settings = WizardSettings.Load();
                if (settings.Completed)
                {
                    throw new Exception("Wizard passed.");
                }

                if (IsAmi && IncorrectAmiId(amiid))
                {
                    throw new Exception(Resource.EmailAndPasswordIncorrectAmiId);
                }

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

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

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

                UserManagerWrapper.CheckPasswordPolicy(pwd);
                SecurityContext.SetUserPassword(currentUser.ID, pwd);

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

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

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

                    LicenseReader.RefreshLicense();
                }

                if (TenantExtra.Opensource)
                {
                    settings.Analytics = analytics;
                }
                settings.Completed = true;
                settings.Save();

                TrySetLanguage(tenant, lng);

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

                return(new { Status = 1, Message = Resource.EmailAndPasswordSaved });
            }
            catch (BillingNotFoundException)
            {
                return(new { Status = 0, Message = UserControlsCommonResource.LicenseKeyNotFound });
            }
            catch (BillingNotConfiguredException)
            {
                return(new { Status = 0, Message = UserControlsCommonResource.LicenseKeyNotCorrect });
            }
            catch (BillingException)
            {
                return(new { Status = 0, Message = UserControlsCommonResource.LicenseException });
            }
            catch (Exception ex)
            {
                LogManager.GetLogger("ASC.Web.FirstTime").Error(ex);
                return(new { Status = 0, Message = ex.Message });
            }
        }
Example #30
0
        private static void CheckConvertFilesStatus(object _)
        {
            if (Monitor.TryEnter(singleThread))
            {
                try
                {
                    List <File> filesIsConverting;
                    lock (locker)
                    {
                        timer.Change(Timeout.Infinite, Timeout.Infinite);

                        conversionQueue.Where(x => !string.IsNullOrEmpty(x.Value.Processed) &&
                                              (x.Value.Progress == 100 && DateTime.Now - x.Value.StopDateTime > TimeSpan.FromMinutes(1) ||
                                               DateTime.Now - x.Value.StopDateTime > TimeSpan.FromMinutes(30)))
                        .ToList()
                        .ForEach(x =>
                        {
                            conversionQueue.Remove(x);
                            cache.Remove(GetKey(x.Key));
                        });

                        Global.Logger.DebugFormat("Run CheckConvertFilesStatus: count {0}", conversionQueue.Count);

                        if (conversionQueue.Count == 0)
                        {
                            return;
                        }

                        filesIsConverting = conversionQueue
                                            .Where(x => String.IsNullOrEmpty(x.Value.Processed))
                                            .Select(x => x.Key)
                                            .ToList();
                    }

                    foreach (var file in filesIsConverting)
                    {
                        var    fileUri = file.ID.ToString();
                        string convertedFileUrl;
                        int    operationResultProgress;
                        object folderId;
                        var    currentFolder = false;

                        try
                        {
                            int      tenantId;
                            IAccount account;

                            lock (locker)
                            {
                                if (!conversionQueue.Keys.Contains(file))
                                {
                                    continue;
                                }

                                var operationResult = conversionQueue[file];
                                if (!string.IsNullOrEmpty(operationResult.Processed))
                                {
                                    continue;
                                }

                                operationResult.Processed = "1";
                                tenantId = operationResult.TenantId;
                                account  = operationResult.Account;

                                cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(30));
                            }

                            CoreContext.TenantManager.SetCurrentTenant(tenantId);
                            SecurityContext.AuthenticateMe(account);

                            var user    = CoreContext.UserManager.GetUsers(account.ID);
                            var culture = string.IsNullOrEmpty(user.CultureName) ? CoreContext.TenantManager.GetCurrentTenant().GetCulture() : CultureInfo.GetCultureInfo(user.CultureName);
                            Thread.CurrentThread.CurrentCulture   = culture;
                            Thread.CurrentThread.CurrentUICulture = culture;

                            var fileSecurity = Global.GetFilesSecurity();
                            if (!fileSecurity.CanRead(file) && file.RootFolderType != FolderType.BUNCH)
                            {
                                //No rights in CRM after upload before attach
                                throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFile);
                            }
                            if (file.ContentLength > SetupInfo.AvailableFileSize)
                            {
                                throw new Exception(string.Format(FilesCommonResource.ErrorMassage_FileSizeConvert, FileSizeComment.FilesSizeToString(SetupInfo.AvailableFileSize)));
                            }

                            folderId = Global.FolderMy;
                            using (var folderDao = Global.DaoFactory.GetFolderDao())
                            {
                                var parent = folderDao.GetFolder(file.FolderID);
                                if (parent != null &&
                                    fileSecurity.CanCreate(parent))
                                {
                                    folderId      = parent.ID;
                                    currentFolder = true;
                                }
                            }
                            if (Equals(folderId, 0))
                            {
                                throw new SecurityException(FilesCommonResource.ErrorMassage_FolderNotFound);
                            }

                            fileUri = PathProvider.GetFileStreamUrl(file);

                            var toExtension   = FileUtility.GetInternalExtension(file.Title);
                            var fileExtension = file.ConvertedExtension;
                            var docKey        = DocumentServiceHelper.GetDocKey(file.ID, file.Version, file.ModifiedOn);

                            operationResultProgress = DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, docKey, true, out convertedFileUrl);
                            operationResultProgress = Math.Min(operationResultProgress, 100);
                        }
                        catch (Exception exception)
                        {
                            Global.Logger.ErrorFormat("Error convert {0} with url {1}: {2}", file.ID, fileUri, exception);
                            lock (locker)
                            {
                                if (conversionQueue.Keys.Contains(file))
                                {
                                    var operationResult = conversionQueue[file];
                                    if (operationResult.Delete)
                                    {
                                        conversionQueue.Remove(file);
                                        cache.Remove(GetKey(file));
                                    }
                                    else
                                    {
                                        operationResult.Result       = FileJsonSerializer(file);
                                        operationResult.Progress     = 100;
                                        operationResult.StopDateTime = DateTime.Now;
                                        operationResult.Error        = exception.Message;
                                        cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(30));
                                    }
                                }
                            }
                            continue;
                        }

                        if (operationResultProgress < 100)
                        {
                            lock (locker)
                            {
                                if (conversionQueue.Keys.Contains(file))
                                {
                                    var operationResult = conversionQueue[file];
                                    operationResult.Processed = "";
                                    operationResult.Progress  = operationResultProgress;
                                    cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(30));
                                }
                            }
                            continue;
                        }

                        using (var fileDao = Global.DaoFactory.GetFileDao())
                            using (var folderDao = Global.DaoFactory.GetFolderDao())
                            {
                                var newFileTitle = FileUtility.ReplaceFileExtension(file.Title, FileUtility.GetInternalExtension(file.Title));

                                File newFile = null;
                                if (FilesSettings.UpdateIfExist && (!currentFolder || !file.ProviderEntry))
                                {
                                    newFile = fileDao.GetFile(folderId, newFileTitle);
                                    if (newFile != null && Global.GetFilesSecurity().CanEdit(newFile) && !EntryManager.FileLockedForMe(newFile.ID) && !FileTracker.IsEditing(newFile.ID))
                                    {
                                        newFile.Version++;
                                    }
                                    else
                                    {
                                        newFile = null;
                                    }
                                }

                                if (newFile == null)
                                {
                                    newFile = new File {
                                        FolderID = folderId
                                    };
                                }
                                newFile.Title         = newFileTitle;
                                newFile.ConvertedType = null;
                                newFile.Comment       = string.Format(FilesCommonResource.CommentConvert, file.Title);

                                var operationResultError = string.Empty;
                                try
                                {
                                    var req = (HttpWebRequest)WebRequest.Create(convertedFileUrl);

                                    if (WorkContext.IsMono && ServicePointManager.ServerCertificateValidationCallback == null)
                                    {
                                        ServicePointManager.ServerCertificateValidationCallback += (s, c, n, p) => true; //HACK: http://ubuntuforums.org/showthread.php?t=1841740
                                    }

                                    using (var convertedFileStream = new ResponseStream(req.GetResponse()))
                                    {
                                        newFile.ContentLength = convertedFileStream.Length;
                                        newFile = fileDao.SaveFile(newFile, convertedFileStream);
                                    }

                                    FilesMessageService.Send(newFile, MessageInitiator.DocsService, MessageAction.FileConverted, newFile.Title);
                                    FileMarker.MarkAsNew(newFile);

                                    using (var tagDao = Global.DaoFactory.GetTagDao())
                                    {
                                        var tags = tagDao.GetTags(file.ID, FileEntryType.File, TagType.System).ToList();
                                        if (tags.Any())
                                        {
                                            tags.ForEach(r => r.EntryId = newFile.ID);
                                            tagDao.SaveTags(tags.ToArray());
                                        }
                                    }

                                    operationResultProgress = 100;
                                }
                                catch (WebException e)
                                {
                                    using (var response = e.Response)
                                    {
                                        var httpResponse = (HttpWebResponse)response;
                                        var errorString  = String.Format("Error code: {0}", httpResponse.StatusCode);

                                        if (httpResponse.StatusCode != HttpStatusCode.NotFound)
                                        {
                                            using (var data = response.GetResponseStream())
                                            {
                                                var text = new StreamReader(data).ReadToEnd();
                                                errorString += String.Format(" Error message: {0}", text);
                                            }
                                        }

                                        operationResultProgress = 100;
                                        operationResultError    = errorString;

                                        Global.Logger.ErrorFormat("{0} ConvertUrl: {1} fromUrl: {2}: {3}", errorString, convertedFileUrl, fileUri, e);
                                        throw new Exception(errorString);
                                    }
                                }
                                finally
                                {
                                    var fileSecurity   = Global.GetFilesSecurity();
                                    var removeOriginal = !FilesSettings.StoreOriginalFiles && fileSecurity.CanDelete(file) && currentFolder && !EntryManager.FileLockedForMe(file.ID);
                                    var folderTitle    = folderDao.GetFolder(newFile.FolderID).Title;

                                    lock (locker)
                                    {
                                        if (conversionQueue.Keys.Contains(file))
                                        {
                                            var operationResult = conversionQueue[file];
                                            if (operationResult.Delete)
                                            {
                                                conversionQueue.Remove(file);
                                                cache.Remove(GetKey(file));
                                            }
                                            else
                                            {
                                                operationResult.Result       = FileJsonSerializer(newFile, removeOriginal, folderTitle);
                                                operationResult.StopDateTime = DateTime.Now;
                                                operationResult.Processed    = "1";
                                                operationResult.Progress     = operationResultProgress;
                                                if (!string.IsNullOrEmpty(operationResultError))
                                                {
                                                    operationResult.Error = operationResultError;
                                                }
                                                cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(30));
                                            }
                                        }
                                    }

                                    if (removeOriginal)
                                    {
                                        FileMarker.RemoveMarkAsNewForAll(file);
                                        fileDao.DeleteFile(file.ID);
                                    }
                                }
                            }
                    }

                    lock (locker)
                    {
                        timer.Change(TIMER_PERIOD, TIMER_PERIOD);
                    }
                }
                catch (Exception exception)
                {
                    Global.Logger.Error(exception.Message, exception);
                    lock (locker)
                    {
                        timer.Change(Timeout.Infinite, Timeout.Infinite);
                    }
                }
                finally
                {
                    Monitor.Exit(singleThread);
                }
            }
        }