public string Download(Caller caller, string company, string repository, string projectName, string versionName, string contentType)
        {
            var container = new Version { Company = company, Repository = repository, Project = projectName, Name = versionName };

            using (var session = backendFactory.Create(caller))
                return session.GetPackageLink(ref container, contentType);
        }
        public Version[] Index(Caller caller, string company, string repository)
        {
            var parent = new Repository { Company = company, Name = repository };

            using (var session = backendFactory.Create(caller))
            {
                return session.GetPackages(ref parent, GetPackageFormat());
            }
        }
        public static IManagementSession Create(this IManagementSessionFactory factory, string company, string name, string keyType, string keyValue)
        {
            var caller = new Caller
                             {
                                 Company = company,
                                 Name = name,
                                 KeyType = keyType,
                                 KeyValue = keyValue,
                             };

            return factory.Create(caller);
        }
        private Caller Authenticate(string company, string login, string key, bool require)
        {
            if (!string.IsNullOrEmpty(login) && !string.IsNullOrEmpty(key))
            {
                var caller = new Caller { Company = company, Name = login, KeyType = "VisualStudio", KeyValue = key };

                if (factory.Validate(caller) != null)
                    return caller;

                Response.StatusCode = 403;
                return null;
            }

            var auth = Request.Headers["Authorization"];

            if (auth != null)
            {
                var token = Encoding.ASCII.GetString(Convert.FromBase64String(auth.Split(' ')[1])).Split(':');
                var caller = new Caller { Company = company, Name = token[0], KeyType = "Password", KeyValue = token[1] };

                if (factory.Validate(caller) != null)
                    return caller;
            }

            if (!require)
            {
                var configuration = new AppSettingsConfiguration(company);

                return new Caller
                {
                    Company = company,
                    Name = configuration.PublicLogin,
                    KeyType = "API",
                    KeyValue = configuration.PublicPassword
                };
            }

            Response.StatusCode = 401;
            Response.AddHeader("WWW-Authenticate", string.Format("Basic realm=\"{0}\"", company));
            return null;
        }
        public void Upload(Caller caller, Stream stream, string company, string repository)
        {
            if (log.IsDebugEnabled)
                log.DebugFormat("Uploading");

            var path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            Directory.CreateDirectory(path);

            try
            {
                try
                {
                    SavePackage(stream, path);
                }
                catch (Exception exception)
                {
                    log.Error("Problem with saving package", exception);
                    Elmah.ErrorLog.GetDefault(HttpContext.Current).Log(new Elmah.Error(exception, HttpContext.Current));
                    throw new ClientException("Reading package failed", exception);
                }

                PackageProject package;
                IList<MetadataEntry> metadata;
                ILookup<ContentType, string> contents;

                try
                {
                    GetMetadata(path, repository, out package, out metadata, out contents);
                }
                catch (Exception exception)
                {
                    log.Error("Problem with getting metadata", exception);
                    Elmah.ErrorLog.GetDefault(HttpContext.Current).Log(new Elmah.Error(exception, HttpContext.Current));
                    throw new ClientException("Reading package metadata failed", exception);
                }

                try
                {
                    SynchronizePermissions(caller, company, package);
                }
                catch (Exception exception)
                {
                    log.Error("Problem with synchronizing permissions", exception);
                    Elmah.ErrorLog.GetDefault(HttpContext.Current).Log(new Elmah.Error(exception, HttpContext.Current));
                    throw new ClientException("Failed to synchronize permissions", exception);
                }

                try
                {
                    PrepareUpload(path, contents);
                }
                catch (Exception exception)
                {
                    log.Error("Problem with preparing package", exception);
                    Elmah.ErrorLog.GetDefault(HttpContext.Current).Log(new Elmah.Error(exception, HttpContext.Current));
                    throw new ClientException("Failed to modify package", exception);
                }

                try
                {
                    PerformUpload(caller, package, path);
                }
                catch (Exception exception)
                {
                    log.Error("Problem with uploading package", exception);
                    Elmah.ErrorLog.GetDefault(HttpContext.Current).Log(new Elmah.Error(exception, HttpContext.Current));
                    throw new ServerException("Package submission failed", exception);
                }
            }
            finally
            {
                Directory.Delete(path, true);
            }

            if (log.IsDebugEnabled)
                log.DebugFormat("Uploaded");
        }
        public void Restore(Caller caller, string company, string repository, string projectName, string versionName)
        {
            using (var session = backendFactory.Create(caller))
            {
                //var project = new Project { Company = company, Repository = repository, Name = projectName };
                //var versions = session.GetVersions(ref project);
                //var version = versions.SingleOrDefault(v => v.Name == versionName);

                //if (version == null)
                //    throw new ClientException("Specified version does not exist.", null);

                ////if (version.Hidden == false)
                ////    throw new ClientException("Version is not hidden.", null);

                //session.SetVersionHidden(ref version, false);
            }
        }
        private void PerformUpload(Caller caller, PackageProject packageProject, string path)
        {
            if (log.IsDebugEnabled)
                log.DebugFormat("Uploading package");

            var packagePath = GetFilePath(path);
            var symbolPackagePath = GetSymbolPackagePath(path);

            var package = File.Exists(packagePath) ? File.ReadAllBytes(packagePath) : null;
            var symbolPackage = File.Exists(symbolPackagePath) ? File.ReadAllBytes(symbolPackagePath) : null;

            using (var session = backendFactory.Create(caller))
            {
                var report = session.UploadPackage(packageProject, GetPackageFormat(), package, symbolPackage);

                if (report.Summary != "OK")
                {
                    var builder = new StringBuilder();
                    builder.AppendLine(report.Summary);
                    builder.AppendLine();

                    if (!string.IsNullOrEmpty(report.Exception))
                    {
                        builder.AppendLine("Exception:");
                        builder.AppendLine(report.Exception);
                        builder.AppendLine();
                    }

                    if (!string.IsNullOrEmpty(report.Exception))
                    {
                        builder.AppendLine("Log:");
                        builder.AppendLine(report.Log);
                        builder.AppendLine();
                    }

                    throw new Exception(builder.ToString());
                }
            }

            if (log.IsDebugEnabled)
                log.DebugFormat("Uploaded upload package");
        }
 protected abstract bool? GetProjectPermission(Caller caller, string companyName, PackageProject project);
        private void SynchronizePermissions(Caller caller, string company, PackageProject packageProject)
        {
            var permission = GetProjectPermission(caller, company, packageProject);

            if (permission.HasValue)
            {
                var configuration = configurationFactory.Create(company);

                if (string.IsNullOrEmpty(configuration.GatewayLogin) || string.IsNullOrEmpty(configuration.GatewayPassword))
                    throw new Exception("Missing gateway configuration");

                using (var session = backendFactory.Create(new Caller { Company = company, Name = configuration.GatewayLogin, KeyType = "API", KeyValue = configuration.GatewayPassword }))
                {
                    var project = new Project { Company = company, Repository = packageProject.Repository, Name = packageProject.Name };

                    if (permission.Value)
                    {
                        try
                        {
                            session.CreateProject(project);
                        }
                        catch (Exception)
                        {
                            //ignore if exists
                        }
                    }

                    try
                    {
                        session.SetProjectPermissions(new User { Company = caller.Company, Name = caller.Name }, project, new Permission { Grant = false, Read = false, Write = permission.Value });
                    }
                    catch (Exception)
                    {
                        //ignore if not exists
                    }

                    if (!permission.Value)
                        throw new Exception("External permission source denied publish access");
                }
            }
        }
 protected override bool? GetProjectPermission(Caller caller, string companyName, PackageProject project)
 {
     return null;
 }
        protected override bool? GetProjectPermission(Caller caller, string companyName, PackageProject project)
        {
            var configuration = configurationFactory.Create(companyName, project.Repository);

            if (string.IsNullOrEmpty(configuration.NuGetService))
                return null;

            return new NuGetService(configuration.NuGetService).CheckPermission(caller.KeyValue, project.Name);
        }
        private void PerformUpload(Caller caller, PackageProject packageProject, string path)
        {
            if (log.IsDebugEnabled)
                log.DebugFormat("Uploading package");

            var packagePath = GetFilePath(path);
            var symbolPackagePath = GetSymbolPackagePath(path);

            var package = File.Exists(packagePath) ? File.ReadAllBytes(packagePath) : null;
            var symbolPackage = File.Exists(symbolPackagePath) ? File.ReadAllBytes(symbolPackagePath) : null;

            using (var session = backendFactory.Create(caller))
            {
                var report = session.UploadPackage(packageProject, GetPackageFormat(), package, symbolPackage);

                if (report.Summary != "OK")
                    throw new Exception(report.Summary);
            }

            if (log.IsDebugEnabled)
                log.DebugFormat("Uploaded upload package");
        }
 public WebServiceManagementSession(IWebServiceManagementConfiguration configuration, Caller caller)
 {
     service = new ConfigurableWebService(configuration);
     this.caller = caller;
     user = service.UserValidate(caller);
 }
        private void ApplicationOnPreRequestHandlerExecute(object sender, EventArgs eventArgs)
        {
            var application = (HttpApplication) sender;
            var wrapper = new HttpContextWrapper(application.Context);

            if (wrapper.Request.RequestContext.RouteData.RouteHandler is DynamicServiceRoute 
                /* && !string.IsNullOrEmpty((string) wrapper.Request.RequestContext.RouteData.Values["servicePath"]) */)
            {
                string company = (string)wrapper.Request.RequestContext.RouteData.Values["company"];
                string login = (string)wrapper.Request.RequestContext.RouteData.Values["login"];
                string key = (string)wrapper.Request.RequestContext.RouteData.Values["key"];
                string repository = (string)wrapper.Request.RequestContext.RouteData.Values["repository"];
                application.Context.Items.Add("Repository", new Repository {Company = company, Name = repository});
                var factory = ServiceLocator.Resolve<IGatewayBackendFactory<IPackageBackend>>();
                var manager = ServiceLocator.Resolve<INuGetGatewayManager>();
                var configurationFactory = ServiceLocator.Resolve<IGatewayConfigurationFactory>();

                if (!string.IsNullOrEmpty(login) && !string.IsNullOrEmpty(key))
                {
                    var caller = new Caller { Company = company, Name = login, KeyType = "VisualStudio", KeyValue = key };

                    if (factory.Validate(caller) != null)
                    {
                        application.Context.Items.Add("Caller", caller);
                        return;
                    }                        

                    application.Response.StatusCode = 403;
                    application.CompleteRequest();
                    return;
                }


                var auth = wrapper.Request.Headers["Authorization"];
                if (auth != null)
                {
                    var token = Encoding.ASCII.GetString(Convert.FromBase64String(auth.Split(' ')[1])).Split(':');
                    var caller = new Caller { Company = company, Name = token[0], KeyType = "Password", KeyValue = token[1] };

                    if (factory.Validate(caller) != null)
                    {
                        application.Context.Items.Add("Caller", caller);
                        return;
                    }                        
                }

                if (!manager.AuthenticateDownload(company, repository))
                {
                    var configuration = configurationFactory.Create(company);

                    var caller =  new Caller { Company = company, Name = configuration.PublicLogin, KeyType = "API", KeyValue = configuration.PublicPassword };
                    application.Context.Items.Add("Caller", caller);
                    return;
                }

                application.Response.StatusCode = 401;
                application.Response.AddHeader("WWW-Authenticate", string.Format("Basic realm=\"{0}\"", company));
                application.CompleteRequest();

            }
        }