2016-07-04 2 views
1

Я использую Asp.NET MVC 5 для создания веб-приложения. Я загрузил Ckeditor и CKfinder Connector для ASP.NET. Я смог следовать инструкциям и интегрировать интеграцию Ckeditor и Ckfinder.CKfinder-динамическая папка пользователя -Asp.net MVC 5

Я пытаюсь выяснить, как я могу иметь динамический каталог папок в CkFinder для входа в систему пользователя. В соответствии с инструкциями, приведенными в http://docs.cksource.com/ckfinder3-net/howto.html#howto_private_folders, он сообщает вам об этом в connectorBuilder .SetRequestConfiguration. Проблема в том, что ConnectorBuilder настраивается при запуске, а пользователь регистрируется после этого?

Вот код, который я есть сейчас, где все работает, кроме икон

using DearColleagueV2.Models; 

[assembly: Microsoft.Owin.OwinStartup(typeof(DearColleagueV2.Startup))] 

namespace DearColleagueV2 
{ 
    using System.Configuration; 

    using CKSource.CKFinder.Connector.Config; 
    using CKSource.CKFinder.Connector.Core.Builders; 
    using CKSource.CKFinder.Connector.Core.Logs; 
    using CKSource.CKFinder.Connector.Host.Owin; 
    using CKSource.CKFinder.Connector.Logs.NLog; 
    using CKSource.CKFinder.Connector.KeyValue.EntityFramework; 
    using CKSource.FileSystem.Dropbox; 
    using CKSource.FileSystem.Local; 

    using System; 
    using Microsoft.AspNet.Identity; 
    using Microsoft.AspNet.Identity.Owin; 
    using Microsoft.Owin; 
    using Microsoft.Owin.Security.Cookies; 

    using Owin; 
    using Microsoft.Owin.Security; 
    using CKSource.CKFinder.Connector.Core.Acl; 
    using System.Collections.Generic; 
    using CKSource.CKFinder.Connector.Core.Authentication; 
    using System.Threading.Tasks; 
    using CKSource.CKFinder.Connector.Core; 
    using System.Threading; 
    using System.Security.Cryptography; 
    using System.Text; 

    public partial class Startup 
    { 
     public void Configuration(IAppBuilder builder) 
     { 
      LoggerManager.LoggerAdapterFactory = new NLogLoggerAdapterFactory(); 
      ConfigureAuthForIdentity(builder); 

      RegisterFileSystems(); 

      var connectorBuilder = ConfigureConnector(); 
      var connector = connectorBuilder.Build(new OwinConnectorFactory()); 
      builder.Map("/CKFinder/connector", builder1 => builder1.UseConnector(connector)); 
     } 

     private void ConfigureAuthForIdentity(IAppBuilder app) 
     { 
      // Configure the db context, user manager and signin manager to use a single instance per request 
      app.CreatePerOwinContext(ApplicationDbContext.Create); 
      app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); 
      app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create); 

      // Enable the application to use a cookie to store information for the signed in user 
      // and to use a cookie to temporarily store information about a user logging in with a third party login provider 
      // Configure the sign in cookie 
      app.UseCookieAuthentication(new CookieAuthenticationOptions 
      { 
       AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, 
       LoginPath = new PathString("/Account/Login"), 
       Provider = new CookieAuthenticationProvider 
       { 
        // Enables the application to validate the security stamp when the user logs in. 
        // This is a security feature which is used when you change a password or add an external login to your account. 
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
         validateInterval: TimeSpan.FromMinutes(30), 
         regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) 
       } 
      }); 
      app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); 

      // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process. 
      app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5)); 

      // Enables the application to remember the second login verification factor such as phone or email. 
      // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from. 
      // This is similar to the RememberMe option when you log in. 
      app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie); 


     } 

     public ConnectorBuilder ConfigureConnector() 
     { 
      var connectorBuilder = new ConnectorBuilder(); 
      connectorBuilder 
       .SetRequestConfiguration(
        (request, config) => 
        { 

         //config.AddProxyBackend("local", new LocalStorage(@"MyFiles")); 
         var userName = request.Principal?.Identity?.Name; 
         if (userName != null) 
         { 
          var sha = new SHA1CryptoServiceProvider(); 
          var hash = sha.ComputeHash(Encoding.UTF8.GetBytes(userName)); 
          var folderName = BitConverter.ToString(hash).Replace("-", string.Empty); 
          config.AddProxyBackend("local", new LocalStorage(@"c:\files")); 
          config.AddResourceType("private", resourceBuilder => resourceBuilder.SetBackend("local", folderName)); 
          config.SetThumbnailBackend("local", "thumbs");        
          config.AddAclRule(new AclRule(
        new StringMatcher("*"), new StringMatcher("/"), new StringMatcher("*"), 
        new Dictionary<Permission, PermissionType> 
        { 
         { Permission.FolderView, PermissionType.Allow }, 
         { Permission.FolderCreate, PermissionType.Allow }, 
         { Permission.FolderRename, PermissionType.Allow }, 
         { Permission.FolderDelete, PermissionType.Allow }, 

         { Permission.FileView, PermissionType.Allow }, 
         { Permission.FileCreate, PermissionType.Allow }, 
         { Permission.FileRename, PermissionType.Allow }, 
         { Permission.FileDelete, PermissionType.Allow }, 


         { Permission.ImageResize, PermissionType.Allow }, 
         { Permission.ImageResizeCustom, PermissionType.Allow } 
        })); 
         } 
        }) 
       .SetAuthenticator(new MyAuthenticator()); 

      return connectorBuilder; 
     } 

     private static void RegisterFileSystems() 
     { 
      FileSystemFactory.RegisterFileSystem<LocalStorage>(); 
      FileSystemFactory.RegisterFileSystem<DropboxStorage>(); 
     } 

    } 

    public class MyAuthenticator : IAuthenticator 
    { 
     public Task<CKSource.CKFinder.Connector.Core.Authentication.IUser> AuthenticateAsync(ICommandRequest commandRequest, CancellationToken cancellationToken) 
     { 
      var user = new User(true, null); 
      return Task.FromResult((CKSource.CKFinder.Connector.Core.Authentication.IUser)user); 
     } 
    } 
} 
+0

Не знаете, какие изменения вы внесли, кроме форматирования? – GPS

ответ

2

SetRequestConfiguration метод ConnectorBuilder класса принимает меры, которая будет вызываться для каждого запроса.

Код из приведенного вами примера, хотя он определен во время запуска, будет выполнен для каждого запроса.

Кроме того, вы должны быть уверены, что пользователь уже зарегистрировался, когда пытается использовать CKFinder. Например:

public class Startup 
{ 
    public void Configuration(IAppBuilder app) 
    { 
     var connectorFactory = new OwinConnectorFactory(); 

     var connectorBuilder = ... 

     var connector = connectorBuilder.Build(connectorFactory); 

     app.UseCookieAuthentication(
      /* 
      * Your CookieAuthenticationOptions that will redirect anonymous 
      * users to the login page 
      */ 
      ); 
     app.UseConnector(connector); 
    } 
} 

О недостатках эскизов следует добавить хотя бы один разрешенный размер эскизов. Просто добавьте что-то вроде config.SetThumbnailSizes(new SizeAndQuality(100, 100, new ImageQuality(80))); в действие, выполненное в SetRequestConfiguration.

+0

Спасибо за руководство! Я смог создать отдельную папку для каждого пользователя. Теперь я не могу видеть миниатюры загруженных изображений. Вот код, который у меня есть – GPS

+0

Не могли бы вы обновить свой оригинальный вопрос, чтобы включить код, который у вас есть прямо сейчас? – kfazi

+0

обновленный исходный вопрос. Благодаря! – GPS

Смежные вопросы