Esempio n. 1
0
        private static string GetFileStreamUrl(string fileId)
        {
            Global.Logger.Debug("GoogleDriveApp: get file stream url " + fileId);

            var uriBuilder = new UriBuilder(CommonLinkUtility.GetFullAbsolutePath(ThirdPartyAppHandler.HandlerPath));

            if (uriBuilder.Uri.IsLoopback)
            {
                uriBuilder.Host = Dns.GetHostName();
            }
            var query = uriBuilder.Query;

            query += FilesLinkUtility.Action + "=stream&";
            query += FilesLinkUtility.FileId + "=" + HttpUtility.UrlEncode(fileId) + "&";
            query += CommonLinkUtility.ParamName_UserUserID + "=" + HttpUtility.UrlEncode(SecurityContext.CurrentAccount.ID.ToString()) + "&";
            query += FilesLinkUtility.AuthKey + "=" + EmailValidationKeyProvider.GetEmailKey(fileId + SecurityContext.CurrentAccount.ID) + "&";
            query += ThirdPartySelector.AppAttr + "=" + AppAttr;

            return(uriBuilder.Uri + "?" + query);
        }
Esempio n. 2
0
        private void DownloadFile(int attachmentId, HttpContext context)
        {
            var mailBoxManager = new MailBoxManager();

            var auth = context.Request[FilesLinkUtility.AuthKey];

            var openTempStream = false;

            if (!string.IsNullOrEmpty(auth))
            {
                var stream = context.Request.QueryString["stream"];

                if (!string.IsNullOrEmpty(stream))
                {
                    int validateTimespan;
                    int.TryParse(WebConfigurationManager.AppSettings["files.stream-url-minute"], out validateTimespan);
                    if (validateTimespan <= 0)
                    {
                        validateTimespan = 5;
                    }

                    var validateResult = EmailValidationKeyProvider.ValidateEmailKey(attachmentId + stream, auth, TimeSpan.FromMinutes(validateTimespan));
                    if (validateResult != EmailValidationKeyProvider.ValidationResult.Ok)
                    {
                        var exc = new HttpException((int)HttpStatusCode.Forbidden, "You don't have enough permission to perform the operation");
                        //Global.Logger.Error(string.Format("{0} {1}: {2}", CommonLinkUtility.AuthKey, validateResult, context.Request.Url), exc);
                        throw exc;
                    }

                    openTempStream = true;
                }
            }

            using (var file = openTempStream
                                  ? mailBoxManager.GetAttachmentStream(attachmentId, TenantId)
                                  : mailBoxManager.GetAttachmentStream(attachmentId, TenantId, Username))
            {
                context.Response.AddHeader("Content-Disposition", ContentDispositionUtil.GetHeaderValue(file.FileName));
                file.FileStream.StreamCopyTo(context.Response.OutputStream);
            }
        }
 public DocumentServiceTrackerHelper(
     SecurityContext securityContext,
     UserManager userManager,
     TenantManager tenantManager,
     FilesLinkUtility filesLinkUtility,
     EmailValidationKeyProvider emailValidationKeyProvider,
     BaseCommonLinkUtility baseCommonLinkUtility,
     SocketManager socketManager,
     GlobalStore globalStore,
     DisplayUserSettingsHelper displayUserSettingsHelper,
     IDaoFactory daoFactory,
     IOptionsMonitor <ILog> options,
     DocumentServiceHelper documentServiceHelper,
     EntryManager entryManager,
     FileShareLink fileShareLink,
     FilesMessageService filesMessageService,
     DocumentServiceConnector documentServiceConnector,
     NotifyClient notifyClient,
     MailMergeTaskRunner mailMergeTaskRunner,
     FileTrackerHelper fileTracker)
 {
     SecurityContext            = securityContext;
     UserManager                = userManager;
     TenantManager              = tenantManager;
     FilesLinkUtility           = filesLinkUtility;
     EmailValidationKeyProvider = emailValidationKeyProvider;
     BaseCommonLinkUtility      = baseCommonLinkUtility;
     SocketManager              = socketManager;
     GlobalStore                = globalStore;
     DisplayUserSettingsHelper  = displayUserSettingsHelper;
     DaoFactory               = daoFactory;
     DocumentServiceHelper    = documentServiceHelper;
     EntryManager             = entryManager;
     FileShareLink            = fileShareLink;
     FilesMessageService      = filesMessageService;
     DocumentServiceConnector = documentServiceConnector;
     NotifyClient             = notifyClient;
     MailMergeTaskRunner      = mailMergeTaskRunner;
     FileTracker              = fileTracker;
     Logger = options.CurrentValue;
 }
        public static string GetPreSignedUri(int fileId, int tenant, string user, string stream, int fileNumber, string fileName)
        {
            //TODO: Move url to config;
            const string attachmentPath = "/addons/mail/httphandlers/download.ashx";

            var uriBuilder = new UriBuilder(CommonLinkUtility.GetFullAbsolutePath(attachmentPath));

            if (uriBuilder.Uri.IsLoopback)
            {
                uriBuilder.Host = Dns.GetHostName();
            }
            var query = uriBuilder.Query;

            query += "attachid=" + fileId + "&";
            query += "stream=" + stream + "&";
            query += FilesLinkUtility.AuthKey + "=" + EmailValidationKeyProvider.GetEmailKey(fileId + stream);

            var url = uriBuilder.Uri + "?" + query;

            return(url);
        }
Esempio n. 5
0
 public StorageSettingsHelper(
     BaseStorageSettingsListener baseStorageSettingsListener,
     StorageFactoryConfig storageFactoryConfig,
     PathUtils pathUtils,
     EmailValidationKeyProvider emailValidationKeyProvider,
     ICacheNotify <DataStoreCacheItem> cache,
     IOptionsMonitor <ILog> options,
     TenantManager tenantManager,
     SettingsManager settingsManager,
     IHttpContextAccessor httpContextAccessor)
 {
     BaseStorageSettingsListener = baseStorageSettingsListener;
     StorageFactoryConfig        = storageFactoryConfig;
     PathUtils = pathUtils;
     EmailValidationKeyProvider = emailValidationKeyProvider;
     Cache               = cache;
     Options             = options;
     TenantManager       = tenantManager;
     SettingsManager     = settingsManager;
     HttpContextAccessor = httpContextAccessor;
 }
Esempio n. 6
0
        public string GetFileChangesUrl <T>(File <T> file, string doc = null)
        {
            if (file == null)
            {
                throw new ArgumentNullException("file", FilesCommonResource.ErrorMassage_FileNotFound);
            }

            var uriBuilder = new UriBuilder(CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.FileHandlerPath));
            var query      = uriBuilder.Query;

            query += $"{FilesLinkUtility.Action}=diff&";
            query += $"{FilesLinkUtility.FileId}={HttpUtility.UrlEncode(file.ID.ToString())}&";
            query += $"{FilesLinkUtility.Version}={file.Version}&";
            query += $"{FilesLinkUtility.AuthKey}={EmailValidationKeyProvider.GetEmailKey(file.ID + file.Version.ToString(CultureInfo.InvariantCulture))}";
            if (!string.IsNullOrEmpty(doc))
            {
                query += $"&{FilesLinkUtility.DocShareKey}={HttpUtility.UrlEncode(doc)}";
            }

            return($"{uriBuilder.Uri}?{query}");
        }
 public AuthenticationController(
     UserManager userManager,
     TenantManager tenantManager,
     SecurityContext securityContext,
     TenantCookieSettingsHelper tenantCookieSettingsHelper,
     EmailValidationKeyProvider emailValidationKeyProvider,
     AuthContext authContext,
     AuthManager authManager,
     CookiesManager cookiesManager,
     PasswordHasher passwordHasher)
 {
     UserManager                = userManager;
     TenantManager              = tenantManager;
     SecurityContext            = securityContext;
     TenantCookieSettingsHelper = tenantCookieSettingsHelper;
     EmailValidationKeyProvider = emailValidationKeyProvider;
     AuthContext                = authContext;
     AuthManager                = authManager;
     CookiesManager             = cookiesManager;
     PasswordHasher             = passwordHasher;
 }
Esempio n. 8
0
        private void ProcessSmsValidation(UserTransferData uData)
        {
            var smsAuthSettings = SettingsManager.Instance.LoadSettings <StudioSmsNotificationSettings>(TenantProvider.CurrentTenantID);

            if (smsAuthSettings.Enable && SetupInfo.IsVisibleSettings <StudioSmsNotificationSettings>())
            {
                var confKey   = CookiesManager.GetCookies(CookiesType.ConfKey);
                var activated = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).MobilePhoneActivationStatus;

                if (!String.IsNullOrEmpty(confKey) && EmailValidationKeyProvider.ValidateEmailKey(CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).Email, confKey, TimeSpan.FromDays(30)) == EmailValidationKeyProvider.ValidationResult.Ok)
                {
                    return;
                }

                uData.MobilePhoneActivationStatus = activated;
                uData.ValidationKey         = EmailValidationKeyProvider.GetEmailKey(GetEmailKey(uData, activated));
                Session["UserTransferData"] = uData;
                ProcessLogout();
                Response.Redirect(String.Format("~/Confirm.aspx?type={0}", activated == MobilePhoneActivationStatus.Activated ? ConfirmType.PhoneAuth : ConfirmType.PhoneActivation));
            }
        }
Esempio n. 9
0
        public static string GetLicenseUrl(File file)
        {
            if (!CoreContext.Configuration.Standalone)
            {
                return(string.Empty);
            }
            if (file == null)
            {
                return(string.Empty);
            }

            //NOTE: Always build path to handler!
            var uriBuilder = new UriBuilder(CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.FileHandlerPath));
            var query      = uriBuilder.Query;

            query += FilesLinkUtility.Action + "=license&";
            query += FilesLinkUtility.FileId + "=" + HttpUtility.UrlEncode(file.ID.ToString()) + "&";
            query += FilesLinkUtility.AuthKey + "=" + EmailValidationKeyProvider.GetEmailKey(file.ID.ToString());

            return(uriBuilder.Uri + "?" + query);
        }
        public static string GetFileChangesUrl(File file, string doc = null)
        {
            if (file == null)
            {
                throw new ArgumentNullException("file", FilesCommonResource.ErrorMassage_FileNotFound);
            }

            var uriBuilder = new UriBuilder(CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.FileHandlerPath));
            var query      = uriBuilder.Query;

            query += FilesLinkUtility.Action + "=diff&";
            query += FilesLinkUtility.FileId + "=" + HttpUtility.UrlEncode(file.ID.ToString()) + "&";
            query += FilesLinkUtility.Version + "=" + file.Version + "&";
            query += FilesLinkUtility.AuthKey + "=" + EmailValidationKeyProvider.GetEmailKey(file.ID + file.Version.ToString(CultureInfo.InvariantCulture));
            if (!string.IsNullOrEmpty(doc))
            {
                query += "&" + FilesLinkUtility.DocShareKey + "=" + HttpUtility.UrlEncode(doc);
            }

            return(uriBuilder.Uri + "?" + query);
        }
Esempio n. 11
0
 public ConfirmAuthHandler(
     IOptionsMonitor <AuthenticationSchemeOptions> options,
     ILoggerFactory logger,
     UrlEncoder encoder,
     ISystemClock clock,
     SecurityContext securityContext,
     EmailValidationKeyProvider emailValidationKeyProvider,
     SetupInfo setupInfo,
     TenantManager tenantManager,
     UserManager userManager,
     AuthManager authManager,
     AuthContext authContext) :
     base(options, logger, encoder, clock)
 {
     SecurityContext            = securityContext;
     EmailValidationKeyProvider = emailValidationKeyProvider;
     SetupInfo     = setupInfo;
     TenantManager = tenantManager;
     UserManager   = userManager;
     AuthManager   = authManager;
     AuthContext   = authContext;
 }
        public static string GetPreSignedUri(int fileId, int tenant, string user, string stream, int fileNumber,
                                             string fileName, IDataStore dataStore)
        {
            var attachmentPath = GetFileKey(user, stream, fileNumber, fileName);

            if (dataStore == null)
            {
                dataStore = MailDataStore.GetDataStore(tenant);
            }

            string url;

            if (dataStore is S3Storage)
            {
                var contentDispositionFileName = ContentDispositionUtil.GetHeaderValue(fileName, withoutBase: true);
                var headersForUrl = new [] { "Content-Disposition:" + contentDispositionFileName };
                url = dataStore.GetPreSignedUri("", attachmentPath, TimeSpan.FromMinutes(10), headersForUrl).ToString();
            }
            else
            {
                //TODO: Move url to config;
                attachmentPath = "/addons/mail/httphandlers/download.ashx";

                var uriBuilder = new UriBuilder(CommonLinkUtility.GetFullAbsolutePath(attachmentPath));
                if (uriBuilder.Uri.IsLoopback)
                {
                    uriBuilder.Host = Dns.GetHostName();
                }
                var query = uriBuilder.Query;

                query += "attachid=" + fileId + "&";
                query += "stream=" + stream + "&";
                query += FilesLinkUtility.AuthKey + "=" + EmailValidationKeyProvider.GetEmailKey(fileId + stream);

                url = uriBuilder.Uri + "?" + query;
            }

            return(url);
        }
Esempio n. 13
0
        [Create("sendcongratulations", false)] //NOTE: this method doesn't requires auth!!!
        public void SendCongratulations(Guid userid, string key)
        {
            var authInterval   = TimeSpan.FromHours(1);
            var checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(userid.ToString() + ConfirmType.Auth, key, authInterval);

            switch (checkKeyResult)
            {
            case EmailValidationKeyProvider.ValidationResult.Ok:
                var currentUser = CoreContext.UserManager.GetUsers(userid);
                StudioNotifyService.Instance.SendCongratulations(currentUser);
                FirstTimeTenantSettings.SendInstallInfo(currentUser);

                if (SetupInfo.SmsRegistration && !SetupInfo.IsSecretEmail(currentUser.Email))
                {
                    StudioSmsNotificationSettings.Enable = true;
                }
                break;

            default:
                throw new SecurityException("Access Denied.");
            }
        }
Esempio n. 14
0
        public void UserPasswordChange(UserInfo userInfo)
        {
            var email         = userInfo.Email.ToLower();
            var validationKey = EmailValidationKeyProvider.GetEmailKey(email + ConfirmType.PasswordChange.ToString().ToLower());

            var inviteUrl = CommonLinkUtility.GetFullAbsolutePath(String.Format("~/confirm.aspx?type={2}&email={0}&key={1}",
                                                                                HttpUtility.UrlEncode(email), validationKey,
                                                                                ConfirmType.PasswordChange.ToString().ToLower()));

            client.SendNoticeToAsync(
                Constants.ActionPasswordChange,
                null,
                RecipientFromEmail(new[] { email }, false),
                new[] { EMailSenderName },
                null,
                new TagValue(Constants.TagUserName, SecurityContext.IsAuthenticated ? DisplayUserSettings.GetFullUserName(SecurityContext.CurrentAccount.ID) : ((HttpContext.Current != null) ? HttpContext.Current.Request.UserHostAddress : null)),
                new TagValue(Constants.TagInviteLink, inviteUrl),
                new TagValue(Constants.TagBody, ""),
                //User name tag
                new TagValue(new Tag("UserDisplayName"), userInfo.DisplayUserName())
                );
        }
Esempio n. 15
0
 public StorageFactory(
     StorageFactoryListener storageFactoryListener,
     StorageFactoryConfig storageFactoryConfig,
     SettingsManager settingsManager,
     StorageSettingsHelper storageSettingsHelper,
     TenantManager tenantManager,
     CoreBaseSettings coreBaseSettings,
     PathUtils pathUtils,
     EmailValidationKeyProvider emailValidationKeyProvider,
     IOptionsMonitor <ILog> options,
     IHttpContextAccessor httpContextAccessor)
 {
     StorageFactoryListener = storageFactoryListener;
     StorageFactoryConfig   = storageFactoryConfig;
     SettingsManager        = settingsManager;
     StorageSettingsHelper  = storageSettingsHelper;
     TenantManager          = tenantManager;
     CoreBaseSettings       = coreBaseSettings;
     PathUtils = pathUtils;
     EmailValidationKeyProvider = emailValidationKeyProvider;
     Options             = options;
     HttpContextAccessor = httpContextAccessor;
 }
        public static string GetConfirmationUrlRelative(int tenantId, string email, ConfirmType confirmType, object postfix = null, Guid userId = default)
        {
            var validationKey = EmailValidationKeyProvider.GetEmailKey(tenantId, email + confirmType + (postfix ?? ""));

            var link = $"confirm/{confirmType}?key={validationKey}";

            if (!string.IsNullOrEmpty(email))
            {
                link += $"&email={HttpUtility.UrlEncode(email)}";
            }

            if (userId != default)
            {
                link += $"&uid={userId}";
            }

            if (postfix != null)
            {
                link += "&p=1";
            }

            return(link);
        }
Esempio n. 17
0
        public static string GetConfirmationUrlRelative(int tenantId, string email, ConfirmType confirmType, object postfix = null, Guid userId = default(Guid))
        {
            var validationKey = EmailValidationKeyProvider.GetEmailKey(tenantId, email + confirmType + (postfix ?? ""));

            var link = string.Format("confirm.aspx?type={0}&key={1}", confirmType, validationKey);

            if (!string.IsNullOrEmpty(email))
            {
                link += "&email=" + HttpUtility.UrlEncode(email);
            }

            if (userId != default(Guid))
            {
                link += "&uid=" + userId;
            }

            if (postfix != null)
            {
                link += "&p=1";
            }

            return(link);
        }
Esempio n. 18
0
        private static void StreamFile(HttpContext context)
        {
            try
            {
                var id   = context.Request[UrlConstant.FileId];
                var ver  = context.Request[UrlConstant.Version];
                var auth = context.Request[UrlConstant.AuthKey];

                if (EmailValidationKeyProvider.ValidateEmailKey(id + ver, auth, TimeSpan.FromMinutes(1)) != EmailValidationKeyProvider.ValidationResult.Ok)
                {
                    throw new HttpException((int)HttpStatusCode.Forbidden, FilesCommonResource.ErrorMassage_SecurityException);
                }

                using (var dao = Global.DaoFactory.GetFileDao())
                {
                    var file = dao.GetFile(id, Convert.ToInt32(ver));
                    using (var stream = dao.GetFileStream(file))
                    {
                        context.Response.AddHeader("Content-Length", stream.Length.ToString(CultureInfo.InvariantCulture));
                        stream.StreamCopyTo(context.Response.OutputStream);
                    }
                }
            }
            catch (Exception ex)
            {
                context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                context.Response.Write(ex.Message);
            }
            try
            {
                context.Response.Flush();
                context.Response.End();
            }
            catch (HttpException)
            {
            }
        }
Esempio n. 19
0
        void SendInvite(UserInfo user, string inviteMessage, bool join, bool withFullAccessPrivileges)
        {
            var email         = user.Email.ToLower();
            var validationKey = EmailValidationKeyProvider.GetEmailKey(
                email + ConfirmType.EmpInvite.ToString().ToLower() + (withFullAccessPrivileges ? "allrights" : ""));


            string inviteUrl = String.Format("~/confirm.aspx?type={2}&email={0}&firstname={4}&lastname={5}&key={1}{3}{6}&uid={7}",
                                             HttpUtility.UrlEncode(email),                                              //0
                                             validationKey,                                                             //1
                                             ConfirmType.EmpInvite.ToString().ToLower(),                                //2
                                             withFullAccessPrivileges ? "&fap=1" : "",                                  //3
                                             HttpUtility.UrlEncode(user.FirstName),                                     //4
                                             HttpUtility.UrlEncode(user.LastName),                                      //5
                                             String.IsNullOrEmpty(user.Department) ? "" : "&deptID=" + user.Department, //6
                                             SecurityContext.CurrentAccount.ID);

            client.SendNoticeToAsync(
                join ? Constants.ActionJoinUsers : Constants.ActionInviteUsers,
                null,
                RecipientFromEmail(new string[] { email }, join),        /*if it's invite - don't check activation status*/
                new[] { EMailSenderName },
                null,
                new TagValue(Constants.TagUserName,
                             SecurityContext.IsAuthenticated ? DisplayUserSettings.GetFullUserName(SecurityContext.CurrentAccount.ID) : ((HttpContext.Current != null) ? HttpContext.Current.Request.UserHostAddress : null)
                             ),

                new TagValue(Constants.TagInviteLink, CommonLinkUtility.GetFullAbsolutePath(inviteUrl)),

                new TagValue(Constants.TagBody, inviteMessage ?? ""),

                //User name tag
                new TagValue(new Tag("UserDisplayName"), (user.DisplayUserName() ?? "").Trim()),
                CreateSendFromTag()
                );
        }
Esempio n. 20
0
        private static void StreamFile(HttpContext context)
        {
            var id   = context.Request[FilesLinkUtility.FileId];
            var auth = context.Request[FilesLinkUtility.AuthKey];
            int version;

            int.TryParse(context.Request[FilesLinkUtility.Version] ?? "", out version);

            var validateResult = EmailValidationKeyProvider.ValidateEmailKey(id + version, auth ?? "", Global.StreamUrlExpire);

            if (validateResult != EmailValidationKeyProvider.ValidationResult.Ok)
            {
                var exc = new HttpException((int)HttpStatusCode.Forbidden, FilesCommonResource.ErrorMassage_SecurityException);

                Global.Logger.Error(string.Format("{0} {1}: {2}", FilesLinkUtility.AuthKey, validateResult, context.Request.Url), exc);

                context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                context.Response.Write(FilesCommonResource.ErrorMassage_SecurityException);
                return;
            }

            if (!string.IsNullOrEmpty(FileUtility.SignatureSecret))
            {
                try
                {
                    var header = context.Request.Headers[FileUtility.SignatureHeader];
                    if (string.IsNullOrEmpty(header) || !header.StartsWith("Bearer "))
                    {
                        throw new Exception("header is null");
                    }
                    header = header.Substring("Bearer ".Length);

                    JsonWebToken.JsonSerializer = new DocumentService.JwtSerializer();
                    JsonWebToken.Decode(header, FileUtility.SignatureSecret);
                }
                catch (Exception ex)
                {
                    Global.Logger.Error("Download stream header", ex);
                    context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                    context.Response.Write(FilesCommonResource.ErrorMassage_SecurityException);
                    return;
                }
            }

            try
            {
                using (var fileDao = Global.DaoFactory.GetFileDao())
                {
                    fileDao.InvalidateCache(id);

                    var file = version > 0
                                   ? fileDao.GetFile(id, version)
                                   : fileDao.GetFile(id);

                    if (!string.IsNullOrEmpty(file.Error))
                    {
                        throw new Exception(file.Error);
                    }

                    using (var stream = fileDao.GetFileStream(file))
                    {
                        context.Response.AddHeader("Content-Length",
                                                   stream.CanSeek
                                                       ? stream.Length.ToString(CultureInfo.InvariantCulture)
                                                       : file.ContentLength.ToString(CultureInfo.InvariantCulture));
                        stream.StreamCopyTo(context.Response.OutputStream);
                    }
                }
            }
            catch (Exception ex)
            {
                Global.Logger.Error("Error for: " + context.Request.Url, ex);
                context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                context.Response.Write(ex.Message);
                return;
            }

            try
            {
                context.Response.Flush();
                context.Response.End();
            }
            catch (HttpException)
            {
            }
        }
Esempio n. 21
0
        private static void StreamFile(HttpContext context)
        {
            try
            {
                var fileId = context.Request[FilesLinkUtility.FileId];
                var auth   = context.Request[FilesLinkUtility.AuthKey];
                var userId = context.Request[CommonLinkUtility.ParamName_UserUserID];

                Global.Logger.Debug("GoogleDriveApp: get file stream " + fileId);

                var validateResult = EmailValidationKeyProvider.ValidateEmailKey(fileId + userId, auth, Global.StreamUrlExpire);
                if (validateResult != EmailValidationKeyProvider.ValidationResult.Ok)
                {
                    var exc = new HttpException((int)HttpStatusCode.Forbidden, FilesCommonResource.ErrorMassage_SecurityException);

                    Global.Logger.Error(string.Format("GoogleDriveApp: validate error {0} {1}: {2}", FilesLinkUtility.AuthKey, validateResult, context.Request.Url), exc);

                    throw exc;
                }

                var token     = Token.GetToken(AppAttr, userId);
                var driveFile = GetDriveFile(fileId, token);

                var jsonFile = JObject.Parse(driveFile);

                var downloadUrl = GoogleLoginProvider.GoogleUrlFile + fileId + "?alt=media";

                if (string.IsNullOrEmpty(downloadUrl))
                {
                    Global.Logger.Error("GoogleDriveApp: downloadUrl is null");
                    throw new Exception("downloadUrl is null");
                }

                Global.Logger.Debug("GoogleDriveApp: get file stream  downloadUrl - " + downloadUrl);

                var request = (HttpWebRequest)WebRequest.Create(downloadUrl);
                request.Method = "GET";
                request.Headers.Add("Authorization", "Bearer " + token);

                using (var response = request.GetResponse())
                    using (var stream = new ResponseStream(response))
                    {
                        stream.StreamCopyTo(context.Response.OutputStream);

                        var contentLength = jsonFile.Value <string>("size");
                        Global.Logger.Debug("GoogleDriveApp: get file stream  contentLength - " + contentLength);
                        context.Response.AddHeader("Content-Length", contentLength);
                    }
            }
            catch (Exception ex)
            {
                context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                context.Response.Write(ex.Message);
                Global.Logger.Error("GoogleDriveApp: Error request " + context.Request.Url, ex);
            }
            try
            {
                context.Response.Flush();
                context.Response.End();
            }
            catch (HttpException)
            {
            }
        }
Esempio n. 22
0
        public Uri GetPreSignedUri(string domain, string path, TimeSpan expire, IEnumerable <string> headers)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            if (string.IsNullOrEmpty(_tenant) && IsSupportInternalUri)
            {
                return(GetInternalUri(domain, path, expire, headers));
            }

            var headerAttr = string.Empty;

            if (headers != null)
            {
                headerAttr = string.Join("&", headers);
            }

            if (expire == TimeSpan.Zero || expire == TimeSpan.MinValue || expire == TimeSpan.MaxValue)
            {
                expire = GetExpire(domain);
            }

            var query = string.Empty;

            if (expire != TimeSpan.Zero && expire != TimeSpan.MinValue && expire != TimeSpan.MaxValue)
            {
                var expireString = expire.TotalMinutes.ToString(CultureInfo.InvariantCulture);

                int currentTenantId;
                var currentTenant = CoreContext.TenantManager.GetCurrentTenant(false);
                if (currentTenant != null)
                {
                    currentTenantId = currentTenant.TenantId;
                }
                else if (!TennantPath.TryGetTenant(_tenant, out currentTenantId))
                {
                    currentTenantId = 0;
                }

                var auth = EmailValidationKeyProvider.GetEmailKey(currentTenantId, path.Replace('/', Path.DirectorySeparatorChar) + "." + headerAttr + "." + expireString);
                query = string.Format("{0}{1}={2}&{3}={4}",
                                      path.Contains("?") ? "&" : "?",
                                      Constants.QUERY_EXPIRE,
                                      expireString,
                                      Constants.QUERY_AUTH,
                                      auth);
            }

            if (!string.IsNullOrEmpty(headerAttr))
            {
                query += string.Format("{0}{1}={2}",
                                       query.Contains("?") ? "&" : "?",
                                       Constants.QUERY_HEADER,
                                       HttpUtility.UrlEncode(headerAttr));
            }

            var tenant = _tenant.Trim('/');
            var vpath  = PathUtils.ResolveVirtualPath(_modulename, domain);

            vpath = PathUtils.ResolveVirtualPath(vpath, false);
            vpath = string.Format(vpath, tenant);
            var virtualPath = new Uri(vpath + "/", UriKind.RelativeOrAbsolute);

            var uri = virtualPath.IsAbsoluteUri ?
                      new MonoUri(virtualPath, virtualPath.LocalPath.TrimEnd('/') + EnsureLeadingSlash(path.Replace('\\', '/')) + query) :
                      new MonoUri(virtualPath.ToString().TrimEnd('/') + EnsureLeadingSlash(path.Replace('\\', '/')) + query, UriKind.Relative);

            return(uri);
        }
Esempio n. 23
0
        public static string GetCallbackUrl(string fileId)
        {
            var callbackUrl = CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.FileHandlerPath
                                                                    + "?" + FilesLinkUtility.Action + "=track"
                                                                    + "&" + FilesLinkUtility.FileId + "=" + HttpUtility.UrlEncode(fileId)
                                                                    + "&" + FilesLinkUtility.AuthKey + "=" + EmailValidationKeyProvider.GetEmailKey(fileId));

            callbackUrl = DocumentServiceConnector.ReplaceCommunityAdress(callbackUrl);
            return(callbackUrl);
        }
Esempio n. 24
0
        private bool CheckValidationKey()
        {
            var key      = Request["key"] ?? "";
            var emplType = Request["emplType"] ?? "";

            var validInterval = SetupInfo.ValidEamilKeyInterval;
            var authInterval  = TimeSpan.FromHours(1);

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

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

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

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

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

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

                    if (!SecurityContext.IsAuthenticated)
                    {
                        if (StudioSmsNotificationSettings.IsVisibleSettings && StudioSmsNotificationSettings.Enable)
                        {
                            Response.Redirect(SmsConfirmUrl(user), true);
                        }

                        var authCookie = SecurityContext.AuthenticateMe(user.ID);
                        CookiesManager.SetCookies(CookiesType.AuthKey, authCookie);
                        MessageService.Send(HttpContext.Current.Request, MessageAction.LoginSuccess, user.DisplayUserName(false));
                    }

                    AuthRedirect(user, first.ToLower() == "true", module, Request[FilesLinkUtility.FileUri]);
                }
            }
            break;

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

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

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

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

            case ConfirmType.PasswordChange:

                var userHash = !String.IsNullOrEmpty(Request["p"]) && Request["p"] == "1";

                String hash = String.Empty;

                if (userHash)
                {
                    hash = CoreContext.Authentication.GetUserPasswordHash(CoreContext.UserManager.GetUserByEmail(_email).ID);
                }

                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_email + _type + (string.IsNullOrEmpty(hash) ? string.Empty : Hasher.Base64Hash(hash)), key, validInterval);
                break;

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

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

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

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

            return(true);
        }
Esempio n. 25
0
        public void ProcessRequest(HttpContext context)
        {
            if (_checkAuth && !SecurityContext.IsAuthenticated)
            {
                context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                return;
            }

            var storage = StorageFactory.GetStorage(CoreContext.TenantManager.GetCurrentTenant().TenantId.ToString(CultureInfo.InvariantCulture), _module);

            var path   = _path;
            var header = context.Request[Constants.QUERY_HEADER] ?? "";

            var auth          = context.Request[Constants.QUERY_AUTH];
            var storageExpire = storage.GetExpire(_domain);

            if (storageExpire != TimeSpan.Zero && storageExpire != TimeSpan.MinValue && storageExpire != TimeSpan.MaxValue || !string.IsNullOrEmpty(auth))
            {
                var expire = context.Request[Constants.QUERY_EXPIRE];
                if (string.IsNullOrEmpty(expire))
                {
                    expire = storageExpire.TotalMinutes.ToString(CultureInfo.InvariantCulture);
                }

                var validateResult = EmailValidationKeyProvider.ValidateEmailKey(path + "." + header + "." + expire, auth ?? "", TimeSpan.FromMinutes(Convert.ToDouble(expire)));
                if (validateResult != EmailValidationKeyProvider.ValidationResult.Ok)
                {
                    context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                    return;
                }
            }

            if (!storage.IsFile(_domain, path))
            {
                context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                return;
            }

            var headers = header.Length > 0 ? header.Split('&').Select(HttpUtility.UrlDecode) : new string[] { };

            const int bigSize = 5 * 1024 * 1024;

            if (storage.IsSupportInternalUri && bigSize < storage.GetFileSize(_domain, path))
            {
                var uri = storage.GetInternalUri(_domain, path, TimeSpan.FromMinutes(15), headers);

                context.Response.Cache.SetAllowResponseInBrowserHistory(false);
                context.Response.Cache.SetCacheability(HttpCacheability.NoCache);

                context.Response.Redirect(uri.ToString());
                return;
            }

            string encoding = null;

            if (storage is DiscDataStore && storage.IsFile(_domain, path + ".gz"))
            {
                path    += ".gz";
                encoding = "gzip";
            }

            var headersToCopy = new List <string> {
                "Content-Disposition", "Cache-Control", "Content-Encoding", "Content-Language", "Content-Type", "Expires"
            };

            foreach (var h in headers)
            {
                var toCopy = headersToCopy.Find(x => h.StartsWith(x));
                if (string.IsNullOrEmpty(toCopy))
                {
                    continue;
                }
                context.Response.Headers[toCopy] = h.Substring(toCopy.Length + 1);
            }

            context.Response.ContentType = MimeMapping.GetMimeMapping(path);
            if (encoding != null)
            {
                context.Response.Headers["Content-Encoding"] = encoding;
            }

            if (!context.Response.IsClientConnected)
            {
                context.Response.End();
                return;
            }

            using (var stream = storage.GetReadStream(_domain, path))
            {
                context.Response.Buffer = false;

                long offset = 0;
                var  length = stream.Length;
                if (stream.CanSeek)
                {
                    length = ProcessRangeHeader(context, stream.Length, ref offset);
                    stream.Seek(offset, SeekOrigin.Begin);
                }

                context.Response.AddHeader("Connection", "Keep-Alive");
                context.Response.AddHeader("Content-Length", length.ToString(CultureInfo.InvariantCulture));

                try
                {
                    stream.CopyTo(context.Response.OutputStream);
                    context.Response.Flush();
                }
                catch (Exception e)
                {
                    LogManager.GetLogger("ASC").Debug("StorageHandler.ProcessRequest", e);
                    context.Response.End();
                }
            }
        }
Esempio n. 26
0
        private static void DownloadFile(int attachmentId, HttpContext context)
        {
            var auth = context.Request[FilesLinkUtility.AuthKey];

            var openTempStream = false;

            if (!string.IsNullOrEmpty(auth))
            {
                var stream = context.Request.QueryString["stream"];

                if (!string.IsNullOrEmpty(stream))
                {
                    int validateTimespan;
                    int.TryParse(ConfigurationManagerExtension.AppSettings["files.stream-url-minute"], out validateTimespan);
                    if (validateTimespan <= 0)
                    {
                        validateTimespan = 5;
                    }

                    var validateResult = EmailValidationKeyProvider.ValidateEmailKey(attachmentId + stream, auth, TimeSpan.FromMinutes(validateTimespan));
                    if (validateResult != EmailValidationKeyProvider.ValidationResult.Ok)
                    {
                        var exc = new HttpException((int)HttpStatusCode.Forbidden, "You don't have enough permission to perform the operation");
                        //Global.Logger.Error(string.Format("{0} {1}: {2}", CommonLinkUtility.AuthKey, validateResult, context.Request.Url), exc);
                        throw exc;
                    }

                    openTempStream = true;
                }
            }
            else
            {
                if (!SecurityContext.IsAuthenticated)
                {
                    throw new HttpException(403, "Access denied.");
                }
            }

            var engine     = new EngineFactory(TenantId, Username);
            var attachment = engine.AttachmentEngine.GetAttachment(
                openTempStream
                    ? (IAttachmentExp) new ConcreteTenantAttachmentExp(attachmentId, TenantId)
                    : new ConcreteUserAttachmentExp(attachmentId, TenantId, Username));

            long offset    = 0;
            long endOffset = -1;
            long length    = attachment.size;

            if (context.Request.Headers["Range"] != null)
            {
                var range = context.Request.Headers["Range"].Split('=', '-');
                offset = Convert.ToInt64(range[1]);

                if (range.Count() > 2 && !string.IsNullOrEmpty(range[2]))
                {
                    endOffset = Convert.ToInt64(range[2]);
                }
                if (endOffset < 0 || endOffset >= attachment.size)
                {
                    endOffset = attachment.size - 1;
                }

                length = endOffset - offset + 1;

                if (length <= 0)
                {
                    throw new HttpException("Wrong Range header");
                }

                context.Response.StatusCode = 206;
                context.Response.AddHeader("Content-Range", String.Format(" bytes {0}-{1}/{2}", offset, endOffset, attachment.size));
            }

            using (var file = attachment.ToAttachmentStream((int)offset))
            {
                context.Response.AddHeader("Accept-Ranges", "bytes");
                context.Response.AddHeader("Content-Length", length.ToString(CultureInfo.InvariantCulture));
                context.Response.AddHeader("Content-Disposition", ContentDispositionUtil.GetHeaderValue(file.FileName));
                context.Response.ContentType = MimeMapping.GetMimeMapping(file.FileName);

                if (endOffset != attachment.size - 1)
                {
                    file.FileStream.CopyTo(context.Response.OutputStream);
                }
                else
                {
                    file.FileStream.StreamCopyTo(context.Response.OutputStream, (int)length);
                }
            }
        }
Esempio n. 27
0
        private void StreamFile(HttpContext context)
        {
            try
            {
                var fileId = context.Request.Query[FilesLinkUtility.FileId];
                var auth   = context.Request.Query[FilesLinkUtility.AuthKey];
                var userId = context.Request.Query[CommonLinkUtility.ParamName_UserUserID];

                Logger.Debug("GoogleDriveApp: get file stream " + fileId);

                var validateResult = EmailValidationKeyProvider.ValidateEmailKey(fileId + userId, auth, Global.StreamUrlExpire);
                if (validateResult != EmailValidationKeyProvider.ValidationResult.Ok)
                {
                    var exc = new HttpException((int)HttpStatusCode.Forbidden, FilesCommonResource.ErrorMassage_SecurityException);

                    Logger.Error(string.Format("GoogleDriveApp: validate error {0} {1}: {2}", FilesLinkUtility.AuthKey, validateResult, context.Request.Url()), exc);

                    throw exc;
                }

                Token token = null;

                if (Guid.TryParse(userId, out var userIdGuid))
                {
                    token = TokenHelper.GetToken(AppAttr, userIdGuid);
                }

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

                var driveFile = GetDriveFile(fileId, token);

                var jsonFile = JObject.Parse(driveFile);

                var downloadUrl = GoogleLoginProvider.GoogleUrlFile + fileId + "?alt=media";

                if (string.IsNullOrEmpty(downloadUrl))
                {
                    Logger.Error("GoogleDriveApp: downloadUrl is null");
                    throw new Exception("downloadUrl is null");
                }

                Logger.Debug("GoogleDriveApp: get file stream downloadUrl - " + downloadUrl);

                var request = (HttpWebRequest)WebRequest.Create(downloadUrl);
                request.Method = "GET";
                request.Headers.Add("Authorization", "Bearer " + token);

                using (var response = request.GetResponse())
                    using (var stream = new ResponseStream(response))
                    {
                        stream.CopyTo(context.Response.Body);

                        var contentLength = jsonFile.Value <string>("size");
                        Logger.Debug("GoogleDriveApp: get file stream contentLength - " + contentLength);
                        context.Response.Headers.Add("Content-Length", contentLength);
                    }
            }
            catch (Exception ex)
            {
                context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                context.Response.WriteAsync(ex.Message).Wait();
                Logger.Error("GoogleDriveApp: Error request " + context.Request.Url(), ex);
            }
            try
            {
                context.Response.Body.Flush();
                //TODO
                //context.Response.SuppressContent = true;
                //context.ApplicationInstance.CompleteRequest();
            }
            catch (HttpException ex)
            {
                Logger.Error("GoogleDriveApp StreamFile", ex);
            }
        }
Esempio n. 28
0
 public void Deconstruct(out TenantManager tenantManager, out SecurityContext securityContext, out StorageFactory storageFactory, out EmailValidationKeyProvider emailValidationKeyProvider)
 {
     tenantManager              = TenantManager;
     securityContext            = SecurityContext;
     storageFactory             = StorageFactory;
     emailValidationKeyProvider = EmailValidationKeyProvider;
 }
Esempio n. 29
0
 public StorageHandlerScope(TenantManager tenantManager, SecurityContext securityContext, StorageFactory storageFactory, EmailValidationKeyProvider emailValidationKeyProvider)
 {
     TenantManager              = tenantManager;
     SecurityContext            = securityContext;
     StorageFactory             = storageFactory;
     EmailValidationKeyProvider = emailValidationKeyProvider;
 }
Esempio n. 30
0
        private static void TrackFile(HttpContext context)
        {
            var auth   = context.Request[FilesLinkUtility.AuthKey];
            var fileId = context.Request[FilesLinkUtility.FileId];

            Global.Logger.Debug("DocService track fileid: " + fileId);

            var callbackSpan   = TimeSpan.FromDays(128);
            var validateResult = EmailValidationKeyProvider.ValidateEmailKey(fileId, auth ?? "", callbackSpan);

            if (validateResult != EmailValidationKeyProvider.ValidationResult.Ok)
            {
                Global.Logger.ErrorFormat("DocService track auth error: {0}, {1}: {2}", validateResult.ToString(), FilesLinkUtility.AuthKey, auth);
                throw new HttpException((int)HttpStatusCode.Forbidden, FilesCommonResource.ErrorMassage_SecurityException);
            }

            JToken data;

            if (!string.IsNullOrEmpty(FileUtility.SignatureSecret))
            {
                var header = context.Request.Headers[FileUtility.SignatureHeader];
                if (string.IsNullOrEmpty(header) || !header.StartsWith("Bearer "))
                {
                    Global.Logger.Error("DocService track header is null");
                    throw new HttpException((int)HttpStatusCode.Forbidden, FilesCommonResource.ErrorMassage_SecurityException);
                }
                header = header.Substring("Bearer ".Length);

                try
                {
                    JsonWebToken.JsonSerializer = new DocumentService.JwtSerializer();
                    var stringPayload = JsonWebToken.Decode(header, FileUtility.SignatureSecret);

                    Global.Logger.Debug("DocService track payload: " + stringPayload);
                    var jsonPayload = JObject.Parse(stringPayload);
                    data = jsonPayload["payload"];
                }
                catch (SignatureVerificationException ex)
                {
                    Global.Logger.Error("DocService track header", ex);
                    throw new HttpException((int)HttpStatusCode.Forbidden, ex.Message);
                }
            }
            else
            {
                try
                {
                    string body;

                    using (var receiveStream = context.Request.InputStream)
                        using (var readStream = new StreamReader(receiveStream))
                        {
                            body = readStream.ReadToEnd();
                        }

                    Global.Logger.Debug("DocService track body: " + body);
                    if (string.IsNullOrEmpty(body))
                    {
                        throw new ArgumentException("DocService return null");
                    }

                    data = JToken.Parse(body);
                }
                catch (Exception e)
                {
                    Global.Logger.Error("DocService track error read body", e);
                    throw new HttpException((int)HttpStatusCode.BadRequest, e.Message);
                }
            }

            string error;

            try
            {
                if (data == null)
                {
                    throw new ArgumentException("DocService response is incorrect");
                }

                var fileData = data.ToObject <DocumentServiceTracker.TrackerData>();
                error = DocumentServiceTracker.ProcessData(fileId, fileData);
            }
            catch (Exception e)
            {
                Global.Logger.Error("DocService track:", e);
                throw new HttpException((int)HttpStatusCode.BadRequest, e.Message);
            }

            context.Response.Write(string.Format("{{\"error\":{0}}}", (error ?? "0")));
        }