Merge branch 'dev-v8' into temp-U4-11127
# Conflicts: # src/Umbraco.Web.UI.Client/src/views/dashboard/dashboard.tabs.controller.js
This commit is contained in:
@@ -40,6 +40,7 @@
|
||||
<dependency id="Markdown" version="[2.2.1, 3.0.0)" />
|
||||
<dependency id="log4net" version="[2.0.8, 3.0.0)" />
|
||||
<dependency id="System.Threading.Tasks.Dataflow" version="[4.8.0, 5.0.0)" />
|
||||
<dependency id="System.ValueTuple" version="[4.4.0, 5.0.0)" />
|
||||
</dependencies>
|
||||
</metadata>
|
||||
<files>
|
||||
|
||||
+50
-51
@@ -25,7 +25,7 @@
|
||||
# create and boot the buildsystem
|
||||
$ubuild = &"$PSScriptRoot\build-bootstrap.ps1"
|
||||
if (-not $?) { return }
|
||||
$ubuild.Boot($PSScriptRoot,
|
||||
$ubuild.Boot($PSScriptRoot,
|
||||
@{ Local = $local; },
|
||||
@{ Continue = $continue })
|
||||
if ($ubuild.OnError()) { return }
|
||||
@@ -36,21 +36,21 @@
|
||||
# ################################################################
|
||||
# TASKS
|
||||
# ################################################################
|
||||
|
||||
|
||||
$ubuild.DefineMethod("SetMoreUmbracoVersion",
|
||||
{
|
||||
param ( $semver )
|
||||
|
||||
$release = "" + $semver.Major + "." + $semver.Minor + "." + $semver.Patch
|
||||
|
||||
|
||||
Write-Host "Update UmbracoVersion.cs"
|
||||
$this.ReplaceFileText("$($this.SolutionRoot)\src\Umbraco.Core\Configuration\UmbracoVersion.cs", `
|
||||
"(\d+)\.(\d+)\.(\d+)(.(\d+))?", `
|
||||
"$release")
|
||||
"$release")
|
||||
$this.ReplaceFileText("$($this.SolutionRoot)\src\Umbraco.Core\Configuration\UmbracoVersion.cs", `
|
||||
"CurrentComment => `"(.+)`"", `
|
||||
"CurrentComment => `"$($semver.PreRelease)`"")
|
||||
|
||||
|
||||
Write-Host "Update IIS Express port in csproj"
|
||||
$updater = New-Object "Umbraco.Build.ExpressPortUpdater"
|
||||
$csproj = "$($this.SolutionRoot)\src\Umbraco.Web.UI\Umbraco.Web.UI.csproj"
|
||||
@@ -61,7 +61,7 @@
|
||||
{
|
||||
$global:node_path = $env:path
|
||||
$nodePath = $this.BuildEnv.NodePath
|
||||
$gitExe = (Get-Command git).Source
|
||||
$gitExe = (Get-Command git).Source
|
||||
$gitPath = [System.IO.Path]::GetDirectoryName($gitExe)
|
||||
$env:path = "$nodePath;$gitPath"
|
||||
|
||||
@@ -73,7 +73,7 @@
|
||||
$ubuild.DefineMethod("RestoreNode",
|
||||
{
|
||||
$env:path = $node_path
|
||||
|
||||
|
||||
$this.SetEnvVar("NODEPATH", $node_nodepath)
|
||||
$this.SetEnvVar("NPM_CONFIG_CACHE", $node_npmcache)
|
||||
$this.SetEnvVar("NPM_CONFIG_PREFIX", $node_npmprefix)
|
||||
@@ -83,9 +83,9 @@
|
||||
{
|
||||
$src = "$($this.SolutionRoot)\src"
|
||||
$log = "$($this.BuildTemp)\belle.log"
|
||||
|
||||
|
||||
Write-Host "Compile Belle"
|
||||
Write-Host "Logging to $log"
|
||||
Write-Host "Logging to $log"
|
||||
|
||||
# get a temp clean node env (will restore)
|
||||
$this.SandboxNode()
|
||||
@@ -96,7 +96,7 @@
|
||||
|
||||
Push-Location "$($this.SolutionRoot)\src\Umbraco.Web.UI.Client"
|
||||
Write-Output "" > $log
|
||||
|
||||
|
||||
Write-Output "### node version is:" > $log
|
||||
&node -v >> $log 2>&1
|
||||
if (-not $?) { throw "Failed to report node version." }
|
||||
@@ -106,7 +106,7 @@
|
||||
if (-not $?) { throw "Failed to report npm version." }
|
||||
|
||||
Write-Output "### clean npm cache" >> $log 2>&1
|
||||
&npm cache clean >> $log 2>&1
|
||||
&npm cache clean --force >> $log 2>&1
|
||||
$error.Clear() # that one can fail 'cos security bug - ignore
|
||||
|
||||
Write-Output "### npm install" >> $log 2>&1
|
||||
@@ -116,12 +116,12 @@
|
||||
Write-Output "### install bower" >> $log 2>&1
|
||||
&npm install -g bower >> $log 2>&1
|
||||
$error.Clear() # that one fails 'cos bower is deprecated - ignore
|
||||
|
||||
|
||||
Write-Output "### install gulp" >> $log 2>&1
|
||||
&npm install -g gulp >> $log 2>&1
|
||||
$error.Clear() # that one fails 'cos deprecated stuff - ignore
|
||||
|
||||
Write-Output "### nstall gulp-cli" >> $log 2>&1
|
||||
Write-Output "### install gulp-cli" >> $log 2>&1
|
||||
&npm install -g gulp-cli --quiet >> $log 2>&1
|
||||
if (-not $?) { throw "Failed to install gulp-cli" } # that one is expected to work
|
||||
|
||||
@@ -130,13 +130,13 @@
|
||||
if (-not $?) { throw "Failed to build" } # that one is expected to work
|
||||
|
||||
Pop-Location
|
||||
|
||||
|
||||
# fixme - should we filter the log to find errors?
|
||||
#get-content .\build.tmp\belle.log | %{ if ($_ -match "build") { write $_}}
|
||||
|
||||
|
||||
# restore
|
||||
$this.RestoreNode()
|
||||
|
||||
|
||||
# setting node_modules folder to hidden
|
||||
# used to prevent VS13 from crashing on it while loading the websites project
|
||||
# also makes sure aspnet compiler does not try to handle rogue files and chokes
|
||||
@@ -154,15 +154,15 @@
|
||||
$src = "$($this.SolutionRoot)\src"
|
||||
$log = "$($this.BuildTemp)\msbuild.umbraco.log"
|
||||
$log7 = "$($this.BuildTemp)\msbuild.compat7.log"
|
||||
|
||||
|
||||
if ($this.BuildEnv.VisualStudio -eq $null)
|
||||
{
|
||||
throw "Build environment does not provide VisualStudio."
|
||||
}
|
||||
|
||||
|
||||
Write-Host "Compile Umbraco"
|
||||
Write-Host "Logging to $log"
|
||||
|
||||
|
||||
# beware of the weird double \\ at the end of paths
|
||||
# see http://edgylogic.com/blog/powershell-and-external-commands-done-right/
|
||||
&$this.BuildEnv.VisualStudio.MsBuild "$src\Umbraco.Web.UI\Umbraco.Web.UI.csproj" `
|
||||
@@ -180,7 +180,7 @@
|
||||
> $log
|
||||
|
||||
if (-not $?) { throw "Failed to compile Umbraco.Web.UI." }
|
||||
|
||||
|
||||
Write-Host "Logging to $log7"
|
||||
|
||||
&$this.BuildEnv.VisualStudio.MsBuild "$src\Umbraco.Compat7\Umbraco.Compat7.csproj" `
|
||||
@@ -198,19 +198,19 @@
|
||||
> $log7
|
||||
|
||||
if (-not $?) { throw "Failed to compile Umbraco.Compat7." }
|
||||
|
||||
|
||||
# /p:UmbracoBuild tells the csproj that we are building from PS, not VS
|
||||
})
|
||||
|
||||
$ubuild.DefineMethod("PrepareTests",
|
||||
{
|
||||
Write-Host "Prepare Tests"
|
||||
|
||||
|
||||
# fixme - idea is to avoid rebuilding everything for tests
|
||||
# but because of our weird assembly versioning (with .* stuff)
|
||||
# everything gets rebuilt all the time...
|
||||
#Copy-Files "$tmp\bin" "." "$tmp\tests"
|
||||
|
||||
|
||||
# data
|
||||
Write-Host "Copy data files"
|
||||
if (-not (Test-Path -Path "$($this.BuildTemp)\tests\Packaging" ))
|
||||
@@ -219,8 +219,8 @@
|
||||
mkdir "$($this.BuildTemp)\tests\Packaging" > $null
|
||||
}
|
||||
$this.CopyFiles("$($this.SolutionRoot)\src\Umbraco.Tests\Packaging\Packages", "*", "$($this.BuildTemp)\tests\Packaging\Packages")
|
||||
|
||||
# required for package install tests
|
||||
|
||||
# required for package install tests
|
||||
if (-not (Test-Path -Path "$($this.BuildTemp)\tests\bin" ))
|
||||
{
|
||||
Write-Host "Create bin directory"
|
||||
@@ -237,10 +237,10 @@
|
||||
{
|
||||
throw "Build environment does not provide VisualStudio."
|
||||
}
|
||||
|
||||
|
||||
Write-Host "Compile Tests"
|
||||
Write-Host "Logging to $log"
|
||||
|
||||
|
||||
# beware of the weird double \\ at the end of paths
|
||||
# see http://edgylogic.com/blog/powershell-and-external-commands-done-right/
|
||||
&$this.BuildEnv.VisualStudio.MsBuild "$($this.SolutionRoot)\src\Umbraco.Tests\Umbraco.Tests.csproj" `
|
||||
@@ -264,26 +264,26 @@
|
||||
|
||||
$ubuild.DefineMethod("PreparePackages",
|
||||
{
|
||||
Write-Host "Prepare Packages"
|
||||
|
||||
Write-Host "Prepare Packages"
|
||||
|
||||
$src = "$($this.SolutionRoot)\src"
|
||||
$tmp = "$($this.BuildTemp)"
|
||||
$out = "$($this.BuildOutput)"
|
||||
|
||||
|
||||
$buildConfiguration = "Release"
|
||||
|
||||
|
||||
# restore web.config
|
||||
$this.TempRestoreFile("$src\Umbraco.Web.UI\web.config")
|
||||
|
||||
|
||||
# cleanup build
|
||||
Write-Host "Clean build"
|
||||
$this.RemoveFile("$tmp\bin\*.dll.config")
|
||||
$this.RemoveFile("$tmp\WebApp\bin\*.dll.config")
|
||||
|
||||
|
||||
# cleanup presentation
|
||||
Write-Host "Cleanup presentation"
|
||||
$this.RemoveDirectory("$tmp\WebApp\umbraco.presentation")
|
||||
|
||||
|
||||
# create directories
|
||||
Write-Host "Create directories"
|
||||
mkdir "$tmp\Configs" > $null
|
||||
@@ -291,11 +291,11 @@
|
||||
mkdir "$tmp\WebApp\App_Data" > $null
|
||||
#mkdir "$tmp\WebApp\Media" > $null
|
||||
#mkdir "$tmp\WebApp\Views" > $null
|
||||
|
||||
|
||||
# copy various files
|
||||
Write-Host "Copy xml documentation"
|
||||
Copy-Item -force "$tmp\bin\*.xml" "$tmp\WebApp\bin"
|
||||
|
||||
|
||||
Write-Host "Copy transformed configs and langs"
|
||||
# note: exclude imageprocessor/*.config as imageprocessor pkg installs them
|
||||
$this.CopyFiles("$tmp\WebApp\config", "*.config", "$tmp\Configs", `
|
||||
@@ -303,10 +303,10 @@
|
||||
$this.CopyFiles("$tmp\WebApp\config", "*.js", "$tmp\Configs")
|
||||
$this.CopyFiles("$tmp\WebApp\config\lang", "*.xml", "$tmp\Configs\Lang")
|
||||
$this.CopyFile("$tmp\WebApp\web.config", "$tmp\Configs\web.config.transform")
|
||||
|
||||
|
||||
Write-Host "Copy transformed web.config"
|
||||
$this.CopyFile("$src\Umbraco.Web.UI\web.$buildConfiguration.Config.transformed", "$tmp\WebApp\web.config")
|
||||
|
||||
|
||||
# offset the modified timestamps on all umbraco dlls, as WebResources
|
||||
# break if date is in the future, which, due to timezone offsets can happen.
|
||||
Write-Host "Offset dlls timestamps"
|
||||
@@ -314,49 +314,48 @@
|
||||
$_.CreationTime = $_.CreationTime.AddHours(-11)
|
||||
$_.LastWriteTime = $_.LastWriteTime.AddHours(-11)
|
||||
}
|
||||
|
||||
|
||||
# copy libs
|
||||
Write-Host "Copy SqlCE libraries"
|
||||
$this.CopyFiles("$src\packages\SqlServerCE.4.0.0.1", "*.*", "$tmp\bin", `
|
||||
{ -not $_.Extension.StartsWith(".nu") -and -not $_.RelativeName.StartsWith("lib\") })
|
||||
$this.CopyFiles("$src\packages\SqlServerCE.4.0.0.1", "*.*", "$tmp\WebApp\bin", `
|
||||
{ -not $_.Extension.StartsWith(".nu") -and -not $_.RelativeName.StartsWith("lib\") })
|
||||
|
||||
|
||||
# copy Belle
|
||||
Write-Host "Copy Belle"
|
||||
$this.CopyFiles("$src\Umbraco.Web.UI\umbraco\assets", "*", "$tmp\WebApp\umbraco\assets")
|
||||
$this.CopyFiles("$src\Umbraco.Web.UI\umbraco\js", "*", "$tmp\WebApp\umbraco\js")
|
||||
$this.CopyFiles("$src\Umbraco.Web.UI\umbraco\lib", "*", "$tmp\WebApp\umbraco\lib")
|
||||
$this.CopyFiles("$src\Umbraco.Web.UI\umbraco\views", "*", "$tmp\WebApp\umbraco\views")
|
||||
$this.CopyFiles("$src\Umbraco.Web.UI\umbraco\preview", "*", "$tmp\WebApp\umbraco\preview")
|
||||
})
|
||||
|
||||
$ubuild.DefineMethod("PackageZip",
|
||||
{
|
||||
Write-Host "Create Zip packages"
|
||||
Write-Host "Create Zip packages"
|
||||
|
||||
$src = "$($this.SolutionRoot)\src"
|
||||
$tmp = $this.BuildTemp
|
||||
$out = $this.BuildOutput
|
||||
|
||||
Write-Host "Zip all binaries"
|
||||
|
||||
Write-Host "Zip all binaries"
|
||||
&$this.BuildEnv.Zip a -r "$out\UmbracoCms.AllBinaries.$($this.Version.Semver).zip" `
|
||||
"$tmp\bin\*" `
|
||||
"-x!dotless.Core.*" "-x!Umbraco.Compat7.*" `
|
||||
> $null
|
||||
if (-not $?) { throw "Failed to zip UmbracoCms.AllBinaries." }
|
||||
if (-not $?) { throw "Failed to zip UmbracoCms.AllBinaries." }
|
||||
|
||||
Write-Host "Zip cms"
|
||||
Write-Host "Zip cms"
|
||||
&$this.BuildEnv.Zip a -r "$out\UmbracoCms.$($this.Version.Semver).zip" `
|
||||
"$tmp\WebApp\*" `
|
||||
"-x!dotless.Core.*" "-x!Content_Types.xml" "-x!*.pdb" "-x!Umbraco.Compat7.*" `
|
||||
> $null
|
||||
if (-not $?) { throw "Failed to zip UmbracoCms." }
|
||||
if (-not $?) { throw "Failed to zip UmbracoCms." }
|
||||
})
|
||||
|
||||
$ubuild.DefineMethod("PrepareBuild",
|
||||
{
|
||||
Write-Host "Clear folders and files"
|
||||
Write-Host "Clear folders and files"
|
||||
$this.RemoveDirectory("$($this.SolutionRoot)\src\Umbraco.Web.UI.Client\bower_components")
|
||||
|
||||
$this.TempStoreFile("$($this.SolutionRoot)\src\Umbraco.Web.UI\web.config")
|
||||
@@ -381,7 +380,7 @@
|
||||
Write-Host "Restore NuGet"
|
||||
Write-Host "Logging to $($this.BuildTemp)\nuget.restore.log"
|
||||
&$this.BuildEnv.NuGet restore "$($this.SolutionRoot)\src\Umbraco.sln" -ConfigFile $this.BuildEnv.NuGetConfig > "$($this.BuildTemp)\nuget.restore.log"
|
||||
if (-not $?) { throw "Failed to restore NuGet packages." }
|
||||
if (-not $?) { throw "Failed to restore NuGet packages." }
|
||||
})
|
||||
|
||||
$ubuild.DefineMethod("PackageNuGet",
|
||||
@@ -473,9 +472,9 @@
|
||||
$ubuild.ReleaseBranches = @( "master" )
|
||||
|
||||
# run
|
||||
if (-not $get)
|
||||
if (-not $get)
|
||||
{
|
||||
$ubuild.Build()
|
||||
$ubuild.Build()
|
||||
if ($ubuild.OnError()) { return }
|
||||
}
|
||||
Write-Host "Done"
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="15.0">
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<PropertyGroup>
|
||||
<TargetFrameworkVersion>v4.7</TargetFrameworkVersion>
|
||||
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
|
||||
@@ -27,6 +28,7 @@
|
||||
<DefineConstants>TRACE;COMPAT7</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
<DocumentationFile>bin\Release\Umbraco.Compat7.xml</DocumentationFile>
|
||||
<LangVersion>latest</LangVersion>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
@@ -101,8 +103,8 @@
|
||||
<ItemGroup>
|
||||
<Folder Include="Core\Persistence\" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<Target Name="AfterBuild" Condition="'$(BuildingInsideVisualStudio)' == 'true' AND $([System.Text.RegularExpressions.Regex]::IsMatch($(DefineConstants), '^(.*;)*COMPAT7(;.*)*$'))">
|
||||
<Copy SourceFiles="$(ProjectDir)bin\$(Configuration)\Umbraco.Compat7.dll" DestinationFolder="$(ProjectDir)..\Umbraco.Web.UI\bin" OverwriteReadOnlyFiles="true" SkipUnchangedFiles="false" />
|
||||
</Target>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
</Project>
|
||||
@@ -15,6 +15,7 @@ namespace Umbraco.Core.Composing.CompositionRoots
|
||||
container.Register(factory => factory.GetInstance<IUmbracoSettingsSection>().Content);
|
||||
container.Register(factory => factory.GetInstance<IUmbracoSettingsSection>().Templates);
|
||||
container.Register(factory => factory.GetInstance<IUmbracoSettingsSection>().RequestHandler);
|
||||
container.Register(factory => UmbracoConfig.For.GlobalSettings());
|
||||
|
||||
// fixme - other sections we need to add?
|
||||
}
|
||||
|
||||
@@ -29,6 +29,7 @@ namespace Umbraco.Core.Composing
|
||||
private const string CacheKey = "umbraco-types.list";
|
||||
|
||||
private readonly IRuntimeCacheProvider _runtimeCache;
|
||||
private readonly IGlobalSettings _globalSettings;
|
||||
private readonly ProfilingLogger _logger;
|
||||
|
||||
private readonly object _typesLock = new object();
|
||||
@@ -45,11 +46,13 @@ namespace Umbraco.Core.Composing
|
||||
/// Initializes a new instance of the <see cref="TypeLoader"/> class.
|
||||
/// </summary>
|
||||
/// <param name="runtimeCache">The application runtime cache.</param>
|
||||
/// <param name="globalSettings"></param>
|
||||
/// <param name="logger">A profiling logger.</param>
|
||||
/// <param name="detectChanges">Whether to detect changes using hashes.</param>
|
||||
internal TypeLoader(IRuntimeCacheProvider runtimeCache, ProfilingLogger logger, bool detectChanges = true)
|
||||
internal TypeLoader(IRuntimeCacheProvider runtimeCache, IGlobalSettings globalSettings, ProfilingLogger logger, bool detectChanges = true)
|
||||
{
|
||||
_runtimeCache = runtimeCache ?? throw new ArgumentNullException(nameof(runtimeCache));
|
||||
_globalSettings = globalSettings ?? throw new ArgumentNullException(nameof(globalSettings));
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
|
||||
if (detectChanges)
|
||||
@@ -354,17 +357,17 @@ namespace Umbraco.Core.Composing
|
||||
}
|
||||
|
||||
// internal for tests
|
||||
internal static string GetTypesListFilePath() => GetFileBasePath() + ".list";
|
||||
internal string GetTypesListFilePath() => GetFileBasePath() + ".list";
|
||||
|
||||
private static string GetTypesHashFilePath() => GetFileBasePath() + ".hash";
|
||||
private string GetTypesHashFilePath() => GetFileBasePath() + ".hash";
|
||||
|
||||
private static string GetFileBasePath()
|
||||
private string GetFileBasePath()
|
||||
{
|
||||
var localTempStorage = GlobalSettings.LocalTempStorageLocation;
|
||||
var localTempStorage = _globalSettings.LocalTempStorageLocation;
|
||||
if (_localTempStorage != localTempStorage)
|
||||
{
|
||||
string path;
|
||||
switch (GlobalSettings.LocalTempStorageLocation)
|
||||
switch (_globalSettings.LocalTempStorageLocation)
|
||||
{
|
||||
case LocalTempStorage.AspNetTemp:
|
||||
path = Path.Combine(HttpRuntime.CodegenDir, "UmbracoData", "umbraco-types");
|
||||
@@ -398,38 +401,38 @@ namespace Umbraco.Core.Composing
|
||||
return _fileBasePath;
|
||||
}
|
||||
|
||||
private static string GetFilePath(string extension)
|
||||
{
|
||||
string path;
|
||||
switch (GlobalSettings.LocalTempStorageLocation)
|
||||
{
|
||||
case LocalTempStorage.AspNetTemp:
|
||||
path = Path.Combine(HttpRuntime.CodegenDir, "UmbracoData", "umbraco-types." + extension);
|
||||
break;
|
||||
case LocalTempStorage.EnvironmentTemp:
|
||||
// include the appdomain hash is just a safety check, for example if a website is moved from worker A to worker B and then back
|
||||
// to worker A again, in theory the %temp% folder should already be empty but we really want to make sure that its not
|
||||
// utilizing an old path - assuming we cannot have SHA1 collisions on AppDomainAppId
|
||||
var appDomainHash = HttpRuntime.AppDomainAppId.ToSHA1();
|
||||
var cachePath = Path.Combine(Environment.ExpandEnvironmentVariables("%temp%"), "UmbracoData", appDomainHash);
|
||||
path = Path.Combine(cachePath, "umbraco-types." + extension);
|
||||
break;
|
||||
case LocalTempStorage.Default:
|
||||
default:
|
||||
var tempFolder = IOHelper.MapPath("~/App_Data/TEMP/TypesCache");
|
||||
path = Path.Combine(tempFolder, "umbraco-types." + NetworkHelper.FileSafeMachineName + "." + extension);
|
||||
break;
|
||||
}
|
||||
//private string GetFilePath(string extension)
|
||||
//{
|
||||
// string path;
|
||||
// switch (_globalSettings.LocalTempStorageLocation)
|
||||
// {
|
||||
// case LocalTempStorage.AspNetTemp:
|
||||
// path = Path.Combine(HttpRuntime.CodegenDir, "UmbracoData", "umbraco-types." + extension);
|
||||
// break;
|
||||
// case LocalTempStorage.EnvironmentTemp:
|
||||
// // include the appdomain hash is just a safety check, for example if a website is moved from worker A to worker B and then back
|
||||
// // to worker A again, in theory the %temp% folder should already be empty but we really want to make sure that its not
|
||||
// // utilizing an old path - assuming we cannot have SHA1 collisions on AppDomainAppId
|
||||
// var appDomainHash = HttpRuntime.AppDomainAppId.ToSHA1();
|
||||
// var cachePath = Path.Combine(Environment.ExpandEnvironmentVariables("%temp%"), "UmbracoData", appDomainHash);
|
||||
// path = Path.Combine(cachePath, "umbraco-types." + extension);
|
||||
// break;
|
||||
// case LocalTempStorage.Default:
|
||||
// default:
|
||||
// var tempFolder = IOHelper.MapPath("~/App_Data/TEMP/TypesCache");
|
||||
// path = Path.Combine(tempFolder, "umbraco-types." + NetworkHelper.FileSafeMachineName + "." + extension);
|
||||
// break;
|
||||
// }
|
||||
|
||||
// ensure that the folder exists
|
||||
var directory = Path.GetDirectoryName(path);
|
||||
if (directory == null)
|
||||
throw new InvalidOperationException($"Could not determine folder for file \"{path}\".");
|
||||
if (Directory.Exists(directory) == false)
|
||||
Directory.CreateDirectory(directory);
|
||||
// // ensure that the folder exists
|
||||
// var directory = Path.GetDirectoryName(path);
|
||||
// if (directory == null)
|
||||
// throw new InvalidOperationException($"Could not determine folder for file \"{path}\".");
|
||||
// if (Directory.Exists(directory) == false)
|
||||
// Directory.CreateDirectory(directory);
|
||||
|
||||
return path;
|
||||
}
|
||||
// return path;
|
||||
//}
|
||||
|
||||
// internal for tests
|
||||
internal void WriteCache()
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Configuration;
|
||||
using System.Linq;
|
||||
using System.Net.Configuration;
|
||||
using System.Web;
|
||||
using System.Web.Configuration;
|
||||
using System.Web.Hosting;
|
||||
using System.Web.Routing;
|
||||
using System.Web.Security;
|
||||
using System.Xml;
|
||||
using System.Xml.Linq;
|
||||
@@ -18,36 +16,22 @@ using Umbraco.Core.Security;
|
||||
|
||||
namespace Umbraco.Core.Configuration
|
||||
{
|
||||
//NOTE: Do not expose this class ever until we cleanup all configuration including removal of static classes, etc...
|
||||
// we have this two tasks logged:
|
||||
// http://issues.umbraco.org/issue/U4-58
|
||||
// http://issues.umbraco.org/issue/U4-115
|
||||
|
||||
// TODO: There's a current task and branch to refactor this into interfaces and proper config: http://issues.umbraco.org/issue/U4-8861
|
||||
// PR https://github.com/umbraco/Umbraco-CMS/compare/dev-v8...temp-U4-8861?expand=1
|
||||
|
||||
//TODO: Replace checking for if the app settings exist and returning an empty string, instead return the defaults!
|
||||
|
||||
/// <summary>
|
||||
/// The GlobalSettings Class contains general settings information for the entire Umbraco instance based on information from web.config appsettings
|
||||
/// </summary>
|
||||
[Obsolete("TODO: Need to move this configuration class into the proper configuration accesors for v8!")]
|
||||
public class GlobalSettings
|
||||
public class GlobalSettings : IGlobalSettings
|
||||
{
|
||||
|
||||
#region Private static fields
|
||||
|
||||
private static Version _version;
|
||||
private static readonly object Locker = new object();
|
||||
//make this volatile so that we can ensure thread safety with a double check lock
|
||||
private static volatile string _reservedUrlsCache;
|
||||
private static string _reservedPathsCache;
|
||||
private static HashSet<string> _reservedList = new HashSet<string>();
|
||||
|
||||
private static string _reservedPaths;
|
||||
private static string _reservedUrls;
|
||||
//ensure the built on (non-changeable) reserved paths are there at all times
|
||||
private const string StaticReservedPaths = "~/app_plugins/,~/install/,";
|
||||
private const string StaticReservedUrls = "~/config/splashes/booting.aspx,~/config/splashes/noNodes.aspx,~/VSEnterpriseHelper.axd,";
|
||||
internal const string StaticReservedPaths = "~/app_plugins/,~/install/,";
|
||||
internal const string StaticReservedUrls = "~/config/splashes/booting.aspx,~/config/splashes/noNodes.aspx,~/VSEnterpriseHelper.axd,";
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
@@ -55,7 +39,7 @@ namespace Umbraco.Core.Configuration
|
||||
/// </summary>
|
||||
private static void ResetInternal()
|
||||
{
|
||||
_reservedUrlsCache = null;
|
||||
GlobalSettingsExtensions.Reset();
|
||||
_reservedPaths = null;
|
||||
_reservedUrls = null;
|
||||
HasSmtpServer = null;
|
||||
@@ -69,7 +53,8 @@ namespace Umbraco.Core.Configuration
|
||||
{
|
||||
ResetInternal();
|
||||
}
|
||||
|
||||
|
||||
//fixme should this go on the interface or some other helper?
|
||||
public static bool HasSmtpServerConfigured(string appPath)
|
||||
{
|
||||
if (HasSmtpServer.HasValue) return HasSmtpServer.Value;
|
||||
@@ -93,15 +78,15 @@ namespace Umbraco.Core.Configuration
|
||||
/// Gets the reserved urls from web.config.
|
||||
/// </summary>
|
||||
/// <value>The reserved urls.</value>
|
||||
public static string ReservedUrls
|
||||
public string ReservedUrls
|
||||
{
|
||||
get
|
||||
{
|
||||
{
|
||||
if (_reservedUrls == null)
|
||||
{
|
||||
var urls = ConfigurationManager.AppSettings.ContainsKey("umbracoReservedUrls")
|
||||
? ConfigurationManager.AppSettings["umbracoReservedUrls"]
|
||||
: string.Empty;
|
||||
? ConfigurationManager.AppSettings["umbracoReservedUrls"]
|
||||
: string.Empty;
|
||||
|
||||
//ensure the built on (non-changeable) reserved paths are there at all times
|
||||
_reservedUrls = StaticReservedUrls + urls;
|
||||
@@ -115,7 +100,7 @@ namespace Umbraco.Core.Configuration
|
||||
/// Gets the reserved paths from web.config
|
||||
/// </summary>
|
||||
/// <value>The reserved paths.</value>
|
||||
public static string ReservedPaths
|
||||
public string ReservedPaths
|
||||
{
|
||||
get
|
||||
{
|
||||
@@ -137,7 +122,6 @@ namespace Umbraco.Core.Configuration
|
||||
}
|
||||
return _reservedPaths;
|
||||
}
|
||||
internal set { _reservedPaths = value; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -147,7 +131,7 @@ namespace Umbraco.Core.Configuration
|
||||
/// <remarks>
|
||||
/// Defaults to ~/App_Data/umbraco.config
|
||||
/// </remarks>
|
||||
public static string ContentXmlFile
|
||||
public string ContentXmlFile
|
||||
{
|
||||
get
|
||||
{
|
||||
@@ -156,26 +140,12 @@ namespace Umbraco.Core.Configuration
|
||||
: "~/App_Data/umbraco.config";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the path to the storage directory (/data by default).
|
||||
/// </summary>
|
||||
/// <value>The storage directory.</value>
|
||||
public static string StorageDirectory
|
||||
{
|
||||
get
|
||||
{
|
||||
return ConfigurationManager.AppSettings.ContainsKey("umbracoStorageDirectory")
|
||||
? ConfigurationManager.AppSettings["umbracoStorageDirectory"]
|
||||
: "~/App_Data";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Gets the path to umbraco's root directory (/umbraco by default).
|
||||
/// </summary>
|
||||
/// <value>The path.</value>
|
||||
public static string Path
|
||||
public string Path
|
||||
{
|
||||
get
|
||||
{
|
||||
@@ -183,56 +153,13 @@ namespace Umbraco.Core.Configuration
|
||||
? IOHelper.ResolveUrl(ConfigurationManager.AppSettings["umbracoPath"])
|
||||
: string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This returns the string of the MVC Area route.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// THIS IS TEMPORARY AND SHOULD BE REMOVED WHEN WE MIGRATE/UPDATE THE CONFIG SETTINGS TO BE A REAL CONFIG SECTION
|
||||
/// AND SHOULD PROBABLY BE HANDLED IN A MORE ROBUST WAY.
|
||||
///
|
||||
/// This will return the MVC area that we will route all custom routes through like surface controllers, etc...
|
||||
/// We will use the 'Path' (default ~/umbraco) to create it but since it cannot contain '/' and people may specify a path of ~/asdf/asdf/admin
|
||||
/// we will convert the '/' to '-' and use that as the path. its a bit lame but will work.
|
||||
///
|
||||
/// We also make sure that the virtual directory (SystemDirectories.Root) is stripped off first, otherwise we'd end up with something
|
||||
/// like "MyVirtualDirectory-Umbraco" instead of just "Umbraco".
|
||||
/// </remarks>
|
||||
public static string UmbracoMvcArea
|
||||
{
|
||||
get
|
||||
{
|
||||
if (Path.IsNullOrWhiteSpace())
|
||||
{
|
||||
throw new InvalidOperationException("Cannot create an MVC Area path without the umbracoPath specified");
|
||||
}
|
||||
var path = Path;
|
||||
if (path.StartsWith(SystemDirectories.Root)) // beware of TrimStart, see U4-2518
|
||||
path = path.Substring(SystemDirectories.Root.Length);
|
||||
return path.TrimStart('~').TrimStart('/').Replace('/', '-').Trim().ToLower();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the path to umbraco's client directory (/umbraco_client by default).
|
||||
/// This is a relative path to the Umbraco Path as it always must exist beside the 'umbraco'
|
||||
/// folder since the CSS paths to images depend on it.
|
||||
/// </summary>
|
||||
/// <value>The path.</value>
|
||||
public static string ClientPath
|
||||
{
|
||||
get
|
||||
{
|
||||
return Path + "/../umbraco_client";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the configuration status. This will return the version number of the currently installed umbraco instance.
|
||||
/// </summary>
|
||||
/// <value>The configuration status.</value>
|
||||
public static string ConfigurationStatus
|
||||
public string ConfigurationStatus
|
||||
{
|
||||
get
|
||||
{
|
||||
@@ -245,39 +172,7 @@ namespace Umbraco.Core.Configuration
|
||||
SaveSetting("umbracoConfigurationStatus", value);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Umbraco members membership providers' useLegacyEncoding state. This will return a boolean
|
||||
/// </summary>
|
||||
/// <value>The useLegacyEncoding status.</value>
|
||||
public static bool UmbracoMembershipProviderLegacyEncoding
|
||||
{
|
||||
get
|
||||
{
|
||||
return IsConfiguredMembershipProviderUsingLegacyEncoding(Constants.Conventions.Member.UmbracoMemberProviderName);
|
||||
}
|
||||
set
|
||||
{
|
||||
SetMembershipProvidersLegacyEncoding(Constants.Conventions.Member.UmbracoMemberProviderName, value);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Umbraco users membership providers' useLegacyEncoding state. This will return a boolean
|
||||
/// </summary>
|
||||
/// <value>The useLegacyEncoding status.</value>
|
||||
public static bool UmbracoUsersMembershipProviderLegacyEncoding
|
||||
{
|
||||
get
|
||||
{
|
||||
return IsConfiguredMembershipProviderUsingLegacyEncoding(UmbracoConfig.For.UmbracoSettings().Providers.DefaultBackOfficeUserProvider);
|
||||
}
|
||||
set
|
||||
{
|
||||
SetMembershipProvidersLegacyEncoding(UmbracoConfig.For.UmbracoSettings().Providers.DefaultBackOfficeUserProvider, value);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Saves a setting into the configuration file.
|
||||
/// </summary>
|
||||
@@ -320,64 +215,15 @@ namespace Umbraco.Core.Configuration
|
||||
ConfigurationManager.RefreshSection("appSettings");
|
||||
}
|
||||
}
|
||||
|
||||
private static void SetMembershipProvidersLegacyEncoding(string providerName, bool useLegacyEncoding)
|
||||
{
|
||||
//check if this can even be configured.
|
||||
var membershipProvider = Membership.Providers[providerName] as MembershipProviderBase;
|
||||
if (membershipProvider == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (membershipProvider.GetType().Namespace == "umbraco.providers.members")
|
||||
{
|
||||
//its the legacy one, this cannot be changed
|
||||
return;
|
||||
}
|
||||
|
||||
var webConfigFilename = IOHelper.MapPath(string.Format("{0}/web.config", SystemDirectories.Root));
|
||||
var webConfigXml = XDocument.Load(webConfigFilename, LoadOptions.PreserveWhitespace);
|
||||
|
||||
var membershipConfigs = webConfigXml.XPathSelectElements("configuration/system.web/membership/providers/add").ToList();
|
||||
|
||||
if (membershipConfigs.Any() == false)
|
||||
return;
|
||||
|
||||
var provider = membershipConfigs.SingleOrDefault(c => c.Attribute("name") != null && c.Attribute("name").Value == providerName);
|
||||
|
||||
if (provider == null)
|
||||
return;
|
||||
|
||||
provider.SetAttributeValue("useLegacyEncoding", useLegacyEncoding);
|
||||
|
||||
webConfigXml.Save(webConfigFilename, SaveOptions.DisableFormatting);
|
||||
}
|
||||
|
||||
private static bool IsConfiguredMembershipProviderUsingLegacyEncoding(string providerName)
|
||||
{
|
||||
//check if this can even be configured.
|
||||
var membershipProvider = Membership.Providers[providerName] as MembershipProviderBase;
|
||||
if (membershipProvider == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return membershipProvider.UseLegacyEncoding;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the full path to root.
|
||||
/// </summary>
|
||||
/// <value>The fullpath to root.</value>
|
||||
public static string FullpathToRoot
|
||||
{
|
||||
get { return IOHelper.GetRootDirectorySafe(); }
|
||||
}
|
||||
|
||||
[Obsolete("Use IOHelper.GetRootDirectorySafe() instead")]
|
||||
public static string FullPathToRoot => IOHelper.GetRootDirectorySafe();
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether umbraco is running in [debug mode].
|
||||
/// </summary>
|
||||
/// <value><c>true</c> if [debug mode]; otherwise, <c>false</c>.</value>
|
||||
//fixme surely thsi doesn't belong here and it's also a web request context thing
|
||||
public static bool DebugMode
|
||||
{
|
||||
get
|
||||
@@ -403,7 +249,7 @@ namespace Umbraco.Core.Configuration
|
||||
/// Gets the time out in minutes.
|
||||
/// </summary>
|
||||
/// <value>The time out in minutes.</value>
|
||||
public static int TimeOutInMinutes
|
||||
public int TimeOutInMinutes
|
||||
{
|
||||
get
|
||||
{
|
||||
@@ -422,7 +268,7 @@ namespace Umbraco.Core.Configuration
|
||||
/// Gets a value indicating whether umbraco uses directory urls.
|
||||
/// </summary>
|
||||
/// <value><c>true</c> if umbraco uses directory urls; otherwise, <c>false</c>.</value>
|
||||
public static bool UseDirectoryUrls
|
||||
public bool UseDirectoryUrls
|
||||
{
|
||||
get
|
||||
{
|
||||
@@ -441,7 +287,7 @@ namespace Umbraco.Core.Configuration
|
||||
/// Returns a string value to determine if umbraco should skip version-checking.
|
||||
/// </summary>
|
||||
/// <value>The version check period in days (0 = never).</value>
|
||||
public static int VersionCheckPeriod
|
||||
public int VersionCheckPeriod
|
||||
{
|
||||
get
|
||||
{
|
||||
@@ -455,34 +301,14 @@ namespace Umbraco.Core.Configuration
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a string value to determine if umbraco should disbable xslt extensions
|
||||
/// </summary>
|
||||
/// <value><c>"true"</c> if version xslt extensions are disabled, otherwise, <c>"false"</c></value>
|
||||
[Obsolete("This is no longer used and will be removed from the codebase in future releases")]
|
||||
public static string DisableXsltExtensions
|
||||
{
|
||||
get
|
||||
{
|
||||
return ConfigurationManager.AppSettings.ContainsKey("umbracoDisableXsltExtensions")
|
||||
? ConfigurationManager.AppSettings["umbracoDisableXsltExtensions"]
|
||||
: "false";
|
||||
}
|
||||
}
|
||||
|
||||
internal static bool ContentCacheXmlStoredInCodeGen
|
||||
{
|
||||
get { return LocalTempStorageLocation == LocalTempStorage.AspNetTemp; }
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// This is the location type to store temporary files such as cache files or other localized files for a given machine
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Currently used for the xml cache file and the plugin cache files
|
||||
/// </remarks>
|
||||
internal static LocalTempStorage LocalTempStorageLocation
|
||||
public LocalTempStorage LocalTempStorageLocation
|
||||
{
|
||||
get
|
||||
{
|
||||
@@ -494,21 +320,12 @@ namespace Umbraco.Core.Configuration
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a string value to determine if umbraco should use Xhtml editing mode in the wysiwyg editor
|
||||
/// </summary>
|
||||
/// <value><c>"true"</c> if Xhtml mode is enable, otherwise, <c>"false"</c></value>
|
||||
[Obsolete("This is no longer used and will be removed from the codebase in future releases")]
|
||||
public static string EditXhtmlMode
|
||||
{
|
||||
get { return "true"; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the default UI language.
|
||||
/// </summary>
|
||||
/// <value>The default UI language.</value>
|
||||
public static string DefaultUILanguage
|
||||
// ReSharper disable once InconsistentNaming
|
||||
public string DefaultUILanguage
|
||||
{
|
||||
get
|
||||
{
|
||||
@@ -518,28 +335,13 @@ namespace Umbraco.Core.Configuration
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the profile URL.
|
||||
/// </summary>
|
||||
/// <value>The profile URL.</value>
|
||||
public static string ProfileUrl
|
||||
{
|
||||
get
|
||||
{
|
||||
//the default will be 'profiler'
|
||||
return ConfigurationManager.AppSettings.ContainsKey("umbracoProfileUrl")
|
||||
? ConfigurationManager.AppSettings["umbracoProfileUrl"]
|
||||
: "profiler";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether umbraco should hide top level nodes from generated urls.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <c>true</c> if umbraco hides top level nodes from urls; otherwise, <c>false</c>.
|
||||
/// </value>
|
||||
public static bool HideTopLevelNodeFromPath
|
||||
public bool HideTopLevelNodeFromPath
|
||||
{
|
||||
get
|
||||
{
|
||||
@@ -554,95 +356,16 @@ namespace Umbraco.Core.Configuration
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current version.
|
||||
/// </summary>
|
||||
/// <value>The current version.</value>
|
||||
[Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)]
|
||||
public static string CurrentVersion
|
||||
{
|
||||
get { return UmbracoVersion.SemanticVersion.ToSemanticString(); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the major version number.
|
||||
/// </summary>
|
||||
/// <value>The major version number.</value>
|
||||
[Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)]
|
||||
public static int VersionMajor
|
||||
{
|
||||
get
|
||||
{
|
||||
return UmbracoVersion.Current.Major;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the minor version number.
|
||||
/// </summary>
|
||||
/// <value>The minor version number.</value>
|
||||
[Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)]
|
||||
public static int VersionMinor
|
||||
{
|
||||
get
|
||||
{
|
||||
return UmbracoVersion.Current.Minor;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the patch version number.
|
||||
/// </summary>
|
||||
/// <value>The patch version number.</value>
|
||||
[Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)]
|
||||
public static int VersionPatch
|
||||
{
|
||||
get
|
||||
{
|
||||
return UmbracoVersion.Current.Build;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the version comment (like beta or RC).
|
||||
/// </summary>
|
||||
/// <value>The version comment.</value>
|
||||
[Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)]
|
||||
public static string VersionComment
|
||||
{
|
||||
get
|
||||
{
|
||||
return Umbraco.Core.Configuration.UmbracoVersion.CurrentComment;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Requests the is in umbraco application directory structure.
|
||||
/// </summary>
|
||||
/// <param name="context">The context.</param>
|
||||
/// <returns></returns>
|
||||
public static bool RequestIsInUmbracoApplication(HttpContext context)
|
||||
{
|
||||
return context.Request.Path.ToLower().IndexOf(IOHelper.ResolveUrl(SystemDirectories.Umbraco).ToLower()) > -1;
|
||||
}
|
||||
|
||||
public static bool RequestIsInUmbracoApplication(HttpContextBase context)
|
||||
{
|
||||
return context.Request.Path.ToLower().IndexOf(IOHelper.ResolveUrl(SystemDirectories.Umbraco).ToLower()) > -1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether umbraco should force a secure (https) connection to the backoffice.
|
||||
/// </summary>
|
||||
/// <value><c>true</c> if [use SSL]; otherwise, <c>false</c>.</value>
|
||||
public static bool UseSSL
|
||||
public bool UseHttps
|
||||
{
|
||||
get
|
||||
{
|
||||
try
|
||||
{
|
||||
return bool.Parse(ConfigurationManager.AppSettings["umbracoUseSSL"]);
|
||||
return bool.Parse(ConfigurationManager.AppSettings["umbracoUseHttps"]);
|
||||
}
|
||||
catch
|
||||
{
|
||||
@@ -651,131 +374,6 @@ namespace Umbraco.Core.Configuration
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the umbraco license.
|
||||
/// </summary>
|
||||
/// <value>The license.</value>
|
||||
public static string License
|
||||
{
|
||||
get
|
||||
{
|
||||
string license =
|
||||
"<A href=\"http://umbraco.org/redir/license\" target=\"_blank\">the open source license MIT</A>. The umbraco UI is freeware licensed under the umbraco license.";
|
||||
|
||||
var versionDoc = new XmlDocument();
|
||||
var versionReader = new XmlTextReader(IOHelper.MapPath(SystemDirectories.Umbraco + "/version.xml"));
|
||||
versionDoc.Load(versionReader);
|
||||
versionReader.Close();
|
||||
|
||||
// check for license
|
||||
try
|
||||
{
|
||||
string licenseUrl =
|
||||
versionDoc.SelectSingleNode("/version/licensing/licenseUrl").FirstChild.Value;
|
||||
string licenseValidation =
|
||||
versionDoc.SelectSingleNode("/version/licensing/licenseValidation").FirstChild.Value;
|
||||
string licensedTo =
|
||||
versionDoc.SelectSingleNode("/version/licensing/licensedTo").FirstChild.Value;
|
||||
|
||||
if (licensedTo != "" && licenseUrl != "")
|
||||
{
|
||||
license = "umbraco Commercial License<br/><b>Registered to:</b><br/>" +
|
||||
licensedTo.Replace("\n", "<br/>") + "<br/><b>For use with domain:</b><br/>" +
|
||||
licenseUrl;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
|
||||
return license;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the current request is reserved based on the route table and
|
||||
/// whether the specified URL is reserved or is inside a reserved path.
|
||||
/// </summary>
|
||||
/// <param name="url"></param>
|
||||
/// <param name="httpContext"></param>
|
||||
/// <param name="routes">The route collection to lookup the request in</param>
|
||||
/// <returns></returns>
|
||||
public static bool IsReservedPathOrUrl(string url, HttpContextBase httpContext, RouteCollection routes)
|
||||
{
|
||||
if (httpContext == null) throw new ArgumentNullException("httpContext");
|
||||
if (routes == null) throw new ArgumentNullException("routes");
|
||||
|
||||
//check if the current request matches a route, if so then it is reserved.
|
||||
var route = routes.GetRouteData(httpContext);
|
||||
if (route != null)
|
||||
return true;
|
||||
|
||||
//continue with the standard ignore routine
|
||||
return IsReservedPathOrUrl(url);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the specified URL is reserved or is inside a reserved path.
|
||||
/// </summary>
|
||||
/// <param name="url">The URL to check.</param>
|
||||
/// <returns>
|
||||
/// <c>true</c> if the specified URL is reserved; otherwise, <c>false</c>.
|
||||
/// </returns>
|
||||
public static bool IsReservedPathOrUrl(string url)
|
||||
{
|
||||
if (_reservedUrlsCache == null)
|
||||
{
|
||||
lock (Locker)
|
||||
{
|
||||
if (_reservedUrlsCache == null)
|
||||
{
|
||||
// store references to strings to determine changes
|
||||
_reservedPathsCache = GlobalSettings.ReservedPaths;
|
||||
_reservedUrlsCache = GlobalSettings.ReservedUrls;
|
||||
|
||||
// add URLs and paths to a new list
|
||||
var newReservedList = new HashSet<string>();
|
||||
foreach (var reservedUrlTrimmed in _reservedUrlsCache
|
||||
.Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries)
|
||||
.Select(x => x.Trim().ToLowerInvariant())
|
||||
.Where(x => x.IsNullOrWhiteSpace() == false)
|
||||
.Select(reservedUrl => IOHelper.ResolveUrl(reservedUrl).Trim().EnsureStartsWith("/"))
|
||||
.Where(reservedUrlTrimmed => reservedUrlTrimmed.IsNullOrWhiteSpace() == false))
|
||||
{
|
||||
newReservedList.Add(reservedUrlTrimmed);
|
||||
}
|
||||
|
||||
foreach (var reservedPathTrimmed in _reservedPathsCache
|
||||
.Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries)
|
||||
.Select(x => x.Trim().ToLowerInvariant())
|
||||
.Where(x => x.IsNullOrWhiteSpace() == false)
|
||||
.Select(reservedPath => IOHelper.ResolveUrl(reservedPath).Trim().EnsureStartsWith("/").EnsureEndsWith("/"))
|
||||
.Where(reservedPathTrimmed => reservedPathTrimmed.IsNullOrWhiteSpace() == false))
|
||||
{
|
||||
newReservedList.Add(reservedPathTrimmed);
|
||||
}
|
||||
|
||||
// use the new list from now on
|
||||
_reservedList = newReservedList;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//The url should be cleaned up before checking:
|
||||
// * If it doesn't contain an '.' in the path then we assume it is a path based URL, if that is the case we should add an trailing '/' because all of our reservedPaths use a trailing '/'
|
||||
// * We shouldn't be comparing the query at all
|
||||
var pathPart = url.Split(new[] {'?'}, StringSplitOptions.RemoveEmptyEntries)[0].ToLowerInvariant();
|
||||
if (pathPart.Contains(".") == false)
|
||||
{
|
||||
pathPart = pathPart.EnsureEndsWith('/');
|
||||
}
|
||||
|
||||
// return true if url starts with an element of the reserved list
|
||||
return _reservedList.Any(x => pathPart.InvariantStartsWith(x));
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Web;
|
||||
using System.Web.Routing;
|
||||
using Umbraco.Core.IO;
|
||||
|
||||
namespace Umbraco.Core.Configuration
|
||||
{
|
||||
public static class GlobalSettingsExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Used in unit testing to reset all config items, this is automatically called by GlobalSettings.Reset()
|
||||
/// </summary>
|
||||
internal static void Reset()
|
||||
{
|
||||
_reservedUrlsCache = null;
|
||||
_mvcArea = null;
|
||||
}
|
||||
|
||||
private static readonly object Locker = new object();
|
||||
//make this volatile so that we can ensure thread safety with a double check lock
|
||||
private static volatile string _reservedUrlsCache;
|
||||
private static string _reservedPathsCache;
|
||||
private static HashSet<string> _reservedList = new HashSet<string>();
|
||||
private static string _mvcArea;
|
||||
|
||||
/// <summary>
|
||||
/// This returns the string of the MVC Area route.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This will return the MVC area that we will route all custom routes through like surface controllers, etc...
|
||||
/// We will use the 'Path' (default ~/umbraco) to create it but since it cannot contain '/' and people may specify a path of ~/asdf/asdf/admin
|
||||
/// we will convert the '/' to '-' and use that as the path. its a bit lame but will work.
|
||||
///
|
||||
/// We also make sure that the virtual directory (SystemDirectories.Root) is stripped off first, otherwise we'd end up with something
|
||||
/// like "MyVirtualDirectory-Umbraco" instead of just "Umbraco".
|
||||
/// </remarks>
|
||||
public static string GetUmbracoMvcArea(this IGlobalSettings globalSettings)
|
||||
{
|
||||
if (_mvcArea != null) return _mvcArea;
|
||||
|
||||
if (globalSettings.Path.IsNullOrWhiteSpace())
|
||||
{
|
||||
throw new InvalidOperationException("Cannot create an MVC Area path without the umbracoPath specified");
|
||||
}
|
||||
|
||||
var path = globalSettings.Path;
|
||||
if (path.StartsWith(SystemDirectories.Root)) // beware of TrimStart, see U4-2518
|
||||
path = path.Substring(SystemDirectories.Root.Length);
|
||||
_mvcArea = path.TrimStart('~').TrimStart('/').Replace('/', '-').Trim().ToLower();
|
||||
return _mvcArea;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the specified URL is reserved or is inside a reserved path.
|
||||
/// </summary>
|
||||
/// <param name="globalSettings"></param>
|
||||
/// <param name="url">The URL to check.</param>
|
||||
/// <returns>
|
||||
/// <c>true</c> if the specified URL is reserved; otherwise, <c>false</c>.
|
||||
/// </returns>
|
||||
internal static bool IsReservedPathOrUrl(this IGlobalSettings globalSettings, string url)
|
||||
{
|
||||
if (_reservedUrlsCache == null)
|
||||
{
|
||||
lock (Locker)
|
||||
{
|
||||
if (_reservedUrlsCache == null)
|
||||
{
|
||||
// store references to strings to determine changes
|
||||
_reservedPathsCache = globalSettings.ReservedPaths;
|
||||
_reservedUrlsCache = globalSettings.ReservedUrls;
|
||||
|
||||
// add URLs and paths to a new list
|
||||
var newReservedList = new HashSet<string>();
|
||||
foreach (var reservedUrlTrimmed in _reservedUrlsCache
|
||||
.Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries)
|
||||
.Select(x => x.Trim().ToLowerInvariant())
|
||||
.Where(x => x.IsNullOrWhiteSpace() == false)
|
||||
.Select(reservedUrl => IOHelper.ResolveUrl(reservedUrl).Trim().EnsureStartsWith("/"))
|
||||
.Where(reservedUrlTrimmed => reservedUrlTrimmed.IsNullOrWhiteSpace() == false))
|
||||
{
|
||||
newReservedList.Add(reservedUrlTrimmed);
|
||||
}
|
||||
|
||||
foreach (var reservedPathTrimmed in _reservedPathsCache
|
||||
.Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries)
|
||||
.Select(x => x.Trim().ToLowerInvariant())
|
||||
.Where(x => x.IsNullOrWhiteSpace() == false)
|
||||
.Select(reservedPath => IOHelper.ResolveUrl(reservedPath).Trim().EnsureStartsWith("/").EnsureEndsWith("/"))
|
||||
.Where(reservedPathTrimmed => reservedPathTrimmed.IsNullOrWhiteSpace() == false))
|
||||
{
|
||||
newReservedList.Add(reservedPathTrimmed);
|
||||
}
|
||||
|
||||
// use the new list from now on
|
||||
_reservedList = newReservedList;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//The url should be cleaned up before checking:
|
||||
// * If it doesn't contain an '.' in the path then we assume it is a path based URL, if that is the case we should add an trailing '/' because all of our reservedPaths use a trailing '/'
|
||||
// * We shouldn't be comparing the query at all
|
||||
var pathPart = url.Split(new[] {'?'}, StringSplitOptions.RemoveEmptyEntries)[0].ToLowerInvariant();
|
||||
if (pathPart.Contains(".") == false)
|
||||
{
|
||||
pathPart = pathPart.EnsureEndsWith('/');
|
||||
}
|
||||
|
||||
// return true if url starts with an element of the reserved list
|
||||
return _reservedList.Any(x => pathPart.InvariantStartsWith(x));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the current request is reserved based on the route table and
|
||||
/// whether the specified URL is reserved or is inside a reserved path.
|
||||
/// </summary>
|
||||
/// <param name="globalSettings"></param>
|
||||
/// <param name="url"></param>
|
||||
/// <param name="httpContext"></param>
|
||||
/// <param name="routes">The route collection to lookup the request in</param>
|
||||
/// <returns></returns>
|
||||
internal static bool IsReservedPathOrUrl(this IGlobalSettings globalSettings, string url, HttpContextBase httpContext, RouteCollection routes)
|
||||
{
|
||||
if (httpContext == null) throw new ArgumentNullException(nameof(httpContext));
|
||||
if (routes == null) throw new ArgumentNullException(nameof(routes));
|
||||
|
||||
//check if the current request matches a route, if so then it is reserved.
|
||||
var route = routes.GetRouteData(httpContext);
|
||||
if (route != null)
|
||||
return true;
|
||||
|
||||
//continue with the standard ignore routine
|
||||
return globalSettings.IsReservedPathOrUrl(url);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
namespace Umbraco.Core.Configuration
|
||||
{
|
||||
/// <summary>
|
||||
/// Contains general settings information for the entire Umbraco instance based on information from web.config appsettings
|
||||
/// </summary>
|
||||
public interface IGlobalSettings
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the reserved urls from web.config.
|
||||
/// </summary>
|
||||
/// <value>The reserved urls.</value>
|
||||
string ReservedUrls { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the reserved paths from web.config
|
||||
/// </summary>
|
||||
/// <value>The reserved paths.</value>
|
||||
string ReservedPaths { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the name of the content XML file.
|
||||
/// </summary>
|
||||
/// <value>The content XML.</value>
|
||||
/// <remarks>
|
||||
/// Defaults to ~/App_Data/umbraco.config
|
||||
/// </remarks>
|
||||
string ContentXmlFile { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the path to umbraco's root directory (/umbraco by default).
|
||||
/// </summary>
|
||||
string Path { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the configuration status. This will return the version number of the currently installed umbraco instance.
|
||||
/// </summary>
|
||||
string ConfigurationStatus { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the time out in minutes.
|
||||
/// </summary>
|
||||
int TimeOutInMinutes { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether umbraco uses directory urls.
|
||||
/// </summary>
|
||||
/// <value><c>true</c> if umbraco uses directory urls; otherwise, <c>false</c>.</value>
|
||||
bool UseDirectoryUrls { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the default UI language.
|
||||
/// </summary>
|
||||
/// <value>The default UI language.</value>
|
||||
// ReSharper disable once InconsistentNaming
|
||||
string DefaultUILanguage { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether umbraco should hide top level nodes from generated urls.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <c>true</c> if umbraco hides top level nodes from urls; otherwise, <c>false</c>.
|
||||
/// </value>
|
||||
bool HideTopLevelNodeFromPath { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether umbraco should force a secure (https) connection to the backoffice.
|
||||
/// </summary>
|
||||
bool UseHttps { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Returns a string value to determine if umbraco should skip version-checking.
|
||||
/// </summary>
|
||||
/// <value>The version check period in days (0 = never).</value>
|
||||
int VersionCheckPeriod { get; }
|
||||
|
||||
/// <summary>
|
||||
/// This is the location type to store temporary files such as cache files or other localized files for a given machine
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Used for some cache files and for specific environments such as Azure
|
||||
/// </remarks>
|
||||
LocalTempStorage LocalTempStorageLocation { get; }
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
namespace Umbraco.Core.Configuration
|
||||
{
|
||||
internal enum LocalTempStorage
|
||||
public enum LocalTempStorage
|
||||
{
|
||||
Unknown = 0,
|
||||
Default,
|
||||
|
||||
@@ -65,17 +65,20 @@ namespace Umbraco.Core.Configuration
|
||||
/// <param name="umbracoSettings"></param>
|
||||
/// <param name="dashboardSettings"></param>
|
||||
/// <param name="healthChecks"></param>
|
||||
public UmbracoConfig(IUmbracoSettingsSection umbracoSettings, IDashboardSection dashboardSettings, IHealthChecks healthChecks)
|
||||
/// <param name="globalSettings"></param>
|
||||
public UmbracoConfig(IUmbracoSettingsSection umbracoSettings, IDashboardSection dashboardSettings, IHealthChecks healthChecks, IGlobalSettings globalSettings)
|
||||
{
|
||||
SetHealthCheckSettings(healthChecks);
|
||||
SetUmbracoSettings(umbracoSettings);
|
||||
SetDashboardSettings(dashboardSettings);
|
||||
SetGlobalConfig(globalSettings);
|
||||
}
|
||||
|
||||
private IHealthChecks _healthChecks;
|
||||
private IDashboardSection _dashboardSection;
|
||||
private IUmbracoSettingsSection _umbracoSettings;
|
||||
private IGridConfig _gridConfig;
|
||||
private IGlobalSettings _globalSettings;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the IHealthCheck config
|
||||
@@ -134,6 +137,23 @@ namespace Umbraco.Core.Configuration
|
||||
_umbracoSettings = value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Only for testing
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
public void SetGlobalConfig(IGlobalSettings value)
|
||||
{
|
||||
_globalSettings = value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the IGlobalSettings
|
||||
/// </summary>
|
||||
public IGlobalSettings GlobalSettings()
|
||||
{
|
||||
return _globalSettings ?? (_globalSettings = new GlobalSettings());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the IUmbracoSettings
|
||||
/// </summary>
|
||||
|
||||
@@ -21,6 +21,8 @@ namespace Umbraco.Core
|
||||
/// </summary>
|
||||
public const string PreviewCookieName = "UMB_PREVIEW";
|
||||
|
||||
public const string InstallerCookieName = "umb_installId";
|
||||
|
||||
/// <summary>
|
||||
/// The auth cookie name
|
||||
/// </summary>
|
||||
|
||||
@@ -29,6 +29,7 @@ namespace Umbraco.Core.IO
|
||||
private ShadowWrapper _xsltFileSystem;
|
||||
private ShadowWrapper _masterPagesFileSystem;
|
||||
private ShadowWrapper _mvcViewsFileSystem;
|
||||
private ShadowWrapper _javaScriptLibraryFileSystem;
|
||||
|
||||
// well-known file systems lazy initialization
|
||||
private object _wkfsLock = new object();
|
||||
@@ -165,7 +166,7 @@ namespace Umbraco.Core.IO
|
||||
var xsltFileSystem = new PhysicalFileSystem(SystemDirectories.Xslt);
|
||||
var masterPagesFileSystem = new PhysicalFileSystem(SystemDirectories.Masterpages);
|
||||
var mvcViewsFileSystem = new PhysicalFileSystem(SystemDirectories.MvcViews);
|
||||
|
||||
var javaScriptLibraryFileSystem = new PhysicalFileSystem(SystemDirectories.JavaScriptLibrary);
|
||||
|
||||
_macroPartialFileSystem = new ShadowWrapper(macroPartialFileSystem, "Views/MacroPartials", () => IsScoped());
|
||||
_partialViewsFileSystem = new ShadowWrapper(partialViewsFileSystem, "Views/Partials", () => IsScoped());
|
||||
@@ -174,8 +175,7 @@ namespace Umbraco.Core.IO
|
||||
_xsltFileSystem = new ShadowWrapper(xsltFileSystem, "xslt", () => IsScoped());
|
||||
_masterPagesFileSystem = new ShadowWrapper(masterPagesFileSystem, "masterpages", () => IsScoped());
|
||||
_mvcViewsFileSystem = new ShadowWrapper(mvcViewsFileSystem, "Views", () => IsScoped());
|
||||
|
||||
_javascriptLibraryFileSystem = new PhysicalFileSystem(Path.Combine(SystemDirectories.Umbraco, "lib"));
|
||||
_javascriptLibraryFileSystem = new ShadowWrapper(javaScriptLibraryFileSystem, "Lib", () => IsScoped());
|
||||
|
||||
// filesystems obtained from GetFileSystemProvider are already wrapped and do not need to be wrapped again
|
||||
_mediaFileSystem = GetFileSystemProvider<MediaFileSystem>();
|
||||
|
||||
@@ -131,9 +131,9 @@ namespace Umbraco.Core.IO
|
||||
//use a tilde character instead of the complete path
|
||||
internal static string ReturnPath(string settingsKey, string standardPath, bool useTilde)
|
||||
{
|
||||
string retval = ConfigurationManager.AppSettings[settingsKey];
|
||||
var retval = ConfigurationManager.AppSettings[settingsKey];
|
||||
|
||||
if (String.IsNullOrEmpty(retval))
|
||||
if (string.IsNullOrEmpty(retval))
|
||||
retval = standardPath;
|
||||
|
||||
return retval.TrimEnd('/');
|
||||
|
||||
@@ -1,11 +1,5 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Configuration;
|
||||
|
||||
using System.Web;
|
||||
using System.IO;
|
||||
|
||||
namespace Umbraco.Core.IO
|
||||
{
|
||||
@@ -13,179 +7,56 @@ namespace Umbraco.Core.IO
|
||||
public class SystemDirectories
|
||||
{
|
||||
//TODO: Why on earth is this even configurable? You cannot change the /Bin folder in ASP.Net
|
||||
public static string Bin
|
||||
{
|
||||
get
|
||||
{
|
||||
return IOHelper.ReturnPath("umbracoBinDirectory", "~/bin");
|
||||
}
|
||||
}
|
||||
public static string Bin => IOHelper.ReturnPath("umbracoBinDirectory", "~/bin");
|
||||
|
||||
public static string Base
|
||||
{
|
||||
get
|
||||
{
|
||||
return IOHelper.ReturnPath("umbracoBaseDirectory", "~/base");
|
||||
}
|
||||
}
|
||||
public static string Base => IOHelper.ReturnPath("umbracoBaseDirectory", "~/base");
|
||||
|
||||
public static string Config
|
||||
{
|
||||
get
|
||||
{
|
||||
return IOHelper.ReturnPath("umbracoConfigDirectory", "~/config");
|
||||
}
|
||||
}
|
||||
public static string Config => IOHelper.ReturnPath("umbracoConfigDirectory", "~/config");
|
||||
|
||||
public static string Css
|
||||
{
|
||||
get
|
||||
{
|
||||
return IOHelper.ReturnPath("umbracoCssDirectory", "~/css");
|
||||
}
|
||||
}
|
||||
public static string Css => IOHelper.ReturnPath("umbracoCssDirectory", "~/css");
|
||||
|
||||
public static string Data
|
||||
{
|
||||
get
|
||||
{
|
||||
return IOHelper.ReturnPath("umbracoStorageDirectory", "~/App_Data");
|
||||
}
|
||||
}
|
||||
public static string Data => IOHelper.ReturnPath("umbracoStorageDirectory", "~/App_Data");
|
||||
|
||||
public static string Install
|
||||
{
|
||||
get
|
||||
{
|
||||
return IOHelper.ReturnPath("umbracoInstallPath", "~/install");
|
||||
}
|
||||
}
|
||||
public static string Install => IOHelper.ReturnPath("umbracoInstallPath", "~/install");
|
||||
|
||||
public static string Masterpages
|
||||
{
|
||||
get
|
||||
{
|
||||
return IOHelper.ReturnPath("umbracoMasterPagesPath", "~/masterpages");
|
||||
}
|
||||
}
|
||||
public static string Masterpages => IOHelper.ReturnPath("umbracoMasterPagesPath", "~/masterpages");
|
||||
|
||||
public static string AppCode
|
||||
{
|
||||
get
|
||||
{
|
||||
//NOTE: this is not configurable and shouldn't need to be
|
||||
return "~/App_Code";
|
||||
}
|
||||
}
|
||||
//NOTE: this is not configurable and shouldn't need to be
|
||||
public static string AppCode => "~/App_Code";
|
||||
|
||||
public static string AppPlugins
|
||||
{
|
||||
get
|
||||
{
|
||||
//NOTE: this is not configurable and shouldn't need to be
|
||||
return "~/App_Plugins";
|
||||
}
|
||||
}
|
||||
//NOTE: this is not configurable and shouldn't need to be
|
||||
public static string AppPlugins => "~/App_Plugins";
|
||||
|
||||
public static string MvcViews
|
||||
{
|
||||
get
|
||||
{
|
||||
//NOTE: this is not configurable and shouldn't need to be
|
||||
return "~/Views";
|
||||
}
|
||||
}
|
||||
//NOTE: this is not configurable and shouldn't need to be
|
||||
public static string MvcViews => "~/Views";
|
||||
|
||||
public static string PartialViews
|
||||
{
|
||||
get
|
||||
{
|
||||
return MvcViews + "/Partials/";
|
||||
}
|
||||
}
|
||||
public static string PartialViews => MvcViews + "/Partials/";
|
||||
|
||||
public static string MacroPartials
|
||||
{
|
||||
get
|
||||
{
|
||||
return MvcViews + "/MacroPartials/";
|
||||
public static string MacroPartials => MvcViews + "/MacroPartials/";
|
||||
|
||||
}
|
||||
}
|
||||
public static string Media => IOHelper.ReturnPath("umbracoMediaPath", "~/media");
|
||||
|
||||
public static string Media
|
||||
{
|
||||
get
|
||||
{
|
||||
return IOHelper.ReturnPath("umbracoMediaPath", "~/media");
|
||||
}
|
||||
}
|
||||
public static string Scripts => IOHelper.ReturnPath("umbracoScriptsPath", "~/scripts");
|
||||
|
||||
public static string Scripts
|
||||
{
|
||||
get
|
||||
{
|
||||
return IOHelper.ReturnPath("umbracoScriptsPath", "~/scripts");
|
||||
}
|
||||
}
|
||||
public static string Umbraco => IOHelper.ReturnPath("umbracoPath", "~/umbraco");
|
||||
|
||||
public static string Umbraco
|
||||
{
|
||||
get
|
||||
{
|
||||
return IOHelper.ReturnPath("umbracoPath", "~/umbraco");
|
||||
}
|
||||
}
|
||||
public static string UmbracoClient => IOHelper.ReturnPath("umbracoClientPath", "~/umbraco_client");
|
||||
|
||||
public static string UmbracoClient
|
||||
{
|
||||
get
|
||||
{
|
||||
return IOHelper.ReturnPath("umbracoClientPath", "~/umbraco_client");
|
||||
}
|
||||
}
|
||||
public static string UserControls => IOHelper.ReturnPath("umbracoUsercontrolsPath", "~/usercontrols");
|
||||
|
||||
public static string UserControls
|
||||
{
|
||||
get
|
||||
{
|
||||
return IOHelper.ReturnPath("umbracoUsercontrolsPath", "~/usercontrols");
|
||||
}
|
||||
}
|
||||
public static string WebServices => IOHelper.ReturnPath("umbracoWebservicesPath", Umbraco.EnsureEndsWith("/") + "webservices");
|
||||
|
||||
public static string WebServices
|
||||
{
|
||||
get
|
||||
{
|
||||
return IOHelper.ReturnPath("umbracoWebservicesPath", Umbraco.EnsureEndsWith("/") + "webservices");
|
||||
}
|
||||
}
|
||||
public static string Xslt => IOHelper.ReturnPath("umbracoXsltPath", "~/xslt");
|
||||
|
||||
public static string Xslt
|
||||
{
|
||||
get {
|
||||
return IOHelper.ReturnPath("umbracoXsltPath", "~/xslt");
|
||||
}
|
||||
}
|
||||
//by default the packages folder should exist in the data folder
|
||||
public static string Packages => IOHelper.ReturnPath("umbracoPackagesPath", Data + IOHelper.DirSepChar + "packages");
|
||||
|
||||
public static string Packages
|
||||
{
|
||||
get
|
||||
{
|
||||
//by default the packages folder should exist in the data folder
|
||||
return IOHelper.ReturnPath("umbracoPackagesPath", Data + IOHelper.DirSepChar + "packages");
|
||||
}
|
||||
}
|
||||
public static string Preview => IOHelper.ReturnPath("umbracoPreviewPath", Data + IOHelper.DirSepChar + "preview");
|
||||
|
||||
public static string JavaScriptLibrary => IOHelper.ReturnPath("umbracoJavaScriptLibraryPath", Umbraco + IOHelper.DirSepChar + "lib");
|
||||
|
||||
public static string Preview
|
||||
{
|
||||
get
|
||||
{
|
||||
return IOHelper.ReturnPath("umbracoPreviewPath", Data + IOHelper.DirSepChar + "preview");
|
||||
}
|
||||
}
|
||||
private static string _root;
|
||||
|
||||
private static string _root;
|
||||
/// <summary>
|
||||
/// Gets the root path of the application
|
||||
/// </summary>
|
||||
@@ -193,21 +64,18 @@ namespace Umbraco.Core.IO
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_root == null)
|
||||
{
|
||||
string appPath = HttpRuntime.AppDomainAppVirtualPath ?? string.Empty;
|
||||
if (appPath == "/")
|
||||
appPath = string.Empty;
|
||||
if (_root != null) return _root;
|
||||
|
||||
var appPath = HttpRuntime.AppDomainAppVirtualPath;
|
||||
// ReSharper disable once ConditionIsAlwaysTrueOrFalse
|
||||
if (appPath == null || appPath == "/") appPath = string.Empty;
|
||||
|
||||
_root = appPath;
|
||||
|
||||
_root = appPath;
|
||||
}
|
||||
return _root;
|
||||
}
|
||||
//Only required for unit tests
|
||||
internal set { _root = value; }
|
||||
internal set => _root = value;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -18,27 +18,24 @@ namespace Umbraco.Core.IO
|
||||
public static string FeedProxyConfig => string.Concat(SystemDirectories.Config, "/feedProxy.config");
|
||||
|
||||
// fixme - kill
|
||||
public static string ContentCacheXml
|
||||
public static string GetContentCacheXml(IGlobalSettings globalSettings)
|
||||
{
|
||||
get
|
||||
switch (globalSettings.LocalTempStorageLocation)
|
||||
{
|
||||
switch (GlobalSettings.LocalTempStorageLocation)
|
||||
{
|
||||
case LocalTempStorage.AspNetTemp:
|
||||
return Path.Combine(HttpRuntime.CodegenDir, @"UmbracoData\umbraco.config");
|
||||
case LocalTempStorage.EnvironmentTemp:
|
||||
var appDomainHash = HttpRuntime.AppDomainAppId.ToSHA1();
|
||||
var cachePath = Path.Combine(Environment.ExpandEnvironmentVariables("%temp%"), "UmbracoData",
|
||||
//include the appdomain hash is just a safety check, for example if a website is moved from worker A to worker B and then back
|
||||
// to worker A again, in theory the %temp% folder should already be empty but we really want to make sure that its not
|
||||
// utilizing an old path
|
||||
appDomainHash);
|
||||
return Path.Combine(cachePath, "umbraco.config");
|
||||
case LocalTempStorage.Default:
|
||||
return IOHelper.ReturnPath("umbracoContentXML", "~/App_Data/umbraco.config");
|
||||
default:
|
||||
throw new ArgumentOutOfRangeException();
|
||||
}
|
||||
case LocalTempStorage.AspNetTemp:
|
||||
return Path.Combine(HttpRuntime.CodegenDir, @"UmbracoData\umbraco.config");
|
||||
case LocalTempStorage.EnvironmentTemp:
|
||||
var appDomainHash = HttpRuntime.AppDomainAppId.ToSHA1();
|
||||
var cachePath = Path.Combine(Environment.ExpandEnvironmentVariables("%temp%"), "UmbracoData",
|
||||
//include the appdomain hash is just a safety check, for example if a website is moved from worker A to worker B and then back
|
||||
// to worker A again, in theory the %temp% folder should already be empty but we really want to make sure that its not
|
||||
// utilizing an old path
|
||||
appDomainHash);
|
||||
return Path.Combine(cachePath, "umbraco.config");
|
||||
case LocalTempStorage.Default:
|
||||
return IOHelper.ReturnPath("umbracoContentXML", "~/App_Data/umbraco.config");
|
||||
default:
|
||||
throw new ArgumentOutOfRangeException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ namespace Umbraco.Core.Migrations.Install
|
||||
{
|
||||
private readonly IUmbracoDatabaseFactory _databaseFactory;
|
||||
private readonly IScopeProvider _scopeProvider;
|
||||
private readonly IGlobalSettings _globalSettings;
|
||||
private readonly IRuntimeState _runtime;
|
||||
private readonly IMigrationBuilder _migrationBuilder;
|
||||
private readonly IKeyValueService _keyValueService;
|
||||
@@ -32,9 +33,10 @@ namespace Umbraco.Core.Migrations.Install
|
||||
|
||||
private DatabaseSchemaResult _databaseSchemaValidationResult;
|
||||
|
||||
public DatabaseBuilder(IScopeProvider scopeProvider, IUmbracoDatabaseFactory databaseFactory, IRuntimeState runtime, ILogger logger, IMigrationBuilder migrationBuilder, IKeyValueService keyValueService, PostMigrationCollection postMigrations)
|
||||
public DatabaseBuilder(IScopeProvider scopeProvider, IGlobalSettings globalSettings, IUmbracoDatabaseFactory databaseFactory, IRuntimeState runtime, ILogger logger, IMigrationBuilder migrationBuilder, IKeyValueService keyValueService, PostMigrationCollection postMigrations)
|
||||
{
|
||||
_scopeProvider = scopeProvider;
|
||||
_globalSettings = globalSettings;
|
||||
_databaseFactory = databaseFactory;
|
||||
_runtime = runtime;
|
||||
_logger = logger;
|
||||
@@ -132,7 +134,7 @@ namespace Umbraco.Core.Migrations.Install
|
||||
{
|
||||
SaveConnectionString(EmbeddedDatabaseConnectionString, Constants.DbProviderNames.SqlCe, logger);
|
||||
|
||||
var path = Path.Combine(GlobalSettings.FullpathToRoot, "App_Data", "Umbraco.sdf");
|
||||
var path = Path.Combine(GlobalSettings.FullPathToRoot, "App_Data", "Umbraco.sdf");
|
||||
if (File.Exists(path) == false)
|
||||
{
|
||||
// this should probably be in a "using (new SqlCeEngine)" clause but not sure
|
||||
@@ -488,7 +490,7 @@ namespace Umbraco.Core.Migrations.Install
|
||||
var installedSchemaVersion = schemaResult.DetermineInstalledVersion();
|
||||
|
||||
//If Configuration Status is empty and the determined version is "empty" its a new install - otherwise upgrade the existing
|
||||
if (string.IsNullOrEmpty(GlobalSettings.ConfigurationStatus) && installedSchemaVersion.Equals(new Version(0, 0, 0)))
|
||||
if (string.IsNullOrEmpty(_globalSettings.ConfigurationStatus) && installedSchemaVersion.Equals(new Version(0, 0, 0)))
|
||||
{
|
||||
if (_runtime.Level == RuntimeLevel.Run)
|
||||
throw new Exception("Umbraco is already configured!");
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using NPoco;
|
||||
using Umbraco.Core.Persistence;
|
||||
using Umbraco.Core.Persistence.Dtos;
|
||||
using Umbraco.Core.Persistence.SqlSyntax;
|
||||
@@ -216,8 +215,7 @@ namespace Umbraco.Core.Migrations.Upgrade.V_7_7_0
|
||||
var usersWithApps = new Dictionary<int, List<string>>();
|
||||
foreach (var userApps in userAppsData)
|
||||
{
|
||||
List<string> apps;
|
||||
if (usersWithApps.TryGetValue(userApps.id, out apps) == false)
|
||||
if (usersWithApps.TryGetValue(userApps.id, out List<string> apps) == false)
|
||||
{
|
||||
apps = new List<string> {userApps.app};
|
||||
usersWithApps.Add(userApps.id, apps);
|
||||
|
||||
@@ -6,6 +6,7 @@ using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
using Umbraco.Core.Configuration;
|
||||
using Umbraco.Core.Models.Entities;
|
||||
using Umbraco.Core.Models.Membership;
|
||||
using Umbraco.Core.Security;
|
||||
@@ -64,7 +65,7 @@ namespace Umbraco.Core.Models.Identity
|
||||
_startContentIds = new int[] { };
|
||||
_groups = new IReadOnlyUserGroup[] { };
|
||||
_allowedSections = new string[] { };
|
||||
_culture = Configuration.GlobalSettings.DefaultUILanguage;
|
||||
_culture = UmbracoConfig.For.GlobalSettings().DefaultUILanguage; //fixme inject somehow?
|
||||
_groups = new IReadOnlyUserGroup[0];
|
||||
_roles = new ObservableCollection<IdentityUserRole<string>>();
|
||||
_roles.CollectionChanged += _roles_CollectionChanged;
|
||||
@@ -81,7 +82,7 @@ namespace Umbraco.Core.Models.Identity
|
||||
_startContentIds = new int[] { };
|
||||
_groups = new IReadOnlyUserGroup[] { };
|
||||
_allowedSections = new string[] { };
|
||||
_culture = Configuration.GlobalSettings.DefaultUILanguage;
|
||||
_culture = UmbracoConfig.For.GlobalSettings().DefaultUILanguage; //fixme inject somehow?
|
||||
_groups = groups.ToArray();
|
||||
_roles = new ObservableCollection<IdentityUserRole<string>>(_groups.Select(x => new IdentityUserRole<string>
|
||||
{
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using AutoMapper;
|
||||
using Umbraco.Core.Configuration;
|
||||
using Umbraco.Core.Models.Membership;
|
||||
using Umbraco.Core.Security;
|
||||
using Umbraco.Core.Services;
|
||||
@@ -9,7 +10,7 @@ namespace Umbraco.Core.Models.Identity
|
||||
{
|
||||
public class IdentityProfile : Profile
|
||||
{
|
||||
public IdentityProfile(ILocalizedTextService textService, IEntityService entityService)
|
||||
public IdentityProfile(ILocalizedTextService textService, IEntityService entityService, IGlobalSettings globalSettings)
|
||||
{
|
||||
CreateMap<IUser, BackOfficeIdentityUser>()
|
||||
.BeforeMap((src, dest) =>
|
||||
@@ -25,7 +26,7 @@ namespace Umbraco.Core.Models.Identity
|
||||
.ForMember(dest => dest.IsApproved, opt => opt.MapFrom(src => src.IsApproved))
|
||||
.ForMember(dest => dest.UserName, opt => opt.MapFrom(src => src.Username))
|
||||
.ForMember(dest => dest.PasswordHash, opt => opt.MapFrom(user => GetPasswordHash(user.RawPasswordValue)))
|
||||
.ForMember(dest => dest.Culture, opt => opt.MapFrom(src => src.GetUserCulture(textService)))
|
||||
.ForMember(dest => dest.Culture, opt => opt.MapFrom(src => src.GetUserCulture(textService, globalSettings)))
|
||||
.ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Name))
|
||||
.ForMember(dest => dest.StartMediaIds, opt => opt.MapFrom(src => src.StartMediaIds))
|
||||
.ForMember(dest => dest.StartContentIds, opt => opt.MapFrom(src => src.StartContentIds))
|
||||
|
||||
@@ -27,7 +27,7 @@ namespace Umbraco.Core.Models.Membership
|
||||
{
|
||||
SessionTimeout = 60;
|
||||
_userGroups = new HashSet<IReadOnlyUserGroup>();
|
||||
_language = GlobalSettings.DefaultUILanguage;
|
||||
_language = UmbracoConfig.For.GlobalSettings().DefaultUILanguage; //fixme inject somehow?
|
||||
_isApproved = true;
|
||||
_isLockedOut = false;
|
||||
_startContentIds = new int[] { };
|
||||
|
||||
@@ -126,15 +126,16 @@ namespace Umbraco.Core.Models
|
||||
/// </summary>
|
||||
/// <param name="user"></param>
|
||||
/// <param name="textService"></param>
|
||||
/// <param name="globalSettings"></param>
|
||||
/// <returns></returns>
|
||||
public static CultureInfo GetUserCulture(this IUser user, ILocalizedTextService textService)
|
||||
public static CultureInfo GetUserCulture(this IUser user, ILocalizedTextService textService, IGlobalSettings globalSettings)
|
||||
{
|
||||
if (user == null) throw new ArgumentNullException(nameof(user));
|
||||
if (textService == null) throw new ArgumentNullException(nameof(textService));
|
||||
return GetUserCulture(user.Language, textService);
|
||||
return GetUserCulture(user.Language, textService, globalSettings);
|
||||
}
|
||||
|
||||
internal static CultureInfo GetUserCulture(string userLanguage, ILocalizedTextService textService)
|
||||
internal static CultureInfo GetUserCulture(string userLanguage, ILocalizedTextService textService, IGlobalSettings globalSettings)
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -148,7 +149,7 @@ namespace Umbraco.Core.Models
|
||||
catch (CultureNotFoundException)
|
||||
{
|
||||
//return the default one
|
||||
return CultureInfo.GetCultureInfo(GlobalSettings.DefaultUILanguage);
|
||||
return CultureInfo.GetCultureInfo(globalSettings.DefaultUILanguage);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ namespace Umbraco.Core.Packaging
|
||||
|
||||
public PackageInstallation(IPackagingService packagingService, IMacroService macroService,
|
||||
IFileService fileService, IPackageExtraction packageExtraction)
|
||||
: this(packagingService, macroService, fileService, packageExtraction, GlobalSettings.FullpathToRoot)
|
||||
: this(packagingService, macroService, fileService, packageExtraction, GlobalSettings.FullPathToRoot)
|
||||
{}
|
||||
|
||||
public PackageInstallation(IPackagingService packagingService, IMacroService macroService,
|
||||
|
||||
@@ -27,29 +27,33 @@ namespace Umbraco.Core.Persistence.Repositories.Implement
|
||||
internal class UserRepository : NPocoRepositoryBase<int, IUser>, IUserRepository
|
||||
{
|
||||
private readonly IMapperCollection _mapperCollection;
|
||||
private readonly IGlobalSettings _globalSettings;
|
||||
private string _passwordConfigJson;
|
||||
private bool _passwordConfigInitialized;
|
||||
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
/// <param name="work"></param>
|
||||
/// <param name="scopeAccessor"></param>
|
||||
/// <param name="cacheHelper"></param>
|
||||
/// <param name="logger"></param>
|
||||
/// <param name="passwordConfig">
|
||||
/// <param name="mapperCollection">
|
||||
/// A dictionary specifying the configuration for user passwords. If this is null then no password configuration will be persisted or read.
|
||||
/// </param>
|
||||
public UserRepository(IScopeAccessor scopeAccessor, CacheHelper cacheHelper, ILogger logger, IMapperCollection mapperCollection)
|
||||
/// <param name="globalSettings"></param>
|
||||
public UserRepository(IScopeAccessor scopeAccessor, CacheHelper cacheHelper, ILogger logger, IMapperCollection mapperCollection, IGlobalSettings globalSettings)
|
||||
: base(scopeAccessor, cacheHelper, logger)
|
||||
{
|
||||
_mapperCollection = mapperCollection;
|
||||
_globalSettings = globalSettings;
|
||||
}
|
||||
|
||||
// for tests
|
||||
internal UserRepository(IScopeAccessor scopeAccessor, CacheHelper cacheHelper, ILogger logger, IMapperCollection mapperCollection, IDictionary<string, string> passwordConfig)
|
||||
internal UserRepository(IScopeAccessor scopeAccessor, CacheHelper cacheHelper, ILogger logger, IMapperCollection mapperCollection, IDictionary<string, string> passwordConfig, IGlobalSettings globalSettings)
|
||||
: base(scopeAccessor, cacheHelper, logger)
|
||||
{
|
||||
_mapperCollection = mapperCollection;
|
||||
_globalSettings = globalSettings;
|
||||
_passwordConfigJson = JsonConvert.SerializeObject(passwordConfig);
|
||||
_passwordConfigInitialized = true;
|
||||
}
|
||||
@@ -192,7 +196,7 @@ ORDER BY colName";
|
||||
return false;
|
||||
|
||||
//now detect if there's been a timeout
|
||||
if (DateTime.UtcNow - found.LastValidatedUtc > TimeSpan.FromMinutes(GlobalSettings.TimeOutInMinutes))
|
||||
if (DateTime.UtcNow - found.LastValidatedUtc > TimeSpan.FromMinutes(_globalSettings.TimeOutInMinutes))
|
||||
{
|
||||
//timeout detected, update the record
|
||||
ClearLoginSession(sessionId);
|
||||
|
||||
@@ -7,6 +7,7 @@ using LightInject;
|
||||
using Umbraco.Core.Cache;
|
||||
using Umbraco.Core.Components;
|
||||
using Umbraco.Core.Composing;
|
||||
using Umbraco.Core.Composing.CompositionRoots;
|
||||
using Umbraco.Core.Configuration;
|
||||
using Umbraco.Core.Exceptions;
|
||||
using Umbraco.Core.IO;
|
||||
@@ -194,6 +195,8 @@ namespace Umbraco.Core.Runtime
|
||||
container.RegisterSingleton<ProfilingLogger>();
|
||||
container.RegisterSingleton<IRuntimeState, RuntimeState>();
|
||||
|
||||
container.RegisterFrom<ConfigurationCompositionRoot>();
|
||||
|
||||
// register caches
|
||||
// need the deep clone runtime cache profiver to ensure entities are cached properly, ie
|
||||
// are cloned in and cloned out - no request-based cache here since no web-based context,
|
||||
@@ -206,7 +209,7 @@ namespace Umbraco.Core.Runtime
|
||||
container.RegisterSingleton(f => f.GetInstance<CacheHelper>().RuntimeCache);
|
||||
|
||||
// register the plugin manager
|
||||
container.RegisterSingleton(f => new TypeLoader(f.GetInstance<IRuntimeCacheProvider>(), f.GetInstance<ProfilingLogger>()));
|
||||
container.RegisterSingleton(f => new TypeLoader(f.GetInstance<IRuntimeCacheProvider>(), f.GetInstance<IGlobalSettings>(), f.GetInstance<ProfilingLogger>()));
|
||||
|
||||
// register syntax providers - required by database factory
|
||||
container.Register<ISqlSyntaxProvider, MySqlSyntaxProvider>("MySqlSyntaxProvider");
|
||||
|
||||
@@ -35,7 +35,6 @@ namespace Umbraco.Core.Runtime
|
||||
base.Compose(composition);
|
||||
|
||||
// register from roots
|
||||
composition.Container.RegisterFrom<ConfigurationCompositionRoot>();
|
||||
composition.Container.RegisterFrom<RepositoryCompositionRoot>();
|
||||
composition.Container.RegisterFrom<ServicesCompositionRoot>();
|
||||
composition.Container.RegisterFrom<CoreMappingProfilesCompositionRoot>();
|
||||
@@ -78,7 +77,7 @@ namespace Umbraco.Core.Runtime
|
||||
composition.Container.RegisterSingleton<IServerRegistrar>(f =>
|
||||
{
|
||||
if (UmbracoConfig.For.UmbracoSettings().DistributedCall.Enabled)
|
||||
return new ConfigServerRegistrar(UmbracoConfig.For.UmbracoSettings(), f.GetInstance<ILogger>());
|
||||
return new ConfigServerRegistrar(f.GetInstance<IUmbracoSettingsSection>(), f.GetInstance<ILogger>(), f.GetInstance<IGlobalSettings>());
|
||||
if ("true".InvariantEquals(ConfigurationManager.AppSettings["umbracoDisableElectionForSingleServer"]))
|
||||
return new SingleServerRegistrar(f.GetInstance<IRuntimeState>());
|
||||
return new DatabaseServerRegistrar(
|
||||
@@ -94,8 +93,8 @@ namespace Umbraco.Core.Runtime
|
||||
factory.GetInstance<IRuntimeState>(),
|
||||
factory.GetInstance<IScopeProvider>(),
|
||||
factory.GetInstance<ISqlContext>(),
|
||||
factory.GetInstance<ILogger>(),
|
||||
factory.GetInstance<ProfilingLogger>(),
|
||||
factory.GetInstance<IGlobalSettings>(),
|
||||
true, new DatabaseServerMessengerOptions()));
|
||||
|
||||
composition.Container.RegisterCollectionBuilder<CacheRefresherCollectionBuilder>()
|
||||
|
||||
@@ -103,14 +103,15 @@ namespace Umbraco.Core
|
||||
/// <summary>
|
||||
/// Ensures that the <see cref="ApplicationUrl"/> property has a value.
|
||||
/// </summary>
|
||||
/// <param name="globalSettings"></param>
|
||||
/// <param name="request"></param>
|
||||
/// <param name="settings"></param>
|
||||
internal void EnsureApplicationUrl(HttpRequestBase request = null, IUmbracoSettingsSection settings = null)
|
||||
internal void EnsureApplicationUrl(IUmbracoSettingsSection settings, IGlobalSettings globalSettings, HttpRequestBase request = null)
|
||||
{
|
||||
// see U4-10626 - in some cases we want to reset the application url
|
||||
// (this is a simplified version of what was in 7.x)
|
||||
// note: should this be optional? is it expensive?
|
||||
var url = request == null ? null : ApplicationUrlHelper.GetApplicationUrlFromCurrentRequest(request);
|
||||
var url = request == null ? null : ApplicationUrlHelper.GetApplicationUrlFromCurrentRequest(request, globalSettings);
|
||||
var change = url != null && !_applicationUrls.Contains(url);
|
||||
if (change)
|
||||
{
|
||||
@@ -119,7 +120,7 @@ namespace Umbraco.Core
|
||||
}
|
||||
|
||||
if (ApplicationUrl != null && !change) return;
|
||||
ApplicationUrl = new Uri(ApplicationUrlHelper.GetApplicationUrl(_logger, request, settings));
|
||||
ApplicationUrl = new Uri(ApplicationUrlHelper.GetApplicationUrl(_logger, globalSettings, settings, request));
|
||||
}
|
||||
|
||||
private readonly ManualResetEventSlim _runLevel = new ManualResetEventSlim(false);
|
||||
|
||||
@@ -1,445 +1,67 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Specialized;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Security.Claims;
|
||||
using System.Security.Principal;
|
||||
using System.Threading;
|
||||
using System.Web;
|
||||
using System.Web.Security;
|
||||
using Microsoft.AspNet.Identity;
|
||||
using AutoMapper;
|
||||
using Microsoft.Owin;
|
||||
using Newtonsoft.Json;
|
||||
using Umbraco.Core.Configuration;
|
||||
using Umbraco.Core.Composing;
|
||||
using Umbraco.Core.Models.Membership;
|
||||
using Umbraco.Core.Logging;
|
||||
using IUser = Umbraco.Core.Models.Membership.IUser;
|
||||
|
||||
namespace Umbraco.Core.Security
|
||||
{
|
||||
/// <summary>
|
||||
/// Extensions to create and renew and remove authentication tickets for the Umbraco back office
|
||||
/// </summary>
|
||||
public static class AuthenticationExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// This will check the ticket to see if it is valid, if it is it will set the current thread's user and culture
|
||||
/// </summary>
|
||||
/// <param name="http"></param>
|
||||
/// <param name="ticket"></param>
|
||||
/// <param name="renewTicket">If true will attempt to renew the ticket</param>
|
||||
public static bool AuthenticateCurrentRequest(this HttpContextBase http, FormsAuthenticationTicket ticket, bool renewTicket)
|
||||
{
|
||||
if (http == null) throw new ArgumentNullException("http");
|
||||
|
||||
//if there was a ticket, it's not expired, - it should not be renewed or its renewable
|
||||
if (ticket != null && ticket.Expired == false && (renewTicket == false || http.RenewUmbracoAuthTicket()))
|
||||
{
|
||||
try
|
||||
{
|
||||
//create the Umbraco user identity
|
||||
var identity = new UmbracoBackOfficeIdentity(ticket);
|
||||
|
||||
//set the principal object
|
||||
var principal = new GenericPrincipal(identity, identity.Roles);
|
||||
|
||||
//It is actually not good enough to set this on the current app Context and the thread, it also needs
|
||||
// to be set explicitly on the HttpContext.Current !! This is a strange web api thing that is actually
|
||||
// an underlying fault of asp.net not propogating the User correctly.
|
||||
if (HttpContext.Current != null)
|
||||
{
|
||||
HttpContext.Current.User = principal;
|
||||
}
|
||||
http.User = principal;
|
||||
Thread.CurrentPrincipal = principal;
|
||||
|
||||
//This is a back office request, we will also set the culture/ui culture
|
||||
Thread.CurrentThread.CurrentCulture =
|
||||
Thread.CurrentThread.CurrentUICulture =
|
||||
new System.Globalization.CultureInfo(identity.Culture);
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (ex is FormatException || ex is JsonReaderException)
|
||||
{
|
||||
//this will occur if the cookie data is invalid
|
||||
http.UmbracoLogout();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This will return the current back office identity if the IPrincipal is the correct type
|
||||
/// </summary>
|
||||
/// <param name="user"></param>
|
||||
/// <returns></returns>
|
||||
internal static UmbracoBackOfficeIdentity GetUmbracoIdentity(this IPrincipal user)
|
||||
{
|
||||
//If it's already a UmbracoBackOfficeIdentity
|
||||
var backOfficeIdentity = user.Identity as UmbracoBackOfficeIdentity;
|
||||
if (backOfficeIdentity != null) return backOfficeIdentity;
|
||||
|
||||
//Check if there's more than one identity assigned and see if it's a UmbracoBackOfficeIdentity and use that
|
||||
var claimsPrincipal = user as ClaimsPrincipal;
|
||||
if (claimsPrincipal != null)
|
||||
{
|
||||
backOfficeIdentity = claimsPrincipal.Identities.OfType<UmbracoBackOfficeIdentity>().FirstOrDefault();
|
||||
if (backOfficeIdentity != null) return backOfficeIdentity;
|
||||
}
|
||||
|
||||
//Otherwise convert to a UmbracoBackOfficeIdentity if it's auth'd and has the back office session
|
||||
var claimsIdentity = user.Identity as ClaimsIdentity;
|
||||
if (claimsIdentity != null && claimsIdentity.IsAuthenticated && claimsIdentity.HasClaim(x => x.Type == Constants.Security.SessionIdClaimType))
|
||||
{
|
||||
try
|
||||
{
|
||||
return UmbracoBackOfficeIdentity.FromClaimsIdentity(claimsIdentity);
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This will return the current back office identity.
|
||||
/// </summary>
|
||||
/// <param name="http"></param>
|
||||
/// <param name="authenticateRequestIfNotFound">
|
||||
/// If set to true and a back office identity is not found and not authenticated, this will attempt to authenticate the
|
||||
/// request just as is done in the Umbraco module and then set the current identity if it is valid.
|
||||
/// Just like in the UmbracoModule, if this is true then the user's culture will be assigned to the request.
|
||||
/// </param>
|
||||
/// <returns>
|
||||
/// Returns the current back office identity if an admin is authenticated otherwise null
|
||||
/// </returns>
|
||||
public static UmbracoBackOfficeIdentity GetCurrentIdentity(this HttpContextBase http, bool authenticateRequestIfNotFound)
|
||||
{
|
||||
if (http == null) throw new ArgumentNullException("http");
|
||||
if (http.User == null) return null; //there's no user at all so no identity
|
||||
|
||||
//If it's already a UmbracoBackOfficeIdentity
|
||||
var backOfficeIdentity = GetUmbracoIdentity(http.User);
|
||||
if (backOfficeIdentity != null) return backOfficeIdentity;
|
||||
|
||||
if (authenticateRequestIfNotFound == false) return null;
|
||||
|
||||
//even if authenticateRequestIfNotFound is true we cannot continue if the request is actually authenticated
|
||||
// which would mean something strange is going on that it is not an umbraco identity.
|
||||
if (http.User.Identity.IsAuthenticated) return null;
|
||||
|
||||
//So the user is not authed but we've been asked to do the auth if authenticateRequestIfNotFound = true,
|
||||
// which might occur in old webforms style things or for routes that aren't included as a back office request.
|
||||
// in this case, we are just reverting to authing using the cookie.
|
||||
|
||||
// TODO: Even though this is in theory legacy, we have legacy bits laying around and we'd need to do the auth based on
|
||||
// how the Module will eventually do it (by calling in to any registered authenticators).
|
||||
|
||||
var ticket = http.GetUmbracoAuthTicket();
|
||||
if (http.AuthenticateCurrentRequest(ticket, true))
|
||||
{
|
||||
//now we 'should have an umbraco identity
|
||||
return http.User.Identity as UmbracoBackOfficeIdentity;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This will return the current back office identity.
|
||||
/// </summary>
|
||||
/// <param name="http"></param>
|
||||
/// <param name="authenticateRequestIfNotFound">
|
||||
/// If set to true and a back office identity is not found and not authenticated, this will attempt to authenticate the
|
||||
/// request just as is done in the Umbraco module and then set the current identity if it is valid
|
||||
/// </param>
|
||||
/// <returns>
|
||||
/// Returns the current back office identity if an admin is authenticated otherwise null
|
||||
/// </returns>
|
||||
internal static UmbracoBackOfficeIdentity GetCurrentIdentity(this HttpContext http, bool authenticateRequestIfNotFound)
|
||||
{
|
||||
if (http == null) throw new ArgumentNullException("http");
|
||||
return new HttpContextWrapper(http).GetCurrentIdentity(authenticateRequestIfNotFound);
|
||||
}
|
||||
|
||||
public static void UmbracoLogout(this HttpContextBase http)
|
||||
{
|
||||
if (http == null) throw new ArgumentNullException("http");
|
||||
Logout(http, UmbracoConfig.For.UmbracoSettings().Security.AuthCookieName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This clears the forms authentication cookie
|
||||
/// </summary>
|
||||
/// <param name="http"></param>
|
||||
internal static void UmbracoLogout(this HttpContext http)
|
||||
{
|
||||
if (http == null) throw new ArgumentNullException("http");
|
||||
new HttpContextWrapper(http).UmbracoLogout();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This will force ticket renewal in the OWIN pipeline
|
||||
/// </summary>
|
||||
/// <param name="http"></param>
|
||||
/// <returns></returns>
|
||||
public static bool RenewUmbracoAuthTicket(this HttpContextBase http)
|
||||
{
|
||||
if (http == null) throw new ArgumentNullException("http");
|
||||
http.Items[Constants.Security.ForceReAuthFlag] = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This will force ticket renewal in the OWIN pipeline
|
||||
/// </summary>
|
||||
/// <param name="http"></param>
|
||||
/// <returns></returns>
|
||||
internal static bool RenewUmbracoAuthTicket(this HttpContext http)
|
||||
{
|
||||
if (http == null) throw new ArgumentNullException("http");
|
||||
http.Items[Constants.Security.ForceReAuthFlag] = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the umbraco authentication ticket
|
||||
/// </summary>
|
||||
/// <param name="http"></param>
|
||||
/// <param name="userdata"></param>
|
||||
public static FormsAuthenticationTicket CreateUmbracoAuthTicket(this HttpContextBase http, UserData userdata)
|
||||
{
|
||||
//ONLY used by BasePage.doLogin!
|
||||
|
||||
if (http == null) throw new ArgumentNullException("http");
|
||||
if (userdata == null) throw new ArgumentNullException("userdata");
|
||||
|
||||
var userDataString = JsonConvert.SerializeObject(userdata);
|
||||
return CreateAuthTicketAndCookie(
|
||||
http,
|
||||
userdata.Username,
|
||||
userDataString,
|
||||
//use the configuration timeout - this is the same timeout that will be used when renewing the ticket.
|
||||
GlobalSettings.TimeOutInMinutes,
|
||||
//Umbraco has always persisted it's original cookie for 1 day so we'll keep it that way
|
||||
1440,
|
||||
UmbracoConfig.For.UmbracoSettings().Security.AuthCookieName,
|
||||
UmbracoConfig.For.UmbracoSettings().Security.AuthCookieDomain);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// returns the number of seconds the user has until their auth session times out
|
||||
/// </summary>
|
||||
/// <param name="http"></param>
|
||||
/// <returns></returns>
|
||||
public static double GetRemainingAuthSeconds(this HttpContextBase http)
|
||||
{
|
||||
if (http == null) throw new ArgumentNullException("http");
|
||||
var ticket = http.GetUmbracoAuthTicket();
|
||||
return ticket.GetRemainingAuthSeconds();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// returns the number of seconds the user has until their auth session times out
|
||||
/// </summary>
|
||||
/// <param name="ticket"></param>
|
||||
/// <returns></returns>
|
||||
public static double GetRemainingAuthSeconds(this FormsAuthenticationTicket ticket)
|
||||
{
|
||||
if (ticket == null)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
var utcExpired = ticket.Expiration.ToUniversalTime();
|
||||
var secondsRemaining = utcExpired.Subtract(DateTime.UtcNow).TotalSeconds;
|
||||
return secondsRemaining;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the umbraco auth ticket
|
||||
/// </summary>
|
||||
/// <param name="http"></param>
|
||||
/// <returns></returns>
|
||||
public static FormsAuthenticationTicket GetUmbracoAuthTicket(this HttpContextBase http)
|
||||
{
|
||||
if (http == null) throw new ArgumentNullException("http");
|
||||
return GetAuthTicket(http, UmbracoConfig.For.UmbracoSettings().Security.AuthCookieName);
|
||||
}
|
||||
|
||||
internal static FormsAuthenticationTicket GetUmbracoAuthTicket(this HttpContext http)
|
||||
{
|
||||
if (http == null) throw new ArgumentNullException("http");
|
||||
return new HttpContextWrapper(http).GetUmbracoAuthTicket();
|
||||
}
|
||||
|
||||
internal static FormsAuthenticationTicket GetUmbracoAuthTicket(this IOwinContext ctx)
|
||||
{
|
||||
if (ctx == null) throw new ArgumentNullException("ctx");
|
||||
//get the ticket
|
||||
try
|
||||
{
|
||||
return GetAuthTicket(ctx.Request.Cookies.ToDictionary(x => x.Key, x => x.Value), UmbracoConfig.For.UmbracoSettings().Security.AuthCookieName);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
ctx.Authentication.SignOut(
|
||||
Constants.Security.BackOfficeAuthenticationType,
|
||||
Constants.Security.BackOfficeExternalAuthenticationType);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This clears the forms authentication cookie
|
||||
/// </summary>
|
||||
/// <param name="http"></param>
|
||||
/// <param name="cookieName"></param>
|
||||
private static void Logout(this HttpContextBase http, string cookieName)
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using System.Security.Principal;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Umbraco.Core.Security
|
||||
{
|
||||
public static class AuthenticationExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// This will return the current back office identity if the IPrincipal is the correct type
|
||||
/// </summary>
|
||||
/// <param name="user"></param>
|
||||
/// <returns></returns>
|
||||
internal static UmbracoBackOfficeIdentity GetUmbracoIdentity(this IPrincipal user)
|
||||
{
|
||||
//We need to clear the sessionId from the database. This is legacy code to do any logging out and shouldn't really be used at all but in any case
|
||||
//we need to make sure the session is cleared. Due to the legacy nature of this it means we need to use singletons
|
||||
if (http.User != null)
|
||||
{
|
||||
var claimsIdentity = http.User.Identity as ClaimsIdentity;
|
||||
if (claimsIdentity != null)
|
||||
{
|
||||
var sessionId = claimsIdentity.FindFirstValue(Constants.Security.SessionIdClaimType);
|
||||
Guid guidSession;
|
||||
if (sessionId.IsNullOrWhiteSpace() == false && Guid.TryParse(sessionId, out guidSession))
|
||||
{
|
||||
Current.Services.UserService.ClearLoginSession(guidSession);
|
||||
}
|
||||
//If it's already a UmbracoBackOfficeIdentity
|
||||
if (user.Identity is UmbracoBackOfficeIdentity backOfficeIdentity) return backOfficeIdentity;
|
||||
|
||||
//Check if there's more than one identity assigned and see if it's a UmbracoBackOfficeIdentity and use that
|
||||
if (user is ClaimsPrincipal claimsPrincipal)
|
||||
{
|
||||
backOfficeIdentity = claimsPrincipal.Identities.OfType<UmbracoBackOfficeIdentity>().FirstOrDefault();
|
||||
if (backOfficeIdentity != null) return backOfficeIdentity;
|
||||
}
|
||||
|
||||
//Otherwise convert to a UmbracoBackOfficeIdentity if it's auth'd and has the back office session
|
||||
if (user.Identity is ClaimsIdentity claimsIdentity && claimsIdentity.IsAuthenticated && claimsIdentity.HasClaim(x => x.Type == Constants.Security.SessionIdClaimType))
|
||||
{
|
||||
try
|
||||
{
|
||||
return UmbracoBackOfficeIdentity.FromClaimsIdentity(claimsIdentity);
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
if (http == null) throw new ArgumentNullException("http");
|
||||
//clear the preview cookie and external login
|
||||
var cookies = new[] { cookieName, Constants.Web.PreviewCookieName, Constants.Security.BackOfficeExternalCookieName };
|
||||
foreach (var c in cookies)
|
||||
{
|
||||
//remove from the request
|
||||
http.Request.Cookies.Remove(c);
|
||||
|
||||
//expire from the response
|
||||
var formsCookie = http.Response.Cookies[c];
|
||||
if (formsCookie != null)
|
||||
{
|
||||
//this will expire immediately and be removed from the browser
|
||||
formsCookie.Expires = DateTime.Now.AddYears(-1);
|
||||
}
|
||||
else
|
||||
{
|
||||
//ensure there's def an expired cookie
|
||||
http.Response.Cookies.Add(new HttpCookie(c) { Expires = DateTime.Now.AddYears(-1) });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static FormsAuthenticationTicket GetAuthTicket(this HttpContextBase http, string cookieName)
|
||||
{
|
||||
var asDictionary = new Dictionary<string, string>();
|
||||
for (var i = 0; i < http.Request.Cookies.Keys.Count; i++)
|
||||
{
|
||||
var key = http.Request.Cookies.Keys.Get(i);
|
||||
asDictionary[key] = http.Request.Cookies[key].Value;
|
||||
}
|
||||
|
||||
//get the ticket
|
||||
try
|
||||
{
|
||||
|
||||
return GetAuthTicket(asDictionary, cookieName);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
//occurs when decryption fails
|
||||
http.Logout(cookieName);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static FormsAuthenticationTicket GetAuthTicket(IDictionary<string, string> cookies, string cookieName)
|
||||
{
|
||||
if (cookies == null) throw new ArgumentNullException("cookies");
|
||||
|
||||
if (cookies.ContainsKey(cookieName) == false) return null;
|
||||
|
||||
var formsCookie = cookies[cookieName];
|
||||
if (formsCookie == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
//get the ticket
|
||||
return FormsAuthentication.Decrypt(formsCookie);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a custom FormsAuthentication ticket with the data specified
|
||||
/// </summary>
|
||||
/// <param name="http">The HTTP.</param>
|
||||
/// <param name="username">The username.</param>
|
||||
/// <param name="userData">The user data.</param>
|
||||
/// <param name="loginTimeoutMins">The login timeout mins.</param>
|
||||
/// <param name="minutesPersisted">The minutes persisted.</param>
|
||||
/// <param name="cookieName">Name of the cookie.</param>
|
||||
/// <param name="cookieDomain">The cookie domain.</param>
|
||||
private static FormsAuthenticationTicket CreateAuthTicketAndCookie(this HttpContextBase http,
|
||||
string username,
|
||||
string userData,
|
||||
int loginTimeoutMins,
|
||||
int minutesPersisted,
|
||||
string cookieName,
|
||||
string cookieDomain)
|
||||
{
|
||||
if (http == null) throw new ArgumentNullException("http");
|
||||
// Create a new ticket used for authentication
|
||||
var ticket = new FormsAuthenticationTicket(
|
||||
4,
|
||||
username,
|
||||
DateTime.Now,
|
||||
DateTime.Now.AddMinutes(loginTimeoutMins),
|
||||
true,
|
||||
userData,
|
||||
"/"
|
||||
);
|
||||
|
||||
// Encrypt the cookie using the machine key for secure transport
|
||||
var hash = FormsAuthentication.Encrypt(ticket);
|
||||
var cookie = new HttpCookie(
|
||||
cookieName,
|
||||
hash)
|
||||
{
|
||||
Expires = DateTime.Now.AddMinutes(minutesPersisted),
|
||||
Domain = cookieDomain,
|
||||
Path = "/"
|
||||
};
|
||||
|
||||
if (GlobalSettings.UseSSL)
|
||||
cookie.Secure = true;
|
||||
|
||||
//ensure http only, this should only be able to be accessed via the server
|
||||
cookie.HttpOnly = true;
|
||||
|
||||
http.Response.Cookies.Set(cookie);
|
||||
|
||||
return ticket;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ensures that the thread culture is set based on the back office user's culture
|
||||
/// </summary>
|
||||
/// <param name="identity"></param>
|
||||
internal static void EnsureCulture(this IIdentity identity)
|
||||
{
|
||||
if (identity is UmbracoBackOfficeIdentity umbIdentity && umbIdentity.IsAuthenticated)
|
||||
{
|
||||
Thread.CurrentThread.CurrentUICulture =
|
||||
Thread.CurrentThread.CurrentCulture = UserCultures.GetOrAdd(umbIdentity.Culture, s => new CultureInfo(s));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Used so that we aren't creating a new CultureInfo object for every single request
|
||||
/// </summary>
|
||||
private static readonly ConcurrentDictionary<string, CultureInfo> UserCultures = new ConcurrentDictionary<string, CultureInfo>();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.Linq;
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNet.Identity;
|
||||
@@ -25,22 +26,20 @@ namespace Umbraco.Core.Security
|
||||
var baseIdentity = await base.CreateAsync(manager, user, authenticationType);
|
||||
|
||||
var umbracoIdentity = new UmbracoBackOfficeIdentity(baseIdentity,
|
||||
user.Id,
|
||||
user.UserName,
|
||||
user.Name,
|
||||
user.CalculatedContentStartNodeIds,
|
||||
user.CalculatedMediaStartNodeIds,
|
||||
user.Culture,
|
||||
//NOTE - there is no session id assigned here, this is just creating the identity, a session id will be generated when the cookie is written
|
||||
new UserData
|
||||
{
|
||||
Id = user.Id,
|
||||
Username = user.UserName,
|
||||
RealName = user.Name,
|
||||
AllowedApplications = user.AllowedSections,
|
||||
Culture = user.Culture,
|
||||
Roles = user.Roles.Select(x => x.RoleId).ToArray(),
|
||||
StartContentNodes = user.CalculatedContentStartNodeIds,
|
||||
StartMediaNodes = user.CalculatedMediaStartNodeIds,
|
||||
SecurityStamp = user.SecurityStamp
|
||||
});
|
||||
Guid.NewGuid().ToString(),
|
||||
user.SecurityStamp,
|
||||
user.AllowedSections,
|
||||
user.Roles.Select(x => x.RoleId).ToArray());
|
||||
|
||||
return umbracoIdentity;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class BackOfficeClaimsIdentityFactory : BackOfficeClaimsIdentityFactory<BackOfficeIdentityUser>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Globalization;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Security.Claims;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
@@ -15,9 +16,16 @@ namespace Umbraco.Core.Security
|
||||
{
|
||||
public class BackOfficeCookieAuthenticationProvider : CookieAuthenticationProvider
|
||||
{
|
||||
// fixme inject
|
||||
private IUserService UserService => Current.Services.UserService;
|
||||
private IRuntimeState RuntimeState => Current.RuntimeState;
|
||||
private readonly IUserService _userService;
|
||||
private readonly IRuntimeState _runtimeState;
|
||||
private readonly IGlobalSettings _globalSettings;
|
||||
|
||||
public BackOfficeCookieAuthenticationProvider(IUserService userService, IRuntimeState runtimeState, IGlobalSettings globalSettings)
|
||||
{
|
||||
_userService = userService;
|
||||
_runtimeState = runtimeState;
|
||||
_globalSettings = globalSettings;
|
||||
}
|
||||
|
||||
public override void ResponseSignIn(CookieResponseSignInContext context)
|
||||
{
|
||||
@@ -26,12 +34,12 @@ namespace Umbraco.Core.Security
|
||||
//generate a session id and assign it
|
||||
//create a session token - if we are configured and not in an upgrade state then use the db, otherwise just generate one
|
||||
|
||||
var session = RuntimeState.Level == RuntimeLevel.Run
|
||||
? UserService.CreateLoginSession((int)backOfficeIdentity.Id, context.OwinContext.GetCurrentRequestIpAddress())
|
||||
var session = _runtimeState.Level == RuntimeLevel.Run
|
||||
? _userService.CreateLoginSession(backOfficeIdentity.Id, context.OwinContext.GetCurrentRequestIpAddress())
|
||||
: Guid.NewGuid();
|
||||
|
||||
backOfficeIdentity.UserData.SessionId = session.ToString();
|
||||
}
|
||||
backOfficeIdentity.SessionId = session.ToString();
|
||||
}
|
||||
|
||||
base.ResponseSignIn(context);
|
||||
}
|
||||
@@ -45,7 +53,7 @@ namespace Umbraco.Core.Security
|
||||
var sessionId = claimsIdentity.FindFirstValue(Constants.Security.SessionIdClaimType);
|
||||
if (sessionId.IsNullOrWhiteSpace() == false && Guid.TryParse(sessionId, out var guidSession))
|
||||
{
|
||||
UserService.ClearLoginSession(guidSession);
|
||||
_userService.ClearLoginSession(guidSession);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,12 +89,13 @@ namespace Umbraco.Core.Security
|
||||
/// <returns/>
|
||||
public override async Task ValidateIdentity(CookieValidateIdentityContext context)
|
||||
{
|
||||
EnsureCulture(context);
|
||||
//ensure the thread culture is set
|
||||
context?.Identity?.EnsureCulture();
|
||||
|
||||
await EnsureValidSessionId(context);
|
||||
|
||||
await base.ValidateIdentity(context);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ensures that the user has a valid session id
|
||||
@@ -94,26 +103,14 @@ namespace Umbraco.Core.Security
|
||||
/// <remarks>
|
||||
/// So that we are not overloading the database this throttles it's check to every minute
|
||||
/// </remarks>
|
||||
protected virtual async Task EnsureValidSessionId(CookieValidateIdentityContext context)
|
||||
protected virtual async Task EnsureValidSessionId(CookieValidateIdentityContext context)
|
||||
{
|
||||
if (RuntimeState.Level == RuntimeLevel.Run)
|
||||
await SessionIdValidator.ValidateSessionAsync(TimeSpan.FromMinutes(1), context);
|
||||
if (_runtimeState.Level == RuntimeLevel.Run)
|
||||
await SessionIdValidator.ValidateSessionAsync(TimeSpan.FromMinutes(1), context, _globalSettings);
|
||||
}
|
||||
|
||||
private void EnsureCulture(CookieValidateIdentityContext context)
|
||||
{
|
||||
var umbIdentity = context.Identity as UmbracoBackOfficeIdentity;
|
||||
if (umbIdentity != null && umbIdentity.IsAuthenticated)
|
||||
{
|
||||
Thread.CurrentThread.CurrentCulture =
|
||||
Thread.CurrentThread.CurrentUICulture =
|
||||
UserCultures.GetOrAdd(umbIdentity.Culture, s => new CultureInfo(s));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Used so that we aren't creating a new CultureInfo object for every single request
|
||||
/// </summary>
|
||||
private static readonly ConcurrentDictionary<string, CultureInfo> UserCultures = new ConcurrentDictionary<string, CultureInfo>();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,14 +17,16 @@ namespace Umbraco.Core.Security
|
||||
{
|
||||
private readonly ILogger _logger;
|
||||
private readonly IOwinRequest _request;
|
||||
private readonly IGlobalSettings _globalSettings;
|
||||
|
||||
public BackOfficeSignInManager(UserManager<BackOfficeIdentityUser, int> userManager, IAuthenticationManager authenticationManager, ILogger logger, IOwinRequest request)
|
||||
public BackOfficeSignInManager(UserManager<BackOfficeIdentityUser, int> userManager, IAuthenticationManager authenticationManager, ILogger logger, IGlobalSettings globalSettings, IOwinRequest request)
|
||||
: base(userManager, authenticationManager)
|
||||
{
|
||||
if (logger == null) throw new ArgumentNullException("logger");
|
||||
if (request == null) throw new ArgumentNullException("request");
|
||||
_logger = logger;
|
||||
_request = request;
|
||||
_globalSettings = globalSettings;
|
||||
AuthenticationType = Constants.Security.BackOfficeAuthenticationType;
|
||||
}
|
||||
|
||||
@@ -33,12 +35,13 @@ namespace Umbraco.Core.Security
|
||||
return user.GenerateUserIdentityAsync((BackOfficeUserManager<BackOfficeIdentityUser>)UserManager);
|
||||
}
|
||||
|
||||
public static BackOfficeSignInManager Create(IdentityFactoryOptions<BackOfficeSignInManager> options, IOwinContext context, ILogger logger)
|
||||
public static BackOfficeSignInManager Create(IdentityFactoryOptions<BackOfficeSignInManager> options, IOwinContext context, IGlobalSettings globalSettings, ILogger logger)
|
||||
{
|
||||
return new BackOfficeSignInManager(
|
||||
context.GetBackOfficeUserManager(),
|
||||
context.Authentication,
|
||||
logger,
|
||||
globalSettings,
|
||||
context.Request);
|
||||
}
|
||||
|
||||
@@ -55,31 +58,19 @@ namespace Umbraco.Core.Security
|
||||
{
|
||||
case SignInStatus.Success:
|
||||
_logger.WriteCore(TraceEventType.Information, 0,
|
||||
string.Format(
|
||||
"User: {0} logged in from IP address {1}",
|
||||
userName,
|
||||
_request.RemoteIpAddress), null, null);
|
||||
$"User: {userName} logged in from IP address {_request.RemoteIpAddress}", null, null);
|
||||
break;
|
||||
case SignInStatus.LockedOut:
|
||||
_logger.WriteCore(TraceEventType.Information, 0,
|
||||
string.Format(
|
||||
"Login attempt failed for username {0} from IP address {1}, the user is locked",
|
||||
userName,
|
||||
_request.RemoteIpAddress), null, null);
|
||||
$"Login attempt failed for username {userName} from IP address {_request.RemoteIpAddress}, the user is locked", null, null);
|
||||
break;
|
||||
case SignInStatus.RequiresVerification:
|
||||
_logger.WriteCore(TraceEventType.Information, 0,
|
||||
string.Format(
|
||||
"Login attempt requires verification for username {0} from IP address {1}",
|
||||
userName,
|
||||
_request.RemoteIpAddress), null, null);
|
||||
$"Login attempt requires verification for username {userName} from IP address {_request.RemoteIpAddress}", null, null);
|
||||
break;
|
||||
case SignInStatus.Failure:
|
||||
_logger.WriteCore(TraceEventType.Information, 0,
|
||||
string.Format(
|
||||
"Login attempt failed for username {0} from IP address {1}",
|
||||
userName,
|
||||
_request.RemoteIpAddress), null, null);
|
||||
$"Login attempt failed for username {userName} from IP address {_request.RemoteIpAddress}", null, null);
|
||||
break;
|
||||
default:
|
||||
throw new ArgumentOutOfRangeException();
|
||||
@@ -107,7 +98,7 @@ namespace Umbraco.Core.Security
|
||||
|
||||
//if the user is null, create an empty one which can be used for auto-linking
|
||||
if (user == null)
|
||||
user = BackOfficeIdentityUser.CreateNew(userName, null, GlobalSettings.DefaultUILanguage);
|
||||
user = BackOfficeIdentityUser.CreateNew(userName, null, _globalSettings.DefaultUILanguage);
|
||||
|
||||
//check the password for the user, this will allow a developer to auto-link
|
||||
//an account if they have specified an IBackOfficeUserPasswordChecker
|
||||
@@ -202,7 +193,7 @@ namespace Umbraco.Core.Security
|
||||
IsPersistent = isPersistent,
|
||||
AllowRefresh = true,
|
||||
IssuedUtc = nowUtc,
|
||||
ExpiresUtc = nowUtc.AddMinutes(GlobalSettings.TimeOutInMinutes)
|
||||
ExpiresUtc = nowUtc.AddMinutes(_globalSettings.TimeOutInMinutes)
|
||||
}, userIdentity, rememberBrowserIdentity);
|
||||
}
|
||||
else
|
||||
@@ -212,7 +203,7 @@ namespace Umbraco.Core.Security
|
||||
IsPersistent = isPersistent,
|
||||
AllowRefresh = true,
|
||||
IssuedUtc = nowUtc,
|
||||
ExpiresUtc = nowUtc.AddMinutes(GlobalSettings.TimeOutInMinutes)
|
||||
ExpiresUtc = nowUtc.AddMinutes(_globalSettings.TimeOutInMinutes)
|
||||
}, userIdentity);
|
||||
}
|
||||
|
||||
|
||||
@@ -31,16 +31,6 @@ namespace Umbraco.Core.Security
|
||||
{
|
||||
}
|
||||
|
||||
[EditorBrowsable(EditorBrowsableState.Never)]
|
||||
[Obsolete("Use the constructor specifying all dependencies instead")]
|
||||
public BackOfficeUserManager(
|
||||
IUserStore<BackOfficeIdentityUser, int> store,
|
||||
IdentityFactoryOptions<BackOfficeUserManager> options,
|
||||
MembershipProviderBase membershipProvider)
|
||||
: this(store, options, membershipProvider, UmbracoConfig.For.UmbracoSettings().Content)
|
||||
{
|
||||
}
|
||||
|
||||
public BackOfficeUserManager(
|
||||
IUserStore<BackOfficeIdentityUser, int> store,
|
||||
IdentityFactoryOptions<BackOfficeUserManager> options,
|
||||
@@ -64,6 +54,7 @@ namespace Umbraco.Core.Security
|
||||
/// <param name="externalLoginService"></param>
|
||||
/// <param name="membershipProvider"></param>
|
||||
/// <param name="contentSectionConfig"></param>
|
||||
/// <param name="globalSettings"></param>
|
||||
/// <returns></returns>
|
||||
public static BackOfficeUserManager Create(
|
||||
IdentityFactoryOptions<BackOfficeUserManager> options,
|
||||
@@ -72,29 +63,20 @@ namespace Umbraco.Core.Security
|
||||
IEntityService entityService,
|
||||
IExternalLoginService externalLoginService,
|
||||
MembershipProviderBase membershipProvider,
|
||||
IContentSection contentSectionConfig)
|
||||
IContentSection contentSectionConfig,
|
||||
IGlobalSettings globalSettings)
|
||||
{
|
||||
if (options == null) throw new ArgumentNullException("options");
|
||||
if (userService == null) throw new ArgumentNullException("userService");
|
||||
if (memberTypeService == null) throw new ArgumentNullException("memberTypeService");
|
||||
if (externalLoginService == null) throw new ArgumentNullException("externalLoginService");
|
||||
|
||||
var manager = new BackOfficeUserManager(new BackOfficeUserStore(userService, memberTypeService, entityService, externalLoginService, membershipProvider));
|
||||
var manager = new BackOfficeUserManager(
|
||||
new BackOfficeUserStore(userService, memberTypeService, entityService, externalLoginService, globalSettings, membershipProvider));
|
||||
manager.InitUserManager(manager, membershipProvider, contentSectionConfig, options);
|
||||
return manager;
|
||||
}
|
||||
|
||||
[EditorBrowsable(EditorBrowsableState.Never)]
|
||||
[Obsolete("Use the overload specifying all dependencies instead")]
|
||||
public static BackOfficeUserManager Create(
|
||||
IdentityFactoryOptions<BackOfficeUserManager> options,
|
||||
BackOfficeUserStore customUserStore,
|
||||
MembershipProviderBase membershipProvider)
|
||||
{
|
||||
var manager = new BackOfficeUserManager(customUserStore, options, membershipProvider);
|
||||
return manager;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a BackOfficeUserManager instance with all default options and a custom BackOfficeUserManager instance
|
||||
/// </summary>
|
||||
@@ -114,16 +96,6 @@ namespace Umbraco.Core.Security
|
||||
}
|
||||
#endregion
|
||||
|
||||
[EditorBrowsable(EditorBrowsableState.Never)]
|
||||
[Obsolete("Use the overload specifying all dependencies instead")]
|
||||
protected void InitUserManager(
|
||||
BackOfficeUserManager manager,
|
||||
MembershipProviderBase membershipProvider,
|
||||
IdentityFactoryOptions<BackOfficeUserManager> options)
|
||||
{
|
||||
InitUserManager(manager, membershipProvider, UmbracoConfig.For.UmbracoSettings().Content, options);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the user manager with the correct options
|
||||
/// </summary>
|
||||
@@ -154,7 +126,6 @@ namespace Umbraco.Core.Security
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
#region What we support do not currently
|
||||
|
||||
//TODO: We could support this - but a user claims will mostly just be what is in the auth cookie
|
||||
@@ -183,17 +154,7 @@ namespace Umbraco.Core.Security
|
||||
get { return false; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
[EditorBrowsable(EditorBrowsableState.Never)]
|
||||
[Obsolete("Use the overload specifying all dependencies instead")]
|
||||
protected void InitUserManager(
|
||||
BackOfficeUserManager<T> manager,
|
||||
MembershipProviderBase membershipProvider,
|
||||
IDataProtectionProvider dataProtectionProvider)
|
||||
{
|
||||
InitUserManager(manager, membershipProvider, dataProtectionProvider, UmbracoConfig.For.UmbracoSettings().Content);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the user manager with the correct options
|
||||
/// </summary>
|
||||
|
||||
@@ -8,6 +8,7 @@ using System.Web.Security;
|
||||
using AutoMapper;
|
||||
using Microsoft.AspNet.Identity;
|
||||
using Microsoft.Owin;
|
||||
using Umbraco.Core.Configuration;
|
||||
using Umbraco.Core.Exceptions;
|
||||
using Umbraco.Core.Models;
|
||||
using Umbraco.Core.Models.Identity;
|
||||
@@ -38,14 +39,16 @@ namespace Umbraco.Core.Security
|
||||
private readonly IMemberTypeService _memberTypeService;
|
||||
private readonly IEntityService _entityService;
|
||||
private readonly IExternalLoginService _externalLoginService;
|
||||
private readonly IGlobalSettings _globalSettings;
|
||||
private bool _disposed = false;
|
||||
|
||||
public BackOfficeUserStore(IUserService userService, IMemberTypeService memberTypeService, IEntityService entityService, IExternalLoginService externalLoginService, MembershipProviderBase usersMembershipProvider)
|
||||
public BackOfficeUserStore(IUserService userService, IMemberTypeService memberTypeService, IEntityService entityService, IExternalLoginService externalLoginService, IGlobalSettings globalSettings, MembershipProviderBase usersMembershipProvider)
|
||||
{
|
||||
_userService = userService;
|
||||
_memberTypeService = memberTypeService;
|
||||
_entityService = entityService;
|
||||
_externalLoginService = externalLoginService;
|
||||
_globalSettings = globalSettings;
|
||||
if (userService == null) throw new ArgumentNullException("userService");
|
||||
if (usersMembershipProvider == null) throw new ArgumentNullException("usersMembershipProvider");
|
||||
if (externalLoginService == null) throw new ArgumentNullException("externalLoginService");
|
||||
@@ -88,7 +91,7 @@ namespace Umbraco.Core.Security
|
||||
var userEntity = new User(user.Name, user.Email, user.UserName, emptyPasswordValue)
|
||||
{
|
||||
DefaultToLiveEditing = false,
|
||||
Language = user.Culture ?? Configuration.GlobalSettings.DefaultUILanguage,
|
||||
Language = user.Culture ?? _globalSettings.DefaultUILanguage,
|
||||
StartContentIds = user.StartContentIds ?? new int[] { },
|
||||
StartMediaIds = user.StartMediaIds ?? new int[] { },
|
||||
IsLockedOut = user.IsLockedOut,
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
using System.Web;
|
||||
using Microsoft.AspNet.Identity.Owin;
|
||||
using Microsoft.Owin;
|
||||
using Microsoft.Owin.Security;
|
||||
using Umbraco.Core.Models.Identity;
|
||||
|
||||
namespace Umbraco.Core.Security
|
||||
@@ -67,5 +68,7 @@ namespace Umbraco.Core.Security
|
||||
return marker.GetManager(owinContext)
|
||||
?? throw new NullReferenceException($"Could not resolve an instance of {typeof (BackOfficeUserManager<BackOfficeIdentityUser>)} from the {typeof (IOwinContext)}.");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -28,12 +28,12 @@ namespace Umbraco.Core.Security
|
||||
{
|
||||
public const string CookieName = "UMB_UCONTEXT_C";
|
||||
|
||||
public static async Task ValidateSessionAsync(TimeSpan validateInterval, CookieValidateIdentityContext context)
|
||||
public static async Task ValidateSessionAsync(TimeSpan validateInterval, CookieValidateIdentityContext context, IGlobalSettings globalSettings)
|
||||
{
|
||||
if (context.Request.Uri.IsBackOfficeRequest(HttpRuntime.AppDomainAppVirtualPath) == false)
|
||||
if (context.Request.Uri.IsBackOfficeRequest(HttpRuntime.AppDomainAppVirtualPath, globalSettings) == false)
|
||||
return;
|
||||
|
||||
var valid = await ValidateSessionAsync(validateInterval, context.OwinContext, context.Options.CookieManager, context.Options.SystemClock, context.Properties.IssuedUtc, context.Identity);
|
||||
var valid = await ValidateSessionAsync(validateInterval, context.OwinContext, context.Options.CookieManager, context.Options.SystemClock, context.Properties.IssuedUtc, context.Identity, globalSettings);
|
||||
|
||||
if (valid == false)
|
||||
{
|
||||
@@ -48,7 +48,8 @@ namespace Umbraco.Core.Security
|
||||
ICookieManager cookieManager,
|
||||
ISystemClock systemClock,
|
||||
DateTimeOffset? authTicketIssueDate,
|
||||
ClaimsIdentity currentIdentity)
|
||||
ClaimsIdentity currentIdentity,
|
||||
IGlobalSettings globalSettings)
|
||||
{
|
||||
if (owinCtx == null) throw new ArgumentNullException("owinCtx");
|
||||
if (cookieManager == null) throw new ArgumentNullException("cookieManager");
|
||||
@@ -107,7 +108,7 @@ namespace Umbraco.Core.Security
|
||||
new CookieOptions
|
||||
{
|
||||
HttpOnly = true,
|
||||
Secure = GlobalSettings.UseSSL || owinCtx.Request.IsSecure,
|
||||
Secure = globalSettings.UseHttps || owinCtx.Request.IsSecure,
|
||||
Path = "/"
|
||||
});
|
||||
|
||||
@@ -115,4 +116,4 @@ namespace Umbraco.Core.Security
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ using System.Security.Principal;
|
||||
using System.Web;
|
||||
using System.Web.Security;
|
||||
using Microsoft.AspNet.Identity;
|
||||
using Microsoft.Owin.Security;
|
||||
using Newtonsoft.Json;
|
||||
using Umbraco.Core.Configuration;
|
||||
|
||||
@@ -21,10 +22,81 @@ namespace Umbraco.Core.Security
|
||||
/// change over to 'pure' asp.net identity and just inherit from ClaimsIdentity.
|
||||
/// </remarks>
|
||||
[Serializable]
|
||||
public class UmbracoBackOfficeIdentity : FormsIdentity
|
||||
public class UmbracoBackOfficeIdentity : ClaimsIdentity
|
||||
{
|
||||
public static UmbracoBackOfficeIdentity FromClaimsIdentity(ClaimsIdentity identity)
|
||||
{
|
||||
return new UmbracoBackOfficeIdentity(identity);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new UmbracoBackOfficeIdentity
|
||||
/// </summary>
|
||||
/// <param name="userId"></param>
|
||||
/// <param name="username"></param>
|
||||
/// <param name="realName"></param>
|
||||
/// <param name="startContentNodes"></param>
|
||||
/// <param name="startMediaNodes"></param>
|
||||
/// <param name="culture"></param>
|
||||
/// <param name="sessionId"></param>
|
||||
/// <param name="securityStamp"></param>
|
||||
/// <param name="allowedApps"></param>
|
||||
/// <param name="roles"></param>
|
||||
public UmbracoBackOfficeIdentity(int userId, string username, string realName,
|
||||
IEnumerable<int> startContentNodes, IEnumerable<int> startMediaNodes, string culture,
|
||||
string sessionId, string securityStamp, IEnumerable<string> allowedApps, IEnumerable<string> roles)
|
||||
: base(Enumerable.Empty<Claim>(), Constants.Security.BackOfficeAuthenticationType) //this ctor is used to ensure the IsAuthenticated property is true
|
||||
{
|
||||
if (allowedApps == null) throw new ArgumentNullException(nameof(allowedApps));
|
||||
if (string.IsNullOrWhiteSpace(username)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(username));
|
||||
if (string.IsNullOrWhiteSpace(realName)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(realName));
|
||||
if (string.IsNullOrWhiteSpace(culture)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(culture));
|
||||
if (string.IsNullOrWhiteSpace(sessionId)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(sessionId));
|
||||
if (string.IsNullOrWhiteSpace(securityStamp)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(securityStamp));
|
||||
AddRequiredClaims(userId, username, realName, startContentNodes, startMediaNodes, culture, sessionId, securityStamp, allowedApps, roles);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new UmbracoBackOfficeIdentity
|
||||
/// </summary>
|
||||
/// <param name="childIdentity">
|
||||
/// The original identity created by the ClaimsIdentityFactory
|
||||
/// </param>
|
||||
/// <param name="userId"></param>
|
||||
/// <param name="username"></param>
|
||||
/// <param name="realName"></param>
|
||||
/// <param name="startContentNodes"></param>
|
||||
/// <param name="startMediaNodes"></param>
|
||||
/// <param name="culture"></param>
|
||||
/// <param name="sessionId"></param>
|
||||
/// <param name="securityStamp"></param>
|
||||
/// <param name="allowedApps"></param>
|
||||
/// <param name="roles"></param>
|
||||
public UmbracoBackOfficeIdentity(ClaimsIdentity childIdentity,
|
||||
int userId, string username, string realName,
|
||||
IEnumerable<int> startContentNodes, IEnumerable<int> startMediaNodes, string culture,
|
||||
string sessionId, string securityStamp, IEnumerable<string> allowedApps, IEnumerable<string> roles)
|
||||
: base(childIdentity.Claims, Constants.Security.BackOfficeAuthenticationType)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(username)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(username));
|
||||
if (string.IsNullOrWhiteSpace(realName)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(realName));
|
||||
if (string.IsNullOrWhiteSpace(culture)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(culture));
|
||||
if (string.IsNullOrWhiteSpace(sessionId)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(sessionId));
|
||||
if (string.IsNullOrWhiteSpace(securityStamp)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(securityStamp));
|
||||
Actor = childIdentity;
|
||||
AddRequiredClaims(userId, username, realName, startContentNodes, startMediaNodes, culture, sessionId, securityStamp, allowedApps, roles);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create a back office identity based on an existing claims identity
|
||||
/// </summary>
|
||||
/// <param name="identity"></param>
|
||||
private UmbracoBackOfficeIdentity(ClaimsIdentity identity)
|
||||
: base(identity.Claims, Constants.Security.BackOfficeAuthenticationType)
|
||||
{
|
||||
Actor = identity;
|
||||
|
||||
//validate that all claims exist
|
||||
foreach (var t in RequiredBackOfficeIdentityClaimTypes)
|
||||
{
|
||||
//if the identity doesn't have the claim, or the claim value is null
|
||||
@@ -33,145 +105,9 @@ namespace Umbraco.Core.Security
|
||||
throw new InvalidOperationException("Cannot create a " + typeof(UmbracoBackOfficeIdentity) + " from " + typeof(ClaimsIdentity) + " since the required claim " + t + " is missing");
|
||||
}
|
||||
}
|
||||
|
||||
var username = identity.GetUserName();
|
||||
var session = identity.FindFirstValue(Constants.Security.SessionIdClaimType);
|
||||
var securityStamp = identity.FindFirstValue(Microsoft.AspNet.Identity.Constants.DefaultSecurityStampClaimType);
|
||||
var startContentId = identity.FindFirstValue(Constants.Security.StartContentNodeIdClaimType);
|
||||
var startMediaId = identity.FindFirstValue(Constants.Security.StartMediaNodeIdClaimType);
|
||||
|
||||
var culture = identity.FindFirstValue(ClaimTypes.Locality);
|
||||
var id = identity.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
var realName = identity.FindFirstValue(ClaimTypes.GivenName);
|
||||
|
||||
if (username == null || startContentId == null || startMediaId == null
|
||||
|| culture == null || id == null
|
||||
|| realName == null || session == null)
|
||||
throw new InvalidOperationException("Cannot create a " + typeof(UmbracoBackOfficeIdentity) + " from " + typeof(ClaimsIdentity) + " since there are missing required claims");
|
||||
|
||||
int[] startContentIdsAsInt;
|
||||
int[] startMediaIdsAsInt;
|
||||
if (startContentId.DetectIsJson() == false || startMediaId.DetectIsJson() == false)
|
||||
throw new InvalidOperationException("Cannot create a " + typeof(UmbracoBackOfficeIdentity) + " from " + typeof(ClaimsIdentity) + " since the data is not formatted correctly - either content or media start Ids are not JSON");
|
||||
|
||||
try
|
||||
{
|
||||
startContentIdsAsInt = JsonConvert.DeserializeObject<int[]>(startContentId);
|
||||
startMediaIdsAsInt = JsonConvert.DeserializeObject<int[]>(startMediaId);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
throw new InvalidOperationException("Cannot create a " + typeof(UmbracoBackOfficeIdentity) + " from " + typeof(ClaimsIdentity) + " since the data is not formatted correctly - either content or media start Ids could not be parsed as JSON", e);
|
||||
}
|
||||
|
||||
var roles = identity.FindAll(x => x.Type == DefaultRoleClaimType).Select(role => role.Value).ToList();
|
||||
var allowedApps = identity.FindAll(x => x.Type == Constants.Security.AllowedApplicationsClaimType).Select(app => app.Value).ToList();
|
||||
|
||||
var userData = new UserData
|
||||
{
|
||||
SecurityStamp = securityStamp,
|
||||
SessionId = session,
|
||||
AllowedApplications = allowedApps.ToArray(),
|
||||
Culture = culture,
|
||||
Id = id,
|
||||
Roles = roles.ToArray(),
|
||||
Username = username,
|
||||
RealName = realName,
|
||||
StartContentNodes = startContentIdsAsInt,
|
||||
StartMediaNodes = startMediaIdsAsInt
|
||||
};
|
||||
|
||||
return new UmbracoBackOfficeIdentity(identity, userData);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create a back office identity based on user data
|
||||
/// </summary>
|
||||
/// <param name="userdata"></param>
|
||||
public UmbracoBackOfficeIdentity(UserData userdata)
|
||||
//This just creates a temp/fake ticket
|
||||
: base(new FormsAuthenticationTicket(userdata.Username, true, 10))
|
||||
{
|
||||
if (userdata == null) throw new ArgumentNullException("userdata");
|
||||
UserData = userdata;
|
||||
AddUserDataClaims();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create a back office identity based on an existing claims identity
|
||||
/// </summary>
|
||||
/// <param name="claimsIdentity"></param>
|
||||
/// <param name="userdata"></param>
|
||||
public UmbracoBackOfficeIdentity(ClaimsIdentity claimsIdentity, UserData userdata)
|
||||
//This just creates a temp/fake ticket
|
||||
: base(new FormsAuthenticationTicket(userdata.Username, true, 10))
|
||||
{
|
||||
if (claimsIdentity == null) throw new ArgumentNullException("claimsIdentity");
|
||||
if (userdata == null) throw new ArgumentNullException("userdata");
|
||||
|
||||
if (claimsIdentity is FormsIdentity)
|
||||
{
|
||||
//since it's a forms auth ticket, it is from a cookie so add that claim
|
||||
AddClaim(new Claim(ClaimTypes.CookiePath, "/", ClaimValueTypes.String, Issuer, Issuer, this));
|
||||
}
|
||||
|
||||
_currentIssuer = claimsIdentity.AuthenticationType;
|
||||
UserData = userdata;
|
||||
AddExistingClaims(claimsIdentity);
|
||||
Actor = claimsIdentity;
|
||||
AddUserDataClaims();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create a new identity from a forms auth ticket
|
||||
/// </summary>
|
||||
/// <param name="ticket"></param>
|
||||
public UmbracoBackOfficeIdentity(FormsAuthenticationTicket ticket)
|
||||
: base(ticket)
|
||||
{
|
||||
//since it's a forms auth ticket, it is from a cookie so add that claim
|
||||
AddClaim(new Claim(ClaimTypes.CookiePath, "/", ClaimValueTypes.String, Issuer, Issuer, this));
|
||||
|
||||
UserData = JsonConvert.DeserializeObject<UserData>(ticket.UserData);
|
||||
AddUserDataClaims();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Used for cloning
|
||||
/// </summary>
|
||||
/// <param name="identity"></param>
|
||||
private UmbracoBackOfficeIdentity(UmbracoBackOfficeIdentity identity)
|
||||
: base(identity)
|
||||
{
|
||||
if (identity.Actor != null)
|
||||
{
|
||||
_currentIssuer = identity.AuthenticationType;
|
||||
AddExistingClaims(identity);
|
||||
Actor = identity.Clone();
|
||||
}
|
||||
|
||||
UserData = identity.UserData;
|
||||
AddUserDataClaims();
|
||||
}
|
||||
|
||||
public const string Issuer = "UmbracoBackOffice";
|
||||
private readonly string _currentIssuer = Issuer;
|
||||
|
||||
/// <summary>
|
||||
/// Used during ctor to add existing claims from an existing ClaimsIdentity
|
||||
/// </summary>
|
||||
/// <param name="claimsIdentity"></param>
|
||||
private void AddExistingClaims(ClaimsIdentity claimsIdentity)
|
||||
{
|
||||
foreach (var claim in claimsIdentity.Claims)
|
||||
{
|
||||
//In one special case we will replace a claim if it exists already and that is the
|
||||
// Forms auth claim for name which automatically gets added
|
||||
TryRemoveClaim(FindFirst(x => x.Type == claim.Type && x.Issuer == "Forms"));
|
||||
|
||||
AddClaim(claim);
|
||||
}
|
||||
}
|
||||
public const string Issuer = Constants.Security.BackOfficeAuthenticationType;
|
||||
|
||||
/// <summary>
|
||||
/// Returns the required claim types for a back office identity
|
||||
@@ -179,153 +115,125 @@ namespace Umbraco.Core.Security
|
||||
/// <remarks>
|
||||
/// This does not incude the role claim type or allowed apps type since that is a collection and in theory could be empty
|
||||
/// </remarks>
|
||||
public static IEnumerable<string> RequiredBackOfficeIdentityClaimTypes
|
||||
public static IEnumerable<string> RequiredBackOfficeIdentityClaimTypes => new[]
|
||||
{
|
||||
get
|
||||
{
|
||||
return new[]
|
||||
{
|
||||
ClaimTypes.NameIdentifier, //id
|
||||
ClaimTypes.Name, //username
|
||||
ClaimTypes.GivenName,
|
||||
Constants.Security.StartContentNodeIdClaimType,
|
||||
Constants.Security.StartMediaNodeIdClaimType,
|
||||
ClaimTypes.Locality,
|
||||
Constants.Security.SessionIdClaimType,
|
||||
Microsoft.AspNet.Identity.Constants.DefaultSecurityStampClaimType
|
||||
};
|
||||
}
|
||||
}
|
||||
ClaimTypes.NameIdentifier, //id
|
||||
ClaimTypes.Name, //username
|
||||
ClaimTypes.GivenName,
|
||||
Constants.Security.StartContentNodeIdClaimType,
|
||||
Constants.Security.StartMediaNodeIdClaimType,
|
||||
ClaimTypes.Locality,
|
||||
Constants.Security.SessionIdClaimType,
|
||||
Microsoft.AspNet.Identity.Constants.DefaultSecurityStampClaimType
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Adds claims based on the UserData data
|
||||
/// Adds claims based on the ctor data
|
||||
/// </summary>
|
||||
private void AddUserDataClaims()
|
||||
private void AddRequiredClaims(int userId, string username, string realName,
|
||||
IEnumerable<int> startContentNodes, IEnumerable<int> startMediaNodes, string culture,
|
||||
string sessionId, string securityStamp, IEnumerable<string> allowedApps, IEnumerable<string> roles)
|
||||
{
|
||||
//This is the id that 'identity' uses to check for the user id
|
||||
if (HasClaim(x => x.Type == ClaimTypes.NameIdentifier) == false)
|
||||
AddClaim(new Claim(ClaimTypes.NameIdentifier, UserData.Id.ToString(), ClaimValueTypes.Integer32, Issuer, Issuer, this));
|
||||
AddClaim(new Claim(ClaimTypes.NameIdentifier, userId.ToInvariantString(), ClaimValueTypes.Integer32, Issuer, Issuer, this));
|
||||
|
||||
if (HasClaim(x => x.Type == ClaimTypes.Name) == false)
|
||||
AddClaim(new Claim(ClaimTypes.Name, UserData.Username, ClaimValueTypes.String, Issuer, Issuer, this));
|
||||
AddClaim(new Claim(ClaimTypes.Name, username, ClaimValueTypes.String, Issuer, Issuer, this));
|
||||
|
||||
if (HasClaim(x => x.Type == ClaimTypes.GivenName) == false)
|
||||
AddClaim(new Claim(ClaimTypes.GivenName, UserData.RealName, ClaimValueTypes.String, Issuer, Issuer, this));
|
||||
AddClaim(new Claim(ClaimTypes.GivenName, realName, ClaimValueTypes.String, Issuer, Issuer, this));
|
||||
|
||||
if (HasClaim(x => x.Type == Constants.Security.StartContentNodeIdClaimType) == false)
|
||||
AddClaim(new Claim(Constants.Security.StartContentNodeIdClaimType, JsonConvert.SerializeObject(StartContentNodes), ClaimValueTypes.Integer32, Issuer, Issuer, this));
|
||||
if (HasClaim(x => x.Type == Constants.Security.StartContentNodeIdClaimType) == false && startContentNodes != null)
|
||||
{
|
||||
foreach (var startContentNode in startContentNodes)
|
||||
{
|
||||
AddClaim(new Claim(Constants.Security.StartContentNodeIdClaimType, startContentNode.ToInvariantString(), ClaimValueTypes.Integer32, Issuer, Issuer, this));
|
||||
}
|
||||
}
|
||||
|
||||
if (HasClaim(x => x.Type == Constants.Security.StartMediaNodeIdClaimType) == false)
|
||||
AddClaim(new Claim(Constants.Security.StartMediaNodeIdClaimType, JsonConvert.SerializeObject(StartMediaNodes), ClaimValueTypes.Integer32, Issuer, Issuer, this));
|
||||
if (HasClaim(x => x.Type == Constants.Security.StartMediaNodeIdClaimType) == false && startMediaNodes != null)
|
||||
{
|
||||
foreach (var startMediaNode in startMediaNodes)
|
||||
{
|
||||
AddClaim(new Claim(Constants.Security.StartMediaNodeIdClaimType, startMediaNode.ToInvariantString(), ClaimValueTypes.Integer32, Issuer, Issuer, this));
|
||||
}
|
||||
}
|
||||
|
||||
if (HasClaim(x => x.Type == ClaimTypes.Locality) == false)
|
||||
AddClaim(new Claim(ClaimTypes.Locality, Culture, ClaimValueTypes.String, Issuer, Issuer, this));
|
||||
AddClaim(new Claim(ClaimTypes.Locality, culture, ClaimValueTypes.String, Issuer, Issuer, this));
|
||||
|
||||
if (HasClaim(x => x.Type == Constants.Security.SessionIdClaimType) == false && SessionId.IsNullOrWhiteSpace() == false)
|
||||
AddClaim(new Claim(Constants.Security.SessionIdClaimType, SessionId, ClaimValueTypes.String, Issuer, Issuer, this));
|
||||
AddClaim(new Claim(Constants.Security.SessionIdClaimType, sessionId, ClaimValueTypes.String, Issuer, Issuer, this));
|
||||
|
||||
//The security stamp claim is also required... this is because this claim type is hard coded
|
||||
// by the SecurityStampValidator, see: https://katanaproject.codeplex.com/workitem/444
|
||||
if (HasClaim(x => x.Type == Microsoft.AspNet.Identity.Constants.DefaultSecurityStampClaimType) == false)
|
||||
AddClaim(new Claim(Microsoft.AspNet.Identity.Constants.DefaultSecurityStampClaimType, SecurityStamp, ClaimValueTypes.String, Issuer, Issuer, this));
|
||||
AddClaim(new Claim(Microsoft.AspNet.Identity.Constants.DefaultSecurityStampClaimType, securityStamp, ClaimValueTypes.String, Issuer, Issuer, this));
|
||||
|
||||
//Add each app as a separate claim
|
||||
if (HasClaim(x => x.Type == Constants.Security.AllowedApplicationsClaimType) == false)
|
||||
if (HasClaim(x => x.Type == Constants.Security.AllowedApplicationsClaimType) == false && allowedApps != null)
|
||||
{
|
||||
foreach (var application in AllowedApplications)
|
||||
foreach (var application in allowedApps)
|
||||
{
|
||||
AddClaim(new Claim(Constants.Security.AllowedApplicationsClaimType, application, ClaimValueTypes.String, Issuer, Issuer, this));
|
||||
}
|
||||
}
|
||||
|
||||
//Claims are added by the ClaimsIdentityFactory because our UserStore supports roles, however this identity might
|
||||
// not be made with that factory if it was created with a FormsAuthentication ticket so perform the check
|
||||
if (HasClaim(x => x.Type == DefaultRoleClaimType) == false)
|
||||
// not be made with that factory if it was created with a different ticket so perform the check
|
||||
if (HasClaim(x => x.Type == DefaultRoleClaimType) == false && roles != null)
|
||||
{
|
||||
//manually add them based on the UserData
|
||||
foreach (var roleName in UserData.Roles)
|
||||
//manually add them
|
||||
foreach (var roleName in roles)
|
||||
{
|
||||
AddClaim(new Claim(RoleClaimType, roleName, ClaimValueTypes.String, Issuer, Issuer, this));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
protected internal UserData UserData { get; private set; }
|
||||
|
||||
|
||||
/// <inheritdoc />
|
||||
/// <summary>
|
||||
/// Gets the type of authenticated identity.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// The type of authenticated identity. This property always returns "UmbracoBackOffice".
|
||||
/// </returns>
|
||||
public override string AuthenticationType
|
||||
{
|
||||
get { return _currentIssuer; }
|
||||
}
|
||||
public override string AuthenticationType => Issuer;
|
||||
|
||||
public int[] StartContentNodes
|
||||
{
|
||||
get { return UserData.StartContentNodes; }
|
||||
}
|
||||
private int[] _startContentNodes;
|
||||
public int[] StartContentNodes => _startContentNodes ?? (_startContentNodes = FindAll(x => x.Type == Constants.Security.StartContentNodeIdClaimType).Select(app => int.TryParse(app.Value, out var i) ? i : default).Where(x => x != default).ToArray());
|
||||
|
||||
public int[] StartMediaNodes
|
||||
{
|
||||
get { return UserData.StartMediaNodes; }
|
||||
}
|
||||
private int[] _startMediaNodes;
|
||||
public int[] StartMediaNodes => _startMediaNodes ?? (_startMediaNodes = FindAll(x => x.Type == Constants.Security.StartMediaNodeIdClaimType).Select(app => int.TryParse(app.Value, out var i) ? i : default).Where(x => x != default).ToArray());
|
||||
|
||||
public string[] AllowedApplications
|
||||
{
|
||||
get { return UserData.AllowedApplications; }
|
||||
}
|
||||
private string[] _allowedApplications;
|
||||
public string[] AllowedApplications => _allowedApplications ?? (_allowedApplications = FindAll(x => x.Type == Constants.Security.AllowedApplicationsClaimType).Select(app => app.Value).ToArray());
|
||||
|
||||
public object Id
|
||||
{
|
||||
get { return UserData.Id; }
|
||||
}
|
||||
public int Id => int.Parse(this.FindFirstValue(ClaimTypes.NameIdentifier));
|
||||
|
||||
public string RealName
|
||||
{
|
||||
get { return UserData.RealName; }
|
||||
}
|
||||
public string RealName => this.FindFirstValue(ClaimTypes.GivenName);
|
||||
|
||||
public string Username
|
||||
{
|
||||
get { return UserData.Username; }
|
||||
}
|
||||
public string Username => this.GetUserName();
|
||||
|
||||
public string Culture
|
||||
{
|
||||
get { return UserData.Culture; }
|
||||
}
|
||||
public string Culture => this.FindFirstValue(ClaimTypes.Locality);
|
||||
|
||||
public string SessionId
|
||||
{
|
||||
get { return UserData.SessionId; }
|
||||
get => this.FindFirstValue(Constants.Security.SessionIdClaimType);
|
||||
set
|
||||
{
|
||||
var existing = FindFirst(Constants.Security.SessionIdClaimType);
|
||||
if (existing != null)
|
||||
TryRemoveClaim(existing);
|
||||
AddClaim(new Claim(Constants.Security.SessionIdClaimType, value, ClaimValueTypes.String, Issuer, Issuer, this));
|
||||
}
|
||||
}
|
||||
|
||||
public string SecurityStamp
|
||||
{
|
||||
get { return UserData.SecurityStamp; }
|
||||
}
|
||||
|
||||
public string[] Roles
|
||||
{
|
||||
get { return UserData.Roles; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a copy of the current <see cref="T:UmbracoBackOfficeIdentity"/> instance.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A copy of the current <see cref="T:UmbracoBackOfficeIdentity"/> instance.
|
||||
/// </returns>
|
||||
public override ClaimsIdentity Clone()
|
||||
{
|
||||
return new UmbracoBackOfficeIdentity(this);
|
||||
}
|
||||
public string SecurityStamp => this.FindFirstValue(Microsoft.AspNet.Identity.Constants.DefaultSecurityStampClaimType);
|
||||
|
||||
public string[] Roles => this.FindAll(x => x.Type == DefaultRoleClaimType).Select(role => role.Value).ToArray();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,74 +0,0 @@
|
||||
using System;
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace Umbraco.Core.Security
|
||||
{
|
||||
/// <summary>
|
||||
/// Data structure used to store information in the authentication cookie
|
||||
/// </summary>
|
||||
[DataContract(Name = "userData", Namespace = "")]
|
||||
[Serializable]
|
||||
public class UserData
|
||||
{
|
||||
public UserData()
|
||||
{
|
||||
AllowedApplications = new string[] {};
|
||||
Roles = new string[] {};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Use this constructor to create/assign new UserData to the ticket
|
||||
/// </summary>
|
||||
/// <param name="sessionId">
|
||||
/// The current sessionId for the user
|
||||
/// </param>
|
||||
public UserData(string sessionId)
|
||||
{
|
||||
SessionId = sessionId;
|
||||
AllowedApplications = new string[] { };
|
||||
Roles = new string[] { };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the session identifier.
|
||||
/// </summary>
|
||||
[DataMember(Name = "sessionId")]
|
||||
public string SessionId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the security stamp.
|
||||
/// </summary>
|
||||
[DataMember(Name = "securityStamp")]
|
||||
public string SecurityStamp { get; set; }
|
||||
|
||||
[DataMember(Name = "id")]
|
||||
public object Id { get; set; }
|
||||
|
||||
[DataMember(Name = "roles")]
|
||||
public string[] Roles { get; set; }
|
||||
|
||||
[DataMember(Name = "username")]
|
||||
public string Username { get; set; }
|
||||
|
||||
[DataMember(Name = "name")]
|
||||
public string RealName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The start nodes on the UserData object for the auth ticket contains all of the user's start nodes including ones assigned to their user groups
|
||||
/// </summary>
|
||||
[DataMember(Name = "startContent")]
|
||||
public int[] StartContentNodes { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The start nodes on the UserData object for the auth ticket contains all of the user's start nodes including ones assigned to their user groups
|
||||
/// </summary>
|
||||
[DataMember(Name = "startMedia")]
|
||||
public int[] StartMediaNodes { get; set; }
|
||||
|
||||
[DataMember(Name = "allowedApps")]
|
||||
public string[] AllowedApplications { get; set; }
|
||||
|
||||
[DataMember(Name = "culture")]
|
||||
public string Culture { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -25,12 +25,14 @@ namespace Umbraco.Core.Services.Implement
|
||||
private readonly IUserService _userService;
|
||||
private readonly IContentService _contentService;
|
||||
private readonly INotificationsRepository _notificationsRepository;
|
||||
private readonly IGlobalSettings _globalSettings;
|
||||
private readonly ILogger _logger;
|
||||
|
||||
public NotificationService(IScopeProvider provider, IUserService userService, IContentService contentService, ILogger logger,
|
||||
INotificationsRepository notificationsRepository)
|
||||
INotificationsRepository notificationsRepository, IGlobalSettings globalSettings)
|
||||
{
|
||||
_notificationsRepository = notificationsRepository;
|
||||
_globalSettings = globalSettings;
|
||||
_uowProvider = provider ?? throw new ArgumentNullException(nameof(provider));
|
||||
_userService = userService ?? throw new ArgumentNullException(nameof(userService));
|
||||
_contentService = contentService ?? throw new ArgumentNullException(nameof(contentService));
|
||||
@@ -427,7 +429,7 @@ namespace Umbraco.Core.Services.Implement
|
||||
"<tr><td colspan=\"2\" style=\"border-bottom: 1px solid #CCC; font-size: 2px;\"> </td></tr>");
|
||||
}
|
||||
|
||||
string protocol = GlobalSettings.UseSSL ? "https" : "http";
|
||||
string protocol = _globalSettings.UseHttps ? "https" : "http";
|
||||
|
||||
|
||||
string[] subjectVars = {
|
||||
@@ -473,7 +475,7 @@ namespace Umbraco.Core.Services.Implement
|
||||
|
||||
// nh, issue 30724. Due to hardcoded http strings in resource files, we need to check for https replacements here
|
||||
// adding the server name to make sure we don't replace external links
|
||||
if (GlobalSettings.UseSSL && string.IsNullOrEmpty(mail.Body) == false)
|
||||
if (_globalSettings.UseHttps && string.IsNullOrEmpty(mail.Body) == false)
|
||||
{
|
||||
string serverName = http.Request.ServerVariables["SERVER_NAME"];
|
||||
mail.Body = mail.Body.Replace(
|
||||
@@ -484,9 +486,9 @@ namespace Umbraco.Core.Services.Implement
|
||||
return new NotificationRequest(mail, actionName, mailingUser.Name, mailingUser.Email);
|
||||
}
|
||||
|
||||
private static string ReplaceLinks(string text, HttpRequestBase request)
|
||||
private string ReplaceLinks(string text, HttpRequestBase request)
|
||||
{
|
||||
var sb = new StringBuilder(GlobalSettings.UseSSL ? "https://" : "http://");
|
||||
var sb = new StringBuilder(_globalSettings.UseHttps ? "https://" : "http://");
|
||||
sb.Append(request.ServerVariables["SERVER_NAME"]);
|
||||
sb.Append(":");
|
||||
sb.Append(request.Url.Port);
|
||||
|
||||
@@ -28,14 +28,16 @@ namespace Umbraco.Core.Services.Implement
|
||||
{
|
||||
private readonly IUserRepository _userRepository;
|
||||
private readonly IUserGroupRepository _userGroupRepository;
|
||||
private readonly IGlobalSettings _globalSettings;
|
||||
private readonly bool _isUpgrading;
|
||||
|
||||
public UserService(IScopeProvider provider, ILogger logger, IEventMessagesFactory eventMessagesFactory, IRuntimeState runtimeState,
|
||||
IUserRepository userRepository, IUserGroupRepository userGroupRepository)
|
||||
IUserRepository userRepository, IUserGroupRepository userGroupRepository, IGlobalSettings globalSettings)
|
||||
: base(provider, logger, eventMessagesFactory)
|
||||
{
|
||||
_userRepository = userRepository;
|
||||
_userGroupRepository = userGroupRepository;
|
||||
_globalSettings = globalSettings;
|
||||
_isUpgrading = runtimeState.Level == RuntimeLevel.Install || runtimeState.Level == RuntimeLevel.Upgrade;
|
||||
}
|
||||
|
||||
@@ -120,7 +122,7 @@ namespace Umbraco.Core.Services.Implement
|
||||
{
|
||||
DefaultToLiveEditing = false,
|
||||
Email = email,
|
||||
Language = GlobalSettings.DefaultUILanguage,
|
||||
Language = _globalSettings.DefaultUILanguage,
|
||||
Name = username,
|
||||
RawPasswordValue = passwordValue,
|
||||
Username = username,
|
||||
|
||||
@@ -29,9 +29,9 @@ namespace Umbraco.Core.Sync
|
||||
// FIXME need another way to do it, eg an interface, injected!
|
||||
public static Func<HttpRequestBase, string> ApplicationUrlProvider { get; set; }
|
||||
|
||||
internal static string GetApplicationUrl(ILogger logger, HttpRequestBase request = null, IUmbracoSettingsSection settings = null)
|
||||
internal static string GetApplicationUrl(ILogger logger, IGlobalSettings globalSettings, IUmbracoSettingsSection settings, HttpRequestBase request = null)
|
||||
{
|
||||
var umbracoApplicationUrl = TryGetApplicationUrl(settings ?? UmbracoConfig.For.UmbracoSettings(), logger);
|
||||
var umbracoApplicationUrl = TryGetApplicationUrl(settings, logger, globalSettings);
|
||||
if (umbracoApplicationUrl != null)
|
||||
return umbracoApplicationUrl;
|
||||
|
||||
@@ -45,12 +45,12 @@ namespace Umbraco.Core.Sync
|
||||
|
||||
if (request == null) return null;
|
||||
|
||||
umbracoApplicationUrl = GetApplicationUrlFromCurrentRequest(request);
|
||||
umbracoApplicationUrl = GetApplicationUrlFromCurrentRequest(request, globalSettings);
|
||||
logger.Info(TypeOfApplicationUrlHelper, "ApplicationUrl: " + umbracoApplicationUrl + " (UmbracoModule request)");
|
||||
return umbracoApplicationUrl;
|
||||
}
|
||||
|
||||
internal static string TryGetApplicationUrl(IUmbracoSettingsSection settings, ILogger logger)
|
||||
internal static string TryGetApplicationUrl(IUmbracoSettingsSection settings, ILogger logger, IGlobalSettings globalSettings)
|
||||
{
|
||||
// try umbracoSettings:settings/web.routing/@umbracoApplicationUrl
|
||||
// which is assumed to:
|
||||
@@ -75,7 +75,7 @@ namespace Umbraco.Core.Sync
|
||||
url = settings.ScheduledTasks.BaseUrl;
|
||||
if (url.IsNullOrWhiteSpace() == false)
|
||||
{
|
||||
var ssl = GlobalSettings.UseSSL ? "s" : "";
|
||||
var ssl = globalSettings.UseHttps ? "s" : "";
|
||||
url = "http" + ssl + "://" + url;
|
||||
var umbracoApplicationUrl = url.TrimEnd('/');
|
||||
logger.Info(TypeOfApplicationUrlHelper, "ApplicationUrl: " + umbracoApplicationUrl + " (using scheduledTasks/@baseUrl)");
|
||||
@@ -100,7 +100,7 @@ namespace Umbraco.Core.Sync
|
||||
return null;
|
||||
}
|
||||
|
||||
public static string GetApplicationUrlFromCurrentRequest(HttpRequestBase request)
|
||||
public static string GetApplicationUrlFromCurrentRequest(HttpRequestBase request, IGlobalSettings globalSettings)
|
||||
{
|
||||
// if (HTTP and SSL not required) or (HTTPS and SSL required),
|
||||
// use ports from request
|
||||
@@ -108,12 +108,12 @@ namespace Umbraco.Core.Sync
|
||||
// if non-standard ports used,
|
||||
// user may need to set umbracoApplicationUrl manually per
|
||||
// http://our.umbraco.org/documentation/Using-Umbraco/Config-files/umbracoSettings/#ScheduledTasks
|
||||
var port = (request.IsSecureConnection == false && GlobalSettings.UseSSL == false)
|
||||
|| (request.IsSecureConnection && GlobalSettings.UseSSL)
|
||||
var port = (request.IsSecureConnection == false && globalSettings.UseHttps == false)
|
||||
|| (request.IsSecureConnection && globalSettings.UseHttps)
|
||||
? ":" + request.ServerVariables["SERVER_PORT"]
|
||||
: "";
|
||||
|
||||
var useSsl = GlobalSettings.UseSSL || port == "443";
|
||||
var useSsl = globalSettings.UseHttps || port == "443";
|
||||
var ssl = useSsl ? "s" : ""; // force, whatever the first request
|
||||
var url = "http" + ssl + "://" + request.ServerVariables["SERVER_NAME"] + port + IOHelper.ResolveUrl(SystemDirectories.Umbraco);
|
||||
|
||||
|
||||
@@ -9,17 +9,17 @@ namespace Umbraco.Core.Sync
|
||||
/// </summary>
|
||||
internal class ConfigServerAddress : IServerAddress
|
||||
{
|
||||
public ConfigServerAddress(IServer n)
|
||||
public ConfigServerAddress(IServer n, IGlobalSettings globalSettings)
|
||||
{
|
||||
var webServicesUrl = IOHelper.ResolveUrl(SystemDirectories.WebServices);
|
||||
|
||||
var protocol = GlobalSettings.UseSSL ? "https" : "http";
|
||||
var protocol = globalSettings.UseHttps ? "https" : "http";
|
||||
if (n.ForceProtocol.IsNullOrWhiteSpace() == false)
|
||||
protocol = n.ForceProtocol;
|
||||
var domain = n.ServerAddress;
|
||||
if (n.ForcePortnumber.IsNullOrWhiteSpace() == false)
|
||||
domain += string.Format(":{0}", n.ForcePortnumber);
|
||||
ServerAddress = string.Format("{0}://{1}{2}/cacheRefresher.asmx", protocol, domain, webServicesUrl);
|
||||
domain += $":{n.ForcePortnumber}";
|
||||
ServerAddress = $"{protocol}://{domain}{webServicesUrl}/cacheRefresher.asmx";
|
||||
}
|
||||
|
||||
public string ServerAddress { get; private set; }
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Web;
|
||||
using Umbraco.Core.Configuration;
|
||||
using Umbraco.Core.Configuration.UmbracoSettings;
|
||||
using Umbraco.Core.IO;
|
||||
using Umbraco.Core.Logging;
|
||||
@@ -17,12 +18,12 @@ namespace Umbraco.Core.Sync
|
||||
private readonly ServerRole _serverRole;
|
||||
private readonly string _umbracoApplicationUrl;
|
||||
|
||||
public ConfigServerRegistrar(IUmbracoSettingsSection settings, ILogger logger)
|
||||
: this(settings.DistributedCall, logger)
|
||||
public ConfigServerRegistrar(IUmbracoSettingsSection settings, ILogger logger, IGlobalSettings globalSettings)
|
||||
: this(settings.DistributedCall, logger, globalSettings)
|
||||
{ }
|
||||
|
||||
// for tests
|
||||
internal ConfigServerRegistrar(IDistributedCallSection settings, ILogger logger)
|
||||
internal ConfigServerRegistrar(IDistributedCallSection settings, ILogger logger, IGlobalSettings globalSettings)
|
||||
{
|
||||
if (settings.Enabled == false)
|
||||
{
|
||||
@@ -35,7 +36,7 @@ namespace Umbraco.Core.Sync
|
||||
var serversA = settings.Servers.ToArray();
|
||||
|
||||
_addresses = serversA
|
||||
.Select(x => new ConfigServerAddress(x))
|
||||
.Select(x => new ConfigServerAddress(x, globalSettings))
|
||||
.Cast<IServerAddress>()
|
||||
.ToList();
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ namespace Umbraco.Core.Sync
|
||||
private readonly object _locko = new object();
|
||||
private readonly ProfilingLogger _profilingLogger;
|
||||
private readonly ISqlContext _sqlContext;
|
||||
private readonly Lazy<string> _distCacheFilePath = new Lazy<string>(GetDistCacheFilePath);
|
||||
private readonly Lazy<string> _distCacheFilePath;
|
||||
private int _lastId = -1;
|
||||
private DateTime _lastSync;
|
||||
private DateTime _lastPruned;
|
||||
@@ -46,18 +46,19 @@ namespace Umbraco.Core.Sync
|
||||
public DatabaseServerMessengerOptions Options { get; }
|
||||
|
||||
public DatabaseServerMessenger(
|
||||
IRuntimeState runtime, IScopeProvider scopeProvider, ISqlContext sqlContext, ILogger logger, ProfilingLogger proflog,
|
||||
IRuntimeState runtime, IScopeProvider scopeProvider, ISqlContext sqlContext, ProfilingLogger proflog, IGlobalSettings globalSettings,
|
||||
bool distributedEnabled, DatabaseServerMessengerOptions options)
|
||||
: base(distributedEnabled)
|
||||
{
|
||||
ScopeProvider = scopeProvider ?? throw new ArgumentNullException(nameof(scopeProvider));
|
||||
Logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
_sqlContext = sqlContext;
|
||||
_runtime = runtime;
|
||||
_profilingLogger = proflog ?? throw new ArgumentNullException(nameof(proflog));
|
||||
Logger = proflog.Logger;
|
||||
Options = options ?? throw new ArgumentNullException(nameof(options));
|
||||
_lastPruned = _lastSync = DateTime.UtcNow;
|
||||
_syncIdle = new ManualResetEvent(true);
|
||||
_distCacheFilePath = new Lazy<string>(() => GetDistCacheFilePath(globalSettings));
|
||||
}
|
||||
|
||||
protected ILogger Logger { get; }
|
||||
@@ -522,12 +523,12 @@ namespace Umbraco.Core.Sync
|
||||
+ "/D" + AppDomain.CurrentDomain.Id // eg 22
|
||||
+ "] " + Guid.NewGuid().ToString("N").ToUpper(); // make it truly unique
|
||||
|
||||
private static string GetDistCacheFilePath()
|
||||
private string GetDistCacheFilePath(IGlobalSettings globalSettings)
|
||||
{
|
||||
var fileName = HttpRuntime.AppDomainAppId.ReplaceNonAlphanumericChars(string.Empty) + "-lastsynced.txt";
|
||||
|
||||
string distCacheFilePath;
|
||||
switch (GlobalSettings.LocalTempStorageLocation)
|
||||
switch (globalSettings.LocalTempStorageLocation)
|
||||
{
|
||||
case LocalTempStorage.AspNetTemp:
|
||||
distCacheFilePath = Path.Combine(HttpRuntime.CodegenDir, @"UmbracoData", fileName);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="15.0">
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<PropertyGroup>
|
||||
<TargetFrameworkVersion>v4.7</TargetFrameworkVersion>
|
||||
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
|
||||
@@ -207,6 +208,7 @@
|
||||
<Compile Include="Configuration\FileSystemProviderElementCollection.cs" />
|
||||
<Compile Include="Configuration\FileSystemProvidersSection.cs" />
|
||||
<Compile Include="Configuration\GlobalSettings.cs" />
|
||||
<Compile Include="Configuration\GlobalSettingsExtensions.cs" />
|
||||
<Compile Include="Configuration\Grid\GridConfig.cs" />
|
||||
<Compile Include="Configuration\Grid\GridEditorsConfig.cs" />
|
||||
<Compile Include="Configuration\Grid\IGridConfig.cs" />
|
||||
@@ -228,6 +230,7 @@
|
||||
<Compile Include="Configuration\HealthChecks\NotificationMethodSettingsElementCollection.cs" />
|
||||
<Compile Include="Configuration\IFileSystemProviderElement.cs" />
|
||||
<Compile Include="Configuration\IFileSystemProvidersSection.cs" />
|
||||
<Compile Include="Configuration\IGlobalSettings.cs" />
|
||||
<Compile Include="Configuration\InnerTextConfigurationElement.cs" />
|
||||
<Compile Include="Configuration\LocalTempStorage.cs" />
|
||||
<Compile Include="Configuration\OptionalCommaDelimitedConfigurationElement.cs" />
|
||||
@@ -1329,7 +1332,6 @@
|
||||
<Compile Include="Security\UmbracoEmailMessage.cs" />
|
||||
<Compile Include="Security\UmbracoMembershipProviderBase.cs" />
|
||||
<Compile Include="Security\UserAwareMembershipProviderPasswordHasher.cs" />
|
||||
<Compile Include="Security\UserData.cs" />
|
||||
<Compile Include="SemVersionExtensions.cs" />
|
||||
<Compile Include="Serialization\AbstractSerializationService.cs" />
|
||||
<Compile Include="Serialization\ForceInt32Converter.cs" />
|
||||
|
||||
@@ -13,33 +13,34 @@ namespace Umbraco.Core
|
||||
/// </summary>
|
||||
public static class UriExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Checks if the current uri is a back office request
|
||||
/// </summary>
|
||||
/// <param name="url"></param>
|
||||
/// <param name="applicationPath">
|
||||
/// The current application path or VirtualPath
|
||||
/// </param>
|
||||
/// <summary>
|
||||
/// Checks if the current uri is a back office request
|
||||
/// </summary>
|
||||
/// <param name="url"></param>
|
||||
/// <param name="applicationPath">
|
||||
/// The current application path or VirtualPath
|
||||
/// </param>
|
||||
/// <param name="globalSettings"></param>
|
||||
/// <returns></returns>
|
||||
/// <remarks>
|
||||
/// There are some special routes we need to check to properly determine this:
|
||||
///
|
||||
/// If any route has an extension in the path like .aspx = back office
|
||||
///
|
||||
/// These are def back office:
|
||||
/// /Umbraco/RestServices = back office
|
||||
/// /Umbraco/BackOffice = back office
|
||||
/// If it's not any of the above, and there's no extension then we cannot determine if it's back office or front-end
|
||||
/// so we can only assume that it is not back office. This will occur if people use an UmbracoApiController for the backoffice
|
||||
/// but do not inherit from UmbracoAuthorizedApiController and do not use [IsBackOffice] attribute.
|
||||
///
|
||||
/// These are def front-end:
|
||||
/// /Umbraco/Surface = front-end
|
||||
/// /Umbraco/Api = front-end
|
||||
/// But if we've got this far we'll just have to assume it's front-end anyways.
|
||||
///
|
||||
/// </remarks>
|
||||
internal static bool IsBackOfficeRequest(this Uri url, string applicationPath)
|
||||
/// <remarks>
|
||||
/// There are some special routes we need to check to properly determine this:
|
||||
///
|
||||
/// If any route has an extension in the path like .aspx = back office
|
||||
///
|
||||
/// These are def back office:
|
||||
/// /Umbraco/RestServices = back office
|
||||
/// /Umbraco/BackOffice = back office
|
||||
/// If it's not any of the above, and there's no extension then we cannot determine if it's back office or front-end
|
||||
/// so we can only assume that it is not back office. This will occur if people use an UmbracoApiController for the backoffice
|
||||
/// but do not inherit from UmbracoAuthorizedApiController and do not use [IsBackOffice] attribute.
|
||||
///
|
||||
/// These are def front-end:
|
||||
/// /Umbraco/Surface = front-end
|
||||
/// /Umbraco/Api = front-end
|
||||
/// But if we've got this far we'll just have to assume it's front-end anyways.
|
||||
///
|
||||
/// </remarks>
|
||||
internal static bool IsBackOfficeRequest(this Uri url, string applicationPath, IGlobalSettings globalSettings)
|
||||
{
|
||||
applicationPath = applicationPath ?? string.Empty;
|
||||
|
||||
@@ -48,13 +49,13 @@ namespace Umbraco.Core
|
||||
var urlPath = fullUrlPath.TrimStart(appPath).EnsureStartsWith('/');
|
||||
|
||||
//check if this is in the umbraco back office
|
||||
var isUmbracoPath = urlPath.InvariantStartsWith(GlobalSettings.Path.EnsureStartsWith('/').TrimStart(appPath.EnsureStartsWith('/')).EnsureStartsWith('/'));
|
||||
var isUmbracoPath = urlPath.InvariantStartsWith(globalSettings.Path.EnsureStartsWith('/').TrimStart(appPath.EnsureStartsWith('/')).EnsureStartsWith('/'));
|
||||
//if not, then def not back office
|
||||
if (isUmbracoPath == false) return false;
|
||||
|
||||
//if its the normal /umbraco path
|
||||
if (urlPath.InvariantEquals("/" + GlobalSettings.UmbracoMvcArea)
|
||||
|| urlPath.InvariantEquals("/" + GlobalSettings.UmbracoMvcArea + "/"))
|
||||
if (urlPath.InvariantEquals("/" + globalSettings.GetUmbracoMvcArea())
|
||||
|| urlPath.InvariantEquals("/" + globalSettings.GetUmbracoMvcArea() + "/"))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
@@ -75,15 +76,15 @@ namespace Umbraco.Core
|
||||
}
|
||||
|
||||
//check for special back office paths
|
||||
if (urlPath.InvariantStartsWith("/" + GlobalSettings.UmbracoMvcArea + "/BackOffice/")
|
||||
|| urlPath.InvariantStartsWith("/" + GlobalSettings.UmbracoMvcArea + "/RestServices/"))
|
||||
if (urlPath.InvariantStartsWith("/" + globalSettings.GetUmbracoMvcArea() + "/BackOffice/")
|
||||
|| urlPath.InvariantStartsWith("/" + globalSettings.GetUmbracoMvcArea() + "/RestServices/"))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
//check for special front-end paths
|
||||
if (urlPath.InvariantStartsWith("/" + GlobalSettings.UmbracoMvcArea + "/Surface/")
|
||||
|| urlPath.InvariantStartsWith("/" + GlobalSettings.UmbracoMvcArea + "/Api/"))
|
||||
if (urlPath.InvariantStartsWith("/" + globalSettings.GetUmbracoMvcArea() + "/Surface/")
|
||||
|| urlPath.InvariantStartsWith("/" + globalSettings.GetUmbracoMvcArea() + "/Api/"))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
@@ -122,13 +123,14 @@ namespace Umbraco.Core
|
||||
/// Checks if the uri is a request for the default back office page
|
||||
/// </summary>
|
||||
/// <param name="url"></param>
|
||||
/// <param name="globalSettings"></param>
|
||||
/// <returns></returns>
|
||||
internal static bool IsDefaultBackOfficeRequest(this Uri url)
|
||||
internal static bool IsDefaultBackOfficeRequest(this Uri url, IGlobalSettings globalSettings)
|
||||
{
|
||||
if (url.AbsolutePath.InvariantEquals(GlobalSettings.Path.TrimEnd("/"))
|
||||
|| url.AbsolutePath.InvariantEquals(GlobalSettings.Path.EnsureEndsWith('/'))
|
||||
|| url.AbsolutePath.InvariantEquals(GlobalSettings.Path.EnsureEndsWith('/') + "Default")
|
||||
|| url.AbsolutePath.InvariantEquals(GlobalSettings.Path.EnsureEndsWith('/') + "Default/"))
|
||||
if (url.AbsolutePath.InvariantEquals(globalSettings.Path.TrimEnd("/"))
|
||||
|| url.AbsolutePath.InvariantEquals(globalSettings.Path.EnsureEndsWith('/'))
|
||||
|| url.AbsolutePath.InvariantEquals(globalSettings.Path.EnsureEndsWith('/') + "Default")
|
||||
|| url.AbsolutePath.InvariantEquals(globalSettings.Path.EnsureEndsWith('/') + "Default/"))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="15.0">
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<PropertyGroup>
|
||||
<TargetFrameworkVersion>v4.7</TargetFrameworkVersion>
|
||||
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
|
||||
@@ -47,9 +48,7 @@
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<!-- note: NuGet deals with transitive references now -->
|
||||
<PackageReference Include="Examine">
|
||||
<Version>1.0.0-beta025</Version>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Examine" Version="1.0.0-beta025" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
|
||||
<PackageReference Include="NPoco" Version="3.9.3" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<Project ToolsVersion="15.0">
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
@@ -63,6 +64,8 @@
|
||||
<PackageReference Include="BenchmarkDotNet.Diagnostics.Windows" Version="0.10.13" />
|
||||
<PackageReference Include="BenchmarkDotNet.Toolchains.Roslyn" Version="0.10.13" />
|
||||
<PackageReference Include="Castle.Core" Version="4.2.1" />
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="2.7.0" />
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.Common" Version="2.7.0" />
|
||||
<PackageReference Include="Microsoft.Diagnostics.Tracing.TraceEvent" Version="2.0.11" />
|
||||
<PackageReference Include="Microsoft.DotNet.InternalAbstractions" Version="1.0.0" />
|
||||
<PackageReference Include="Microsoft.DotNet.PlatformAbstractions" Version="2.0.4" />
|
||||
@@ -155,6 +158,7 @@
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<!-- get NuGet packages directory -->
|
||||
<PropertyGroup>
|
||||
<PostBuildEvent>
|
||||
REM if not exist "$(TargetDir)x86" md "$(TargetDir)x86"
|
||||
@@ -169,16 +173,15 @@ REM xcopy "$(ProjectDir)"..\packages\SqlServerCE.4.0.0.1\x86\*.* "$(TargetDir)x8
|
||||
REM xcopy /s /y "$(NugetPackages)\Microsoft.SqlServer.Compact.4.0.8876.1\NativeBinaries\x86\*.*" "$(TargetDir)x86"
|
||||
REM if not exist "$(TargetDir)amd64" md "$(TargetDir)amd64"
|
||||
REM xcopy /s /y "$(NugetPackages)\Microsoft.SqlServer.Compact.4.0.8876.1\NativeBinaries\amd64\*.*" "$(TargetDir)amd64"</PostBuildEvent>
|
||||
<NuGetPackages>$(NuGetPackageFolders.Split(';')[0])</NuGetPackages>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup>
|
||||
<PreBuildEvent>REM xcopy "$(NugetPackages)\SqlServerCE.4.0.0.1\amd64\*.* "$(TargetDir)amd64\" /Y /F /E /I /C /D
|
||||
REM xcopy "$(NugetPackages)\SqlServerCE.4.0.0.1\x86\*.* "$(TargetDir)x86\" /Y /F /E /I /C /D</PreBuildEvent>
|
||||
</PropertyGroup>
|
||||
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
||||
Other similar extension points exist, see Microsoft.Common.targets.
|
||||
<Target Name="BeforeBuild">
|
||||
<ItemGroup>
|
||||
<SqlCE64 Include="$(NuGetPackages)SqlServerCE\4.0.0.1\amd64\*.*" />
|
||||
<SqlCE86 Include="$(NuGetPackages)SqlServerCE\4.0.0.1\x86\*.*" />
|
||||
</ItemGroup>
|
||||
<Message Text="Copy SqlCe files to $(TargetDir)" Importance="high" />
|
||||
<Copy SourceFiles="@(SqlCe64)" DestinationFolder="$(TargetDir)amd64" OverwriteReadOnlyFiles="true" SkipUnchangedFiles="true" />
|
||||
<Copy SourceFiles="@(SqlCe86)" DestinationFolder="$(TargetDir)x86" OverwriteReadOnlyFiles="true" SkipUnchangedFiles="true" />
|
||||
</Target>
|
||||
<Target Name="AfterBuild">
|
||||
</Target>
|
||||
-->
|
||||
</Project>
|
||||
@@ -62,7 +62,7 @@
|
||||
<add key="umbracoUseDirectoryUrls" value="false"/>
|
||||
<add key="umbracoTimeOutInMinutes" value="20"/>
|
||||
<add key="umbracoDefaultUILanguage" value="en"/>
|
||||
<add key="umbracoUseSSL" value="false"/>
|
||||
<add key="umbracoUseHttps" value="false"/>
|
||||
</appSettings>
|
||||
|
||||
<connectionStrings>
|
||||
|
||||
@@ -53,16 +53,18 @@ namespace Umbraco.Tests.Cache.PublishedCache
|
||||
|
||||
_httpContextFactory = new FakeHttpContextFactory("~/Home");
|
||||
|
||||
var settings = SettingsForTests.GenerateMockSettings();
|
||||
var umbracoSettings = SettingsForTests.GenerateMockUmbracoSettings();
|
||||
var globalSettings = SettingsForTests.GenerateMockGlobalSettings();
|
||||
SettingsForTests.ConfigureSettings(umbracoSettings);
|
||||
SettingsForTests.ConfigureSettings(globalSettings);
|
||||
|
||||
SettingsForTests.ConfigureSettings(settings);
|
||||
_xml = new XmlDocument();
|
||||
_xml.LoadXml(GetXml());
|
||||
var xmlStore = new XmlStore(() => _xml, null, null, null);
|
||||
var cacheProvider = new StaticCacheProvider();
|
||||
var domainCache = new DomainCache(ServiceContext.DomainService);
|
||||
var publishedShapshot = new Umbraco.Web.PublishedCache.XmlPublishedCache.PublishedShapshot(
|
||||
new PublishedContentCache(xmlStore, domainCache, cacheProvider, ContentTypesCache, null, null),
|
||||
new PublishedContentCache(xmlStore, domainCache, cacheProvider, globalSettings, ContentTypesCache, null, null),
|
||||
new PublishedMediaCache(xmlStore, ServiceContext.MediaService, ServiceContext.UserService, cacheProvider, ContentTypesCache),
|
||||
new PublishedMemberCache(null, cacheProvider, Current.Services.MemberService, ContentTypesCache),
|
||||
domainCache);
|
||||
@@ -72,9 +74,10 @@ namespace Umbraco.Tests.Cache.PublishedCache
|
||||
_umbracoContext = new UmbracoContext(
|
||||
_httpContextFactory.HttpContext,
|
||||
publishedSnapshotService.Object,
|
||||
new WebSecurity(_httpContextFactory.HttpContext, Current.Services.UserService),
|
||||
settings,
|
||||
Enumerable.Empty<IUrlProvider>());
|
||||
new WebSecurity(_httpContextFactory.HttpContext, Current.Services.UserService, globalSettings),
|
||||
umbracoSettings,
|
||||
Enumerable.Empty<IUrlProvider>(),
|
||||
globalSettings);
|
||||
|
||||
_cache = _umbracoContext.ContentCache;
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ using NUnit.Framework;
|
||||
using Umbraco.Core.Cache;
|
||||
using Umbraco.Core.Composing;
|
||||
using Umbraco.Core.Logging;
|
||||
using Umbraco.Tests.TestHelpers;
|
||||
|
||||
namespace Umbraco.Tests.Composing
|
||||
{
|
||||
@@ -19,7 +20,7 @@ namespace Umbraco.Tests.Composing
|
||||
{
|
||||
ProfilingLogger = new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>());
|
||||
|
||||
TypeLoader = new TypeLoader(NullCacheProvider.Instance, ProfilingLogger, detectChanges: false)
|
||||
TypeLoader = new TypeLoader(NullCacheProvider.Instance, SettingsForTests.GenerateMockGlobalSettings(), ProfilingLogger, detectChanges: false)
|
||||
{
|
||||
AssembliesToScan = AssembliesToScan
|
||||
};
|
||||
|
||||
@@ -12,6 +12,7 @@ using Umbraco.Core.Composing;
|
||||
using Umbraco.Core.IO;
|
||||
using Umbraco.Core.Logging;
|
||||
using Umbraco.Core.PropertyEditors;
|
||||
using Umbraco.Tests.TestHelpers;
|
||||
using Umbraco.Web;
|
||||
using Umbraco.Web.PropertyEditors;
|
||||
|
||||
@@ -25,7 +26,7 @@ namespace Umbraco.Tests.Composing
|
||||
public void Initialize()
|
||||
{
|
||||
// this ensures it's reset
|
||||
_typeLoader = new TypeLoader(NullCacheProvider.Instance, new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()));
|
||||
_typeLoader = new TypeLoader(NullCacheProvider.Instance, SettingsForTests.GenerateMockGlobalSettings(), new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()));
|
||||
|
||||
foreach (var file in Directory.GetFiles(IOHelper.MapPath("~/App_Data/TEMP/TypesCache")))
|
||||
File.Delete(file);
|
||||
@@ -146,7 +147,7 @@ namespace Umbraco.Tests.Composing
|
||||
[Test]
|
||||
public void Detect_Legacy_Plugin_File_List()
|
||||
{
|
||||
var filePath = TypeLoader.GetTypesListFilePath();
|
||||
var filePath = _typeLoader.GetTypesListFilePath();
|
||||
var fileDir = Path.GetDirectoryName(filePath);
|
||||
Directory.CreateDirectory(fileDir);
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Web.Mvc;
|
||||
using System.Web.Routing;
|
||||
using Moq;
|
||||
using NUnit.Framework;
|
||||
using Umbraco.Core.Configuration;
|
||||
using Umbraco.Core.IO;
|
||||
@@ -10,26 +11,24 @@ namespace Umbraco.Tests.Configurations
|
||||
[TestFixture]
|
||||
public class GlobalSettingsTests : BaseWebTest
|
||||
{
|
||||
private string _root;
|
||||
|
||||
public override void SetUp()
|
||||
{
|
||||
base.SetUp();
|
||||
|
||||
SettingsForTests.UmbracoPath = "~/umbraco";
|
||||
_root = SystemDirectories.Root;
|
||||
}
|
||||
|
||||
public override void TearDown()
|
||||
{
|
||||
base.TearDown();
|
||||
|
||||
//ensure this is reset
|
||||
SystemDirectories.Root = null;
|
||||
SettingsForTests.UmbracoPath = "~/umbraco";
|
||||
SystemDirectories.Root = _root;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Is_Debug_Mode()
|
||||
{
|
||||
Assert.That(Umbraco.Core.Configuration.GlobalSettings.DebugMode, Is.EqualTo(true));
|
||||
Assert.That(GlobalSettings.DebugMode, Is.EqualTo(true));
|
||||
}
|
||||
|
||||
[Ignore("fixme - ignored test")]
|
||||
@@ -46,9 +45,12 @@ namespace Umbraco.Tests.Configurations
|
||||
[TestCase("~/some-wacky/nestedPath", "/MyVirtualDir/NestedVDir/", "some-wacky-nestedpath")]
|
||||
public void Umbraco_Mvc_Area(string path, string rootPath, string outcome)
|
||||
{
|
||||
SettingsForTests.UmbracoPath = path;
|
||||
var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container
|
||||
globalSettingsMock.Setup(x => x.Path).Returns(IOHelper.ResolveUrl(path));
|
||||
SettingsForTests.ConfigureSettings(globalSettingsMock.Object);
|
||||
|
||||
SystemDirectories.Root = rootPath;
|
||||
Assert.AreEqual(outcome, Umbraco.Core.Configuration.GlobalSettings.UmbracoMvcArea);
|
||||
Assert.AreEqual(outcome, UmbracoConfig.For.GlobalSettings().GetUmbracoMvcArea());
|
||||
}
|
||||
|
||||
[TestCase("/umbraco/umbraco.aspx")]
|
||||
@@ -61,7 +63,8 @@ namespace Umbraco.Tests.Configurations
|
||||
[TestCase("/config/splashes/booting.aspx")]
|
||||
public void Is_Reserved_Path_Or_Url(string url)
|
||||
{
|
||||
Assert.IsTrue(Umbraco.Core.Configuration.GlobalSettings.IsReservedPathOrUrl(url));
|
||||
var globalSettings = TestObjects.GetGlobalSettings();
|
||||
Assert.IsTrue(globalSettings.IsReservedPathOrUrl(url));
|
||||
}
|
||||
|
||||
[TestCase("/umbraco_client/Tree/treeIcons.css")]
|
||||
@@ -75,7 +78,8 @@ namespace Umbraco.Tests.Configurations
|
||||
[TestCase("/install.aspx")]
|
||||
public void Is_Not_Reserved_Path_Or_Url(string url)
|
||||
{
|
||||
Assert.IsFalse(Umbraco.Core.Configuration.GlobalSettings.IsReservedPathOrUrl(url));
|
||||
var globalSettings = TestObjects.GetGlobalSettings();
|
||||
Assert.IsFalse(globalSettings.IsReservedPathOrUrl(url));
|
||||
}
|
||||
|
||||
|
||||
@@ -92,8 +96,10 @@ namespace Umbraco.Tests.Configurations
|
||||
public void Is_Reserved_By_Route(string url, bool shouldMatch)
|
||||
{
|
||||
//reset the app config, we only want to test routes not the hard coded paths
|
||||
Umbraco.Core.Configuration.GlobalSettings.ReservedPaths = "";
|
||||
Umbraco.Core.Configuration.GlobalSettings.ReservedUrls = "";
|
||||
var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container
|
||||
globalSettingsMock.Setup(x => x.ReservedPaths).Returns("");
|
||||
globalSettingsMock.Setup(x => x.ReservedUrls).Returns("");
|
||||
SettingsForTests.ConfigureSettings(globalSettingsMock.Object);
|
||||
|
||||
var routes = new RouteCollection();
|
||||
|
||||
@@ -112,7 +118,7 @@ namespace Umbraco.Tests.Configurations
|
||||
|
||||
Assert.AreEqual(
|
||||
shouldMatch,
|
||||
Umbraco.Core.Configuration.GlobalSettings.IsReservedPathOrUrl(url, context.HttpContext, routes));
|
||||
globalSettingsMock.Object.IsReservedPathOrUrl(url, context.HttpContext, routes));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ namespace Umbraco.Tests.CoreThings
|
||||
{
|
||||
base.SetUp();
|
||||
|
||||
var settings = SettingsForTests.GetDefault();
|
||||
var settings = SettingsForTests.GetDefaultUmbracoSettings();
|
||||
|
||||
// fixme - base should do it!
|
||||
Container.RegisterSingleton<IShortStringHelper>(_ => new DefaultShortStringHelper(settings));
|
||||
|
||||
@@ -12,6 +12,7 @@ using Umbraco.Core.Composing;
|
||||
using Umbraco.Core.Deploy;
|
||||
using Umbraco.Core.Logging;
|
||||
using Umbraco.Core.Serialization;
|
||||
using Umbraco.Tests.TestHelpers;
|
||||
|
||||
namespace Umbraco.Tests.CoreThings
|
||||
{
|
||||
@@ -23,7 +24,9 @@ namespace Umbraco.Tests.CoreThings
|
||||
{
|
||||
// fixme - bad in a unit test - but Udi has a static ctor that wants it?!
|
||||
var container = new Mock<IServiceContainer>();
|
||||
container.Setup(x => x.GetInstance(typeof (TypeLoader))).Returns(new TypeLoader(NullCacheProvider.Instance, new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>())));
|
||||
var globalSettings = SettingsForTests.GenerateMockGlobalSettings();
|
||||
container.Setup(x => x.GetInstance(typeof (TypeLoader))).Returns(
|
||||
new TypeLoader(NullCacheProvider.Instance, globalSettings, new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>())));
|
||||
Current.Container = container.Object;
|
||||
|
||||
Udi.ResetUdiTypes();
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
using NUnit.Framework;
|
||||
using Umbraco.Core;
|
||||
using Umbraco.Core.IO;
|
||||
using Umbraco.Tests.TestHelpers;
|
||||
|
||||
namespace Umbraco.Tests.CoreThings
|
||||
{
|
||||
@@ -48,9 +49,9 @@ namespace Umbraco.Tests.CoreThings
|
||||
public void Is_Back_Office_Request(string input, string virtualPath, bool expected)
|
||||
{
|
||||
SystemDirectories.Root = virtualPath;
|
||||
|
||||
var globalConfig = SettingsForTests.GenerateMockGlobalSettings();
|
||||
var source = new Uri(input);
|
||||
Assert.AreEqual(expected, source.IsBackOfficeRequest(virtualPath));
|
||||
Assert.AreEqual(expected, source.IsBackOfficeRequest(virtualPath, globalConfig));
|
||||
}
|
||||
|
||||
[TestCase("http://www.domain.com/install", true)]
|
||||
|
||||
@@ -23,7 +23,7 @@ namespace Umbraco.Tests.IO
|
||||
public void Setup()
|
||||
{
|
||||
//init the config singleton
|
||||
var config = SettingsForTests.GetDefault();
|
||||
var config = SettingsForTests.GetDefaultUmbracoSettings();
|
||||
SettingsForTests.ConfigureSettings(config);
|
||||
|
||||
_container = new ServiceContainer();
|
||||
|
||||
@@ -26,7 +26,7 @@ namespace Umbraco.Tests.Macros
|
||||
new IsolatedRuntimeCache(type => new ObjectCacheRuntimeCacheProvider()));
|
||||
//Current.ApplicationContext = new ApplicationContext(cacheHelper, new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()));
|
||||
|
||||
UmbracoConfig.For.SetUmbracoSettings(SettingsForTests.GetDefault());
|
||||
UmbracoConfig.For.SetUmbracoSettings(SettingsForTests.GetDefaultUmbracoSettings());
|
||||
}
|
||||
|
||||
[TestCase("123", "IntProp", typeof(int))]
|
||||
|
||||
@@ -7,8 +7,10 @@ using NUnit.Framework;
|
||||
using Umbraco.Core;
|
||||
using Umbraco.Core.Configuration.UmbracoSettings;
|
||||
using Umbraco.Core.Composing;
|
||||
using Umbraco.Core.Configuration;
|
||||
using Umbraco.Core.Logging;
|
||||
using Umbraco.Core.Sync;
|
||||
using Umbraco.Tests.TestHelpers;
|
||||
|
||||
namespace Umbraco.Tests.Misc
|
||||
{
|
||||
@@ -20,9 +22,9 @@ namespace Umbraco.Tests.Misc
|
||||
// note: in tests, read appContext._umbracoApplicationUrl and not the property,
|
||||
// because reading the property does run some code, as long as the field is null.
|
||||
|
||||
private void Initialize(IUmbracoSettingsSection settings)
|
||||
private void Initialize(IUmbracoSettingsSection settings, IGlobalSettings globalSettings)
|
||||
{
|
||||
_registrar = new ConfigServerRegistrar(settings.DistributedCall, Mock.Of<ILogger>());
|
||||
_registrar = new ConfigServerRegistrar(settings.DistributedCall, Mock.Of<ILogger>(), globalSettings);
|
||||
var container = new ServiceContainer();
|
||||
container.ConfigureUmbracoCore();
|
||||
container.Register(_ => _registrar);
|
||||
@@ -51,15 +53,16 @@ namespace Umbraco.Tests.Misc
|
||||
&& section.WebRouting == Mock.Of<IWebRoutingSection>(wrSection => wrSection.UmbracoApplicationUrl == (string) null)
|
||||
&& section.ScheduledTasks == Mock.Of<IScheduledTasksSection>());
|
||||
|
||||
var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings());
|
||||
globalConfig.Setup(x => x.UseHttps).Returns(true);
|
||||
|
||||
ApplicationUrlHelper.ApplicationUrlProvider = request => "http://server1.com/umbraco";
|
||||
|
||||
Initialize(settings);
|
||||
Initialize(settings, globalConfig.Object);
|
||||
|
||||
var state = new RuntimeState(Mock.Of<ILogger>(), new Lazy<IServerRegistrar>(Mock.Of<IServerRegistrar>), new Lazy<MainDom>(Mock.Of<MainDom>));
|
||||
|
||||
ConfigurationManager.AppSettings.Set("umbracoUseSSL", "true"); // does not make a diff here
|
||||
|
||||
state.EnsureApplicationUrl(settings: settings);
|
||||
state.EnsureApplicationUrl(settings, globalConfig.Object);
|
||||
|
||||
Assert.AreEqual("http://server1.com/umbraco", state.ApplicationUrl.ToString());
|
||||
}
|
||||
@@ -74,11 +77,12 @@ namespace Umbraco.Tests.Misc
|
||||
&& section.WebRouting == Mock.Of<IWebRoutingSection>(wrSection => wrSection.UmbracoApplicationUrl == (string) null)
|
||||
&& section.ScheduledTasks == Mock.Of<IScheduledTasksSection>());
|
||||
|
||||
Initialize(settings);
|
||||
var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings());
|
||||
globalConfig.Setup(x => x.UseHttps).Returns(true);
|
||||
|
||||
ConfigurationManager.AppSettings.Set("umbracoUseSSL", "true"); // does not make a diff here
|
||||
|
||||
var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of<ILogger>());
|
||||
Initialize(settings, globalConfig.Object);
|
||||
|
||||
var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of<ILogger>(), globalConfig.Object);
|
||||
|
||||
// still NOT set
|
||||
Assert.IsNull(url);
|
||||
@@ -99,11 +103,12 @@ namespace Umbraco.Tests.Misc
|
||||
&& section.WebRouting == Mock.Of<IWebRoutingSection>(wrSection => wrSection.UmbracoApplicationUrl == (string)null)
|
||||
&& section.ScheduledTasks == Mock.Of<IScheduledTasksSection>(tasksSection => tasksSection.BaseUrl == (string)null));
|
||||
|
||||
Initialize(settings);
|
||||
var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings());
|
||||
globalConfig.Setup(x => x.UseHttps).Returns(true);
|
||||
|
||||
ConfigurationManager.AppSettings.Set("umbracoUseSSL", "true");
|
||||
Initialize(settings, globalConfig.Object);
|
||||
|
||||
var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of<ILogger>());
|
||||
var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of<ILogger>(), globalConfig.Object);
|
||||
|
||||
Assert.AreEqual("http://server1.com:80/umbraco", url);
|
||||
|
||||
@@ -126,11 +131,12 @@ namespace Umbraco.Tests.Misc
|
||||
&& section.WebRouting == Mock.Of<IWebRoutingSection>(wrSection => wrSection.UmbracoApplicationUrl == (string)null)
|
||||
&& section.ScheduledTasks == Mock.Of<IScheduledTasksSection>(tasksSection => tasksSection.BaseUrl == (string)null));
|
||||
|
||||
Initialize(settings);
|
||||
var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings());
|
||||
globalConfig.Setup(x => x.UseHttps).Returns(true);
|
||||
|
||||
ConfigurationManager.AppSettings.Set("umbracoUseSSL", "true");
|
||||
Initialize(settings, globalConfig.Object);
|
||||
|
||||
var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of<ILogger>());
|
||||
var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of<ILogger>(), globalConfig.Object);
|
||||
|
||||
Assert.AreEqual("http://server1.com:80/umbraco", url);
|
||||
|
||||
@@ -153,11 +159,12 @@ namespace Umbraco.Tests.Misc
|
||||
&& section.WebRouting == Mock.Of<IWebRoutingSection>(wrSection => wrSection.UmbracoApplicationUrl == (string)null)
|
||||
&& section.ScheduledTasks == Mock.Of<IScheduledTasksSection>(tasksSection => tasksSection.BaseUrl == (string)null));
|
||||
|
||||
Initialize(settings);
|
||||
var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings());
|
||||
globalConfig.Setup(x => x.UseHttps).Returns(true);
|
||||
|
||||
ConfigurationManager.AppSettings.Set("umbracoUseSSL", "true");
|
||||
Initialize(settings, globalConfig.Object);
|
||||
|
||||
var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of<ILogger>());
|
||||
var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of<ILogger>(), globalConfig.Object);
|
||||
|
||||
Assert.IsNull(url);
|
||||
|
||||
@@ -174,8 +181,10 @@ namespace Umbraco.Tests.Misc
|
||||
section.DistributedCall == Mock.Of<IDistributedCallSection>(callSection => callSection.Enabled == false && callSection.Servers == Enumerable.Empty<IServer>())
|
||||
&& section.WebRouting == Mock.Of<IWebRoutingSection>(wrSection => wrSection.UmbracoApplicationUrl == (string)null)
|
||||
&& section.ScheduledTasks == Mock.Of<IScheduledTasksSection>(tasksSection => tasksSection.BaseUrl == (string)null));
|
||||
|
||||
Initialize(settings);
|
||||
|
||||
var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings());
|
||||
|
||||
Initialize(settings, globalConfig.Object);
|
||||
|
||||
var role = _registrar.GetCurrentServerRole();
|
||||
Assert.AreEqual(ServerRole.Single, role);
|
||||
@@ -191,7 +200,9 @@ namespace Umbraco.Tests.Misc
|
||||
&& section.WebRouting == Mock.Of<IWebRoutingSection>(wrSection => wrSection.UmbracoApplicationUrl == (string)null)
|
||||
&& section.ScheduledTasks == Mock.Of<IScheduledTasksSection>(tasksSection => tasksSection.BaseUrl == (string)null));
|
||||
|
||||
Initialize(settings);
|
||||
var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings());
|
||||
|
||||
Initialize(settings, globalConfig.Object);
|
||||
|
||||
var role = _registrar.GetCurrentServerRole();
|
||||
Assert.AreEqual(ServerRole.Unknown, role);
|
||||
@@ -210,7 +221,9 @@ namespace Umbraco.Tests.Misc
|
||||
&& section.WebRouting == Mock.Of<IWebRoutingSection>(wrSection => wrSection.UmbracoApplicationUrl == (string)null)
|
||||
&& section.ScheduledTasks == Mock.Of<IScheduledTasksSection>(tasksSection => tasksSection.BaseUrl == (string)null));
|
||||
|
||||
Initialize(settings);
|
||||
var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings());
|
||||
|
||||
Initialize(settings, globalConfig.Object);
|
||||
|
||||
var role = _registrar.GetCurrentServerRole();
|
||||
Assert.AreEqual(ServerRole.Slave, role);
|
||||
@@ -224,11 +237,12 @@ namespace Umbraco.Tests.Misc
|
||||
&& section.WebRouting == Mock.Of<IWebRoutingSection>(wrSection => wrSection.UmbracoApplicationUrl == (string) null)
|
||||
&& section.ScheduledTasks == Mock.Of<IScheduledTasksSection>(tasksSection => tasksSection.BaseUrl == "mycoolhost.com/umbraco"));
|
||||
|
||||
Initialize(settings);
|
||||
var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings());
|
||||
globalConfig.Setup(x => x.UseHttps).Returns(false);
|
||||
|
||||
ConfigurationManager.AppSettings.Set("umbracoUseSSL", "false");
|
||||
|
||||
var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of<ILogger>());
|
||||
Initialize(settings, globalConfig.Object);
|
||||
|
||||
var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of<ILogger>(), globalConfig.Object);
|
||||
|
||||
Assert.AreEqual("http://mycoolhost.com/umbraco", url);
|
||||
}
|
||||
@@ -241,11 +255,12 @@ namespace Umbraco.Tests.Misc
|
||||
&& section.WebRouting == Mock.Of<IWebRoutingSection>(wrSection => wrSection.UmbracoApplicationUrl == (string) null)
|
||||
&& section.ScheduledTasks == Mock.Of<IScheduledTasksSection>(tasksSection => tasksSection.BaseUrl == "mycoolhost.com/umbraco/"));
|
||||
|
||||
Initialize(settings);
|
||||
var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings());
|
||||
globalConfig.Setup(x => x.UseHttps).Returns(true);
|
||||
|
||||
ConfigurationManager.AppSettings.Set("umbracoUseSSL", "true");
|
||||
|
||||
var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of<ILogger>());
|
||||
Initialize(settings, globalConfig.Object);
|
||||
|
||||
var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of<ILogger>(), globalConfig.Object);
|
||||
|
||||
Assert.AreEqual("https://mycoolhost.com/umbraco", url);
|
||||
}
|
||||
@@ -258,11 +273,12 @@ namespace Umbraco.Tests.Misc
|
||||
&& section.WebRouting == Mock.Of<IWebRoutingSection>(wrSection => wrSection.UmbracoApplicationUrl == "httpx://whatever.com/umbraco/")
|
||||
&& section.ScheduledTasks == Mock.Of<IScheduledTasksSection>(tasksSection => tasksSection.BaseUrl == "mycoolhost.com/umbraco"));
|
||||
|
||||
Initialize(settings);
|
||||
var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings());
|
||||
globalConfig.Setup(x => x.UseHttps).Returns(true);
|
||||
|
||||
ConfigurationManager.AppSettings.Set("umbracoUseSSL", "true"); // does not make a diff here
|
||||
Initialize(settings, globalConfig.Object);
|
||||
|
||||
var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of<ILogger>());
|
||||
var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of<ILogger>(), globalConfig.Object);
|
||||
|
||||
Assert.AreEqual("httpx://whatever.com/umbraco", url);
|
||||
}
|
||||
|
||||
@@ -84,7 +84,10 @@ namespace Umbraco.Tests.Misc
|
||||
{
|
||||
ConfigurationManager.AppSettings.Set("umbracoUseDirectoryUrls", directoryUrls ? "true" : "false");
|
||||
|
||||
var settings = SettingsForTests.GenerateMockSettings();
|
||||
var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings());
|
||||
globalConfig.Setup(x => x.UseDirectoryUrls).Returns(directoryUrls);
|
||||
|
||||
var settings = SettingsForTests.GenerateMockUmbracoSettings();
|
||||
var requestMock = Mock.Get(settings.RequestHandler);
|
||||
requestMock.Setup(x => x.AddTrailingSlash).Returns(trailingSlash);
|
||||
SettingsForTests.ConfigureSettings(settings);
|
||||
@@ -93,7 +96,7 @@ namespace Umbraco.Tests.Misc
|
||||
|
||||
var expectedUri = NewUri(expectedUrl);
|
||||
var sourceUri = NewUri(sourceUrl);
|
||||
var resultUri = UriUtility.UriFromUmbraco(sourceUri);
|
||||
var resultUri = UriUtility.UriFromUmbraco(sourceUri, globalConfig.Object, settings.RequestHandler);
|
||||
|
||||
Assert.AreEqual(expectedUri.ToString(), resultUri.ToString());
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ namespace Umbraco.Tests.Models
|
||||
{
|
||||
base.SetUp();
|
||||
|
||||
var config = SettingsForTests.GetDefault();
|
||||
var config = SettingsForTests.GetDefaultUmbracoSettings();
|
||||
SettingsForTests.ConfigureSettings(config);
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ namespace Umbraco.Tests.Models
|
||||
[SetUp]
|
||||
public void Init()
|
||||
{
|
||||
var config = SettingsForTests.GetDefault();
|
||||
var config = SettingsForTests.GetDefaultUmbracoSettings();
|
||||
SettingsForTests.ConfigureSettings(config);
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ namespace Umbraco.Tests.Packaging
|
||||
private static string GetTestPackagePath(string packageName)
|
||||
{
|
||||
const string testPackagesDirName = "Packaging\\Packages";
|
||||
string path = Path.Combine(Core.Configuration.GlobalSettings.FullpathToRoot, testPackagesDirName, packageName);
|
||||
string path = Path.Combine(Core.Configuration.GlobalSettings.FullPathToRoot, testPackagesDirName, packageName);
|
||||
return path;
|
||||
}
|
||||
|
||||
|
||||
@@ -49,7 +49,7 @@ namespace Umbraco.Tests.Persistence.Repositories
|
||||
private UserRepository CreateRepository(IScopeProvider provider)
|
||||
{
|
||||
var accessor = (IScopeAccessor) provider;
|
||||
var repository = new UserRepository(accessor, CacheHelper.CreateDisabledCacheHelper(), Mock.Of<ILogger>(), Mock.Of<IMapperCollection>());
|
||||
var repository = new UserRepository(accessor, CacheHelper.CreateDisabledCacheHelper(), Mock.Of<ILogger>(), Mock.Of<IMapperCollection>(), TestObjects.GetGlobalSettings());
|
||||
return repository;
|
||||
}
|
||||
|
||||
@@ -204,7 +204,7 @@ namespace Umbraco.Tests.Persistence.Repositories
|
||||
|
||||
var id = user.Id;
|
||||
|
||||
var repository2 = new UserRepository((IScopeAccessor) provider, CacheHelper.CreateDisabledCacheHelper(), Logger, Mock.Of<IMapperCollection>());
|
||||
var repository2 = new UserRepository((IScopeAccessor) provider, CacheHelper.CreateDisabledCacheHelper(), Logger, Mock.Of<IMapperCollection>(),TestObjects.GetGlobalSettings());
|
||||
|
||||
repository2.Delete(user);
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ namespace Umbraco.Tests.PropertyEditors
|
||||
var container = new ServiceContainer();
|
||||
container.ConfigureUmbracoCore();
|
||||
container.Register<IShortStringHelper>(_
|
||||
=> new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault())));
|
||||
=> new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings())));
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
|
||||
@@ -65,13 +65,16 @@ namespace Umbraco.Tests.PublishedContent
|
||||
var publishedSnapshotService = new Mock<IPublishedSnapshotService>();
|
||||
publishedSnapshotService.Setup(x => x.CreatePublishedSnapshot(It.IsAny<string>())).Returns(publishedSnapshot);
|
||||
|
||||
var globalSettings = TestObjects.GetGlobalSettings();
|
||||
|
||||
var httpContext = GetHttpContextFactory("http://umbraco.local/", routeData).HttpContext;
|
||||
var umbracoContext = new UmbracoContext(
|
||||
httpContext,
|
||||
publishedSnapshotService.Object,
|
||||
new WebSecurity(httpContext, Current.Services.UserService),
|
||||
new WebSecurity(httpContext, Current.Services.UserService, globalSettings),
|
||||
TestObjects.GetUmbracoSettings(),
|
||||
Enumerable.Empty<IUrlProvider>());
|
||||
Enumerable.Empty<IUrlProvider>(),
|
||||
globalSettings);
|
||||
|
||||
return umbracoContext;
|
||||
}
|
||||
|
||||
@@ -439,7 +439,7 @@ namespace Umbraco.Tests.PublishedContent
|
||||
[Test]
|
||||
public void Convert_From_Standard_Xml()
|
||||
{
|
||||
var config = SettingsForTests.GenerateMockSettings();
|
||||
var config = SettingsForTests.GenerateMockUmbracoSettings();
|
||||
|
||||
SettingsForTests.ConfigureSettings(config);
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using NUnit.Framework;
|
||||
using Moq;
|
||||
using NUnit.Framework;
|
||||
using Umbraco.Tests.TestHelpers;
|
||||
using Umbraco.Web.Routing;
|
||||
using Umbraco.Core.Models;
|
||||
@@ -26,15 +27,18 @@ namespace Umbraco.Tests.Routing
|
||||
[TestCase("/home/Sub1.aspx/blah")]
|
||||
public void Match_Document_By_Url_With_Template(string urlAsString)
|
||||
{
|
||||
|
||||
var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container
|
||||
globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false);
|
||||
SettingsForTests.ConfigureSettings(globalSettings.Object);
|
||||
|
||||
var template1 = CreateTemplate("test");
|
||||
var template2 = CreateTemplate("blah");
|
||||
var umbracoContext = GetUmbracoContext(urlAsString, template1.Id);
|
||||
var umbracoContext = GetUmbracoContext(urlAsString, template1.Id, globalSettings:globalSettings.Object);
|
||||
var publishedRouter = CreatePublishedRouter();
|
||||
var frequest = publishedRouter.CreateRequest(umbracoContext);
|
||||
var lookup = new ContentFinderByNiceUrlAndTemplate(Logger);
|
||||
|
||||
SettingsForTests.HideTopLevelNodeFromPath = false;
|
||||
|
||||
var result = lookup.TryFindContent(frequest);
|
||||
|
||||
Assert.IsTrue(result);
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using Moq;
|
||||
using NUnit.Framework;
|
||||
using Umbraco.Core.Configuration;
|
||||
using Umbraco.Core.Models;
|
||||
using Umbraco.Tests.TestHelpers;
|
||||
using Umbraco.Tests.Testing;
|
||||
@@ -25,13 +27,16 @@ namespace Umbraco.Tests.Routing
|
||||
[TestCase("/test-page", 1172)]
|
||||
public void Match_Document_By_Url_Hide_Top_Level(string urlString, int expectedId)
|
||||
{
|
||||
var umbracoContext = GetUmbracoContext(urlString);
|
||||
var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container
|
||||
globalSettingsMock.Setup(x => x.HideTopLevelNodeFromPath).Returns(true);
|
||||
SettingsForTests.ConfigureSettings(globalSettingsMock.Object);
|
||||
|
||||
var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettingsMock.Object);
|
||||
var publishedRouter = CreatePublishedRouter();
|
||||
var frequest = publishedRouter.CreateRequest(umbracoContext);
|
||||
var lookup = new ContentFinderByNiceUrl(Logger);
|
||||
SettingsForTests.HideTopLevelNodeFromPath = true;
|
||||
|
||||
Assert.IsTrue(Core.Configuration.GlobalSettings.HideTopLevelNodeFromPath);
|
||||
Assert.IsTrue(UmbracoConfig.For.GlobalSettings().HideTopLevelNodeFromPath);
|
||||
|
||||
// fixme debugging - going further down, the routes cache is NOT empty?!
|
||||
if (urlString == "/home/sub1")
|
||||
@@ -58,13 +63,16 @@ namespace Umbraco.Tests.Routing
|
||||
[TestCase("/home/Sub1.aspx", 1173)]
|
||||
public void Match_Document_By_Url(string urlString, int expectedId)
|
||||
{
|
||||
var umbracoContext = GetUmbracoContext(urlString);
|
||||
var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container
|
||||
globalSettingsMock.Setup(x => x.HideTopLevelNodeFromPath).Returns(false);
|
||||
SettingsForTests.ConfigureSettings(globalSettingsMock.Object);
|
||||
|
||||
var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettingsMock.Object);
|
||||
var publishedRouter = CreatePublishedRouter();
|
||||
var frequest = publishedRouter.CreateRequest(umbracoContext);
|
||||
var lookup = new ContentFinderByNiceUrl(Logger);
|
||||
SettingsForTests.HideTopLevelNodeFromPath = false;
|
||||
|
||||
Assert.IsFalse(Core.Configuration.GlobalSettings.HideTopLevelNodeFromPath);
|
||||
Assert.IsFalse(UmbracoConfig.For.GlobalSettings().HideTopLevelNodeFromPath);
|
||||
|
||||
var result = lookup.TryFindContent(frequest);
|
||||
|
||||
@@ -81,12 +89,15 @@ namespace Umbraco.Tests.Routing
|
||||
[TestCase("/home/sub1/custom-sub-4-with-æøå", 1180)]
|
||||
public void Match_Document_By_Url_With_Special_Characters(string urlString, int expectedId)
|
||||
{
|
||||
var umbracoContext = GetUmbracoContext(urlString);
|
||||
var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container
|
||||
globalSettingsMock.Setup(x => x.HideTopLevelNodeFromPath).Returns(false);
|
||||
SettingsForTests.ConfigureSettings(globalSettingsMock.Object);
|
||||
|
||||
var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettingsMock.Object);
|
||||
var publishedRouter = CreatePublishedRouter();
|
||||
var frequest = publishedRouter.CreateRequest(umbracoContext);
|
||||
var lookup = new ContentFinderByNiceUrl(Logger);
|
||||
SettingsForTests.HideTopLevelNodeFromPath = false;
|
||||
|
||||
|
||||
var result = lookup.TryFindContent(frequest);
|
||||
|
||||
Assert.IsTrue(result);
|
||||
@@ -106,12 +117,15 @@ namespace Umbraco.Tests.Routing
|
||||
[TestCase("/home/sub1/custom-sub-4-with-æøå", 1180)]
|
||||
public void Match_Document_By_Url_With_Special_Characters_Using_Hostname(string urlString, int expectedId)
|
||||
{
|
||||
var umbracoContext = GetUmbracoContext(urlString);
|
||||
var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container
|
||||
globalSettingsMock.Setup(x => x.HideTopLevelNodeFromPath).Returns(false);
|
||||
SettingsForTests.ConfigureSettings(globalSettingsMock.Object);
|
||||
|
||||
var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettingsMock.Object);
|
||||
var publishedRouter = CreatePublishedRouter();
|
||||
var frequest = publishedRouter.CreateRequest(umbracoContext);
|
||||
frequest.Domain = new DomainAndUri(new Domain(1, "mysite", -1, CultureInfo.CurrentCulture, false), new Uri("http://mysite/"));
|
||||
var lookup = new ContentFinderByNiceUrl(Logger);
|
||||
SettingsForTests.HideTopLevelNodeFromPath = false;
|
||||
|
||||
var result = lookup.TryFindContent(frequest);
|
||||
|
||||
@@ -133,13 +147,16 @@ namespace Umbraco.Tests.Routing
|
||||
[TestCase("/æøå/home/sub1/custom-sub-4-with-æøå", 1180)]
|
||||
public void Match_Document_By_Url_With_Special_Characters_In_Hostname(string urlString, int expectedId)
|
||||
{
|
||||
var umbracoContext = GetUmbracoContext(urlString);
|
||||
var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container
|
||||
globalSettingsMock.Setup(x => x.HideTopLevelNodeFromPath).Returns(false);
|
||||
SettingsForTests.ConfigureSettings(globalSettingsMock.Object);
|
||||
|
||||
var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettingsMock.Object);
|
||||
var publishedRouter = CreatePublishedRouter();
|
||||
var frequest = publishedRouter.CreateRequest(umbracoContext);
|
||||
frequest.Domain = new DomainAndUri(new Domain(1, "mysite/æøå", -1, CultureInfo.CurrentCulture, false), new Uri("http://mysite/æøå"));
|
||||
var lookup = new ContentFinderByNiceUrl(Logger);
|
||||
SettingsForTests.HideTopLevelNodeFromPath = false;
|
||||
|
||||
|
||||
var result = lookup.TryFindContent(frequest);
|
||||
|
||||
Assert.IsTrue(result);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using NUnit.Framework;
|
||||
using Moq;
|
||||
using NUnit.Framework;
|
||||
using Umbraco.Core.Models;
|
||||
using Umbraco.Tests.TestHelpers;
|
||||
using Umbraco.Web.Routing;
|
||||
@@ -123,9 +124,11 @@ namespace Umbraco.Tests.Routing
|
||||
{
|
||||
SetDomains3();
|
||||
|
||||
SettingsForTests.HideTopLevelNodeFromPath = true;
|
||||
|
||||
var umbracoContext = GetUmbracoContext(url);
|
||||
var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container
|
||||
globalSettingsMock.Setup(x => x.HideTopLevelNodeFromPath).Returns(true);
|
||||
SettingsForTests.ConfigureSettings(globalSettingsMock.Object);
|
||||
|
||||
var umbracoContext = GetUmbracoContext(url, globalSettings:globalSettingsMock.Object);
|
||||
var publishedRouter = CreatePublishedRouter(Container);
|
||||
var frequest = publishedRouter.CreateRequest(umbracoContext);
|
||||
|
||||
@@ -164,9 +167,11 @@ namespace Umbraco.Tests.Routing
|
||||
// defaults depend on test environment
|
||||
expectedCulture = expectedCulture ?? System.Threading.Thread.CurrentThread.CurrentUICulture.Name;
|
||||
|
||||
SettingsForTests.HideTopLevelNodeFromPath = true;
|
||||
var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container
|
||||
globalSettingsMock.Setup(x => x.HideTopLevelNodeFromPath).Returns(true);
|
||||
SettingsForTests.ConfigureSettings(globalSettingsMock.Object);
|
||||
|
||||
var umbracoContext = GetUmbracoContext(url);
|
||||
var umbracoContext = GetUmbracoContext(url, globalSettings:globalSettingsMock.Object);
|
||||
var publishedRouter = CreatePublishedRouter(Container);
|
||||
var frequest = publishedRouter.CreateRequest(umbracoContext);
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using Moq;
|
||||
using NUnit.Framework;
|
||||
using Umbraco.Core.Models;
|
||||
using Umbraco.Tests.TestHelpers;
|
||||
@@ -263,7 +264,11 @@ namespace Umbraco.Tests.Routing
|
||||
{
|
||||
SetDomains1();
|
||||
|
||||
var umbracoContext = GetUmbracoContext(inputUrl);
|
||||
var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container
|
||||
globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false);
|
||||
SettingsForTests.ConfigureSettings(globalSettings.Object);
|
||||
|
||||
var umbracoContext = GetUmbracoContext(inputUrl, globalSettings:globalSettings.Object);
|
||||
var publishedRouter = CreatePublishedRouter(Container);
|
||||
var frequest = publishedRouter.CreateRequest(umbracoContext);
|
||||
|
||||
@@ -271,8 +276,7 @@ namespace Umbraco.Tests.Routing
|
||||
publishedRouter.FindDomain(frequest);
|
||||
|
||||
Assert.AreEqual(expectedCulture, frequest.Culture.Name);
|
||||
|
||||
SettingsForTests.HideTopLevelNodeFromPath = false;
|
||||
|
||||
var finder = new ContentFinderByNiceUrl(Logger);
|
||||
var result = finder.TryFindContent(frequest);
|
||||
|
||||
@@ -310,7 +314,11 @@ namespace Umbraco.Tests.Routing
|
||||
// defaults depend on test environment
|
||||
expectedCulture = expectedCulture ?? System.Threading.Thread.CurrentThread.CurrentUICulture.Name;
|
||||
|
||||
var umbracoContext = GetUmbracoContext(inputUrl);
|
||||
var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container
|
||||
globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false);
|
||||
SettingsForTests.ConfigureSettings(globalSettings.Object);
|
||||
|
||||
var umbracoContext = GetUmbracoContext(inputUrl, globalSettings:globalSettings.Object);
|
||||
var publishedRouter = CreatePublishedRouter(Container);
|
||||
var frequest = publishedRouter.CreateRequest(umbracoContext);
|
||||
|
||||
@@ -318,7 +326,6 @@ namespace Umbraco.Tests.Routing
|
||||
publishedRouter.FindDomain(frequest);
|
||||
|
||||
// find document
|
||||
SettingsForTests.HideTopLevelNodeFromPath = false;
|
||||
var finder = new ContentFinderByNiceUrl(Logger);
|
||||
var result = finder.TryFindContent(frequest);
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ namespace Umbraco.Tests.Routing
|
||||
base.SetUp();
|
||||
|
||||
//generate new mock settings and assign so we can configure in individual tests
|
||||
_umbracoSettings = SettingsForTests.GenerateMockSettings();
|
||||
_umbracoSettings = SettingsForTests.GenerateMockUmbracoSettings();
|
||||
SettingsForTests.ConfigureSettings(_umbracoSettings);
|
||||
}
|
||||
|
||||
@@ -38,10 +38,16 @@ namespace Umbraco.Tests.Routing
|
||||
[Test]
|
||||
public void Ensure_Cache_Is_Correct()
|
||||
{
|
||||
var umbracoContext = GetUmbracoContext("/test", 1111, urlProviders: new [] { new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger) });
|
||||
SettingsForTests.UseDirectoryUrls = true;
|
||||
SettingsForTests.HideTopLevelNodeFromPath = false;
|
||||
var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container
|
||||
globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true);
|
||||
globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false);
|
||||
SettingsForTests.ConfigureSettings(globalSettings.Object);
|
||||
|
||||
var umbracoContext = GetUmbracoContext("/test", 1111, urlProviders: new []
|
||||
{
|
||||
new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object)
|
||||
}, globalSettings:globalSettings.Object);
|
||||
|
||||
var requestHandlerMock = Mock.Get(_umbracoSettings.RequestHandler);
|
||||
requestHandlerMock.Setup(x => x.AddTrailingSlash).Returns(false);// (cached routes have none)
|
||||
|
||||
@@ -95,10 +101,16 @@ namespace Umbraco.Tests.Routing
|
||||
[TestCase(1172, "/test-page/")]
|
||||
public void Get_Nice_Url_Not_Hiding_Top_Level(int nodeId, string niceUrlMatch)
|
||||
{
|
||||
var umbracoContext = GetUmbracoContext("/test", 1111, urlProviders: new[] { new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger) });
|
||||
var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container
|
||||
globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true);
|
||||
globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false);
|
||||
SettingsForTests.ConfigureSettings(globalSettings.Object);
|
||||
|
||||
var umbracoContext = GetUmbracoContext("/test", 1111, urlProviders: new[]
|
||||
{
|
||||
new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object)
|
||||
}, globalSettings:globalSettings.Object);
|
||||
|
||||
SettingsForTests.UseDirectoryUrls = true;
|
||||
SettingsForTests.HideTopLevelNodeFromPath = false;
|
||||
var requestMock = Mock.Get(_umbracoSettings.RequestHandler);
|
||||
requestMock.Setup(x => x.UseDomainPrefixes).Returns(false);
|
||||
|
||||
@@ -119,10 +131,16 @@ namespace Umbraco.Tests.Routing
|
||||
[TestCase(1172, "/test-page/")] // not hidden because not first root
|
||||
public void Get_Nice_Url_Hiding_Top_Level(int nodeId, string niceUrlMatch)
|
||||
{
|
||||
var umbracoContext = GetUmbracoContext("/test", 1111, urlProviders: new[] { new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger) });
|
||||
var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container
|
||||
globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true);
|
||||
globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(true);
|
||||
SettingsForTests.ConfigureSettings(globalSettings.Object);
|
||||
|
||||
var umbracoContext = GetUmbracoContext("/test", 1111, urlProviders: new[]
|
||||
{
|
||||
new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object)
|
||||
}, globalSettings:globalSettings.Object);
|
||||
|
||||
SettingsForTests.UseDirectoryUrls = true;
|
||||
SettingsForTests.HideTopLevelNodeFromPath = true;
|
||||
var requestMock = Mock.Get(_umbracoSettings.RequestHandler);
|
||||
requestMock.Setup(x => x.UseDomainPrefixes).Returns(false);
|
||||
|
||||
@@ -133,12 +151,19 @@ namespace Umbraco.Tests.Routing
|
||||
[Test]
|
||||
public void Get_Nice_Url_Relative_Or_Absolute()
|
||||
{
|
||||
SettingsForTests.UseDirectoryUrls = true;
|
||||
SettingsForTests.HideTopLevelNodeFromPath = false;
|
||||
var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container
|
||||
globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true);
|
||||
globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false);
|
||||
SettingsForTests.ConfigureSettings(globalSettings.Object);
|
||||
|
||||
|
||||
var requestMock = Mock.Get(_umbracoSettings.RequestHandler);
|
||||
requestMock.Setup(x => x.UseDomainPrefixes).Returns(false);
|
||||
|
||||
var umbracoContext = GetUmbracoContext("http://example.com/test", 1111, umbracoSettings: _umbracoSettings, urlProviders: new[] { new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger) });
|
||||
var umbracoContext = GetUmbracoContext("http://example.com/test", 1111, umbracoSettings: _umbracoSettings, urlProviders: new[]
|
||||
{
|
||||
new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object)
|
||||
}, globalSettings:globalSettings.Object);
|
||||
|
||||
Assert.AreEqual("/home/sub1/custom-sub-1/", umbracoContext.UrlProvider.GetUrl(1177));
|
||||
|
||||
@@ -153,10 +178,15 @@ namespace Umbraco.Tests.Routing
|
||||
[Test]
|
||||
public void Get_Nice_Url_Unpublished()
|
||||
{
|
||||
var umbracoContext = GetUmbracoContext("http://example.com/test", 1111, urlProviders: new[] { new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger) });
|
||||
var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container
|
||||
globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true);
|
||||
globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false);
|
||||
SettingsForTests.ConfigureSettings(globalSettings.Object);
|
||||
|
||||
SettingsForTests.UseDirectoryUrls = true;
|
||||
SettingsForTests.HideTopLevelNodeFromPath = false;
|
||||
var umbracoContext = GetUmbracoContext("http://example.com/test", 1111, urlProviders: new[]
|
||||
{
|
||||
new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object)
|
||||
}, globalSettings:globalSettings.Object);
|
||||
|
||||
//mock the Umbraco settings that we need
|
||||
var requestMock = Mock.Get(_umbracoSettings.RequestHandler);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using Moq;
|
||||
using NUnit.Framework;
|
||||
using Umbraco.Core.Models;
|
||||
using Umbraco.Tests.TestHelpers;
|
||||
@@ -192,12 +193,14 @@ DetermineRouteById(id):
|
||||
[TestCase(2006, false, "/x/b/e")]
|
||||
public void GetRouteByIdNoHide(int id, bool hide, string expected)
|
||||
{
|
||||
var umbracoContext = GetUmbracoContext("/test", 0);
|
||||
var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container
|
||||
globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(hide);
|
||||
SettingsForTests.ConfigureSettings(globalSettings.Object);
|
||||
|
||||
var umbracoContext = GetUmbracoContext("/test", 0, globalSettings: globalSettings.Object);
|
||||
var cache = umbracoContext.ContentCache as PublishedContentCache;
|
||||
if (cache == null) throw new Exception("Unsupported IPublishedContentCache, only the Xml one is supported.");
|
||||
|
||||
SettingsForTests.HideTopLevelNodeFromPath = hide;
|
||||
|
||||
var route = cache.GetRouteById(false, id);
|
||||
Assert.AreEqual(expected, route);
|
||||
}
|
||||
@@ -215,12 +218,14 @@ DetermineRouteById(id):
|
||||
[TestCase(2006, true, "/b/e")] // risky!
|
||||
public void GetRouteByIdHide(int id, bool hide, string expected)
|
||||
{
|
||||
var umbracoContext = GetUmbracoContext("/test", 0);
|
||||
var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container
|
||||
globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(hide);
|
||||
SettingsForTests.ConfigureSettings(globalSettings.Object);
|
||||
|
||||
var umbracoContext = GetUmbracoContext("/test", 0, globalSettings: globalSettings.Object);
|
||||
var cache = umbracoContext.ContentCache as PublishedContentCache;
|
||||
if (cache == null) throw new Exception("Unsupported IPublishedContentCache, only the Xml one is supported.");
|
||||
|
||||
SettingsForTests.HideTopLevelNodeFromPath = hide;
|
||||
|
||||
var route = cache.GetRouteById(false, id);
|
||||
Assert.AreEqual(expected, route);
|
||||
}
|
||||
@@ -228,12 +233,14 @@ DetermineRouteById(id):
|
||||
[Test]
|
||||
public void GetRouteByIdCache()
|
||||
{
|
||||
var umbracoContext = GetUmbracoContext("/test", 0);
|
||||
var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container
|
||||
globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false);
|
||||
SettingsForTests.ConfigureSettings(globalSettings.Object);
|
||||
|
||||
var umbracoContext = GetUmbracoContext("/test", 0, globalSettings:globalSettings.Object);
|
||||
var cache = umbracoContext.ContentCache as PublishedContentCache;
|
||||
if (cache == null) throw new Exception("Unsupported IPublishedContentCache, only the Xml one is supported.");
|
||||
|
||||
SettingsForTests.HideTopLevelNodeFromPath = false;
|
||||
|
||||
|
||||
var route = cache.GetRouteById(false, 1000);
|
||||
Assert.AreEqual("/a", route);
|
||||
|
||||
@@ -258,12 +265,14 @@ DetermineRouteById(id):
|
||||
[TestCase("/x", false, 2000)]
|
||||
public void GetByRouteNoHide(string route, bool hide, int expected)
|
||||
{
|
||||
var umbracoContext = GetUmbracoContext("/test", 0);
|
||||
var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container
|
||||
globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(hide);
|
||||
SettingsForTests.ConfigureSettings(globalSettings.Object);
|
||||
|
||||
var umbracoContext = GetUmbracoContext("/test", 0, globalSettings:globalSettings.Object);
|
||||
var cache = umbracoContext.ContentCache as PublishedContentCache;
|
||||
if (cache == null) throw new Exception("Unsupported IPublishedContentCache, only the Xml one is supported.");
|
||||
|
||||
SettingsForTests.HideTopLevelNodeFromPath = hide;
|
||||
|
||||
const bool preview = false; // make sure we don't cache - but HOW? should be some sort of switch?!
|
||||
var content = cache.GetByRoute(preview, route);
|
||||
if (expected < 0)
|
||||
@@ -288,12 +297,14 @@ DetermineRouteById(id):
|
||||
[TestCase("/b/c", true, 1002)] // (hence the 2005 collision)
|
||||
public void GetByRouteHide(string route, bool hide, int expected)
|
||||
{
|
||||
var umbracoContext = GetUmbracoContext("/test", 0);
|
||||
var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container
|
||||
globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(hide);
|
||||
SettingsForTests.ConfigureSettings(globalSettings.Object);
|
||||
|
||||
var umbracoContext = GetUmbracoContext("/test", 0, globalSettings:globalSettings.Object);
|
||||
var cache = umbracoContext.ContentCache as PublishedContentCache;
|
||||
if (cache == null) throw new Exception("Unsupported IPublishedContentCache, only the Xml one is supported.");
|
||||
|
||||
SettingsForTests.HideTopLevelNodeFromPath = hide;
|
||||
|
||||
const bool preview = false; // make sure we don't cache - but HOW? should be some sort of switch?!
|
||||
var content = cache.GetByRoute(preview, route);
|
||||
if (expected < 0)
|
||||
@@ -310,12 +321,14 @@ DetermineRouteById(id):
|
||||
[Test]
|
||||
public void GetByRouteCache()
|
||||
{
|
||||
var umbracoContext = GetUmbracoContext("/test", 0);
|
||||
var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container
|
||||
globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false);
|
||||
SettingsForTests.ConfigureSettings(globalSettings.Object);
|
||||
|
||||
var umbracoContext = GetUmbracoContext("/test", 0, globalSettings:globalSettings.Object);
|
||||
var cache = umbracoContext.ContentCache as PublishedContentCache;
|
||||
if (cache == null) throw new Exception("Unsupported IPublishedContentCache, only the Xml one is supported.");
|
||||
|
||||
SettingsForTests.HideTopLevelNodeFromPath = false;
|
||||
|
||||
|
||||
var content = cache.GetByRoute(false, "/a/b/c");
|
||||
Assert.IsNotNull(content);
|
||||
Assert.AreEqual(1002, content.Id);
|
||||
|
||||
@@ -173,15 +173,20 @@ namespace Umbraco.Tests.Routing
|
||||
[TestCase(10011, "https://domain1.com", false, "/1001-1/")]
|
||||
public void Get_Nice_Url_SimpleDomain(int nodeId, string currentUrl, bool absolute, string expected)
|
||||
{
|
||||
var settings = SettingsForTests.GenerateMockSettings();
|
||||
var settings = SettingsForTests.GenerateMockUmbracoSettings();
|
||||
var request = Mock.Get(settings.RequestHandler);
|
||||
request.Setup(x => x.UseDomainPrefixes).Returns(false);
|
||||
|
||||
var umbracoContext = GetUmbracoContext("/test", 1111, umbracoSettings: settings, urlProviders: new[] { new DefaultUrlProvider(settings.RequestHandler, Logger) });
|
||||
|
||||
SettingsForTests.UseDirectoryUrls = true;
|
||||
SettingsForTests.HideTopLevelNodeFromPath = false; // ignored w/domains
|
||||
var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container
|
||||
globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true);
|
||||
globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); // ignored w/domains
|
||||
SettingsForTests.ConfigureSettings(globalSettings.Object);
|
||||
|
||||
var umbracoContext = GetUmbracoContext("/test", 1111, umbracoSettings: settings, urlProviders: new[]
|
||||
{
|
||||
new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object)
|
||||
}, globalSettings:globalSettings.Object);
|
||||
|
||||
SetDomains1();
|
||||
|
||||
var currentUri = new Uri(currentUrl);
|
||||
@@ -204,14 +209,19 @@ namespace Umbraco.Tests.Routing
|
||||
[TestCase(10011, "https://domain1.com", false, "http://domain1.com/foo/1001-1/")]
|
||||
public void Get_Nice_Url_SimpleWithSchemeAndPath(int nodeId, string currentUrl, bool absolute, string expected)
|
||||
{
|
||||
var settings = SettingsForTests.GenerateMockSettings();
|
||||
var settings = SettingsForTests.GenerateMockUmbracoSettings();
|
||||
var request = Mock.Get(settings.RequestHandler);
|
||||
request.Setup(x => x.UseDomainPrefixes).Returns(false);
|
||||
|
||||
var umbracoContext = GetUmbracoContext("/test", 1111, umbracoSettings: settings, urlProviders: new[] { new DefaultUrlProvider(settings.RequestHandler, Logger) });
|
||||
var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container
|
||||
globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true);
|
||||
globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); // ignored w/domains
|
||||
SettingsForTests.ConfigureSettings(globalSettings.Object);
|
||||
|
||||
SettingsForTests.UseDirectoryUrls = true;
|
||||
SettingsForTests.HideTopLevelNodeFromPath = false; // ignored w/domains
|
||||
var umbracoContext = GetUmbracoContext("/test", 1111, umbracoSettings: settings, urlProviders: new[]
|
||||
{
|
||||
new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object)
|
||||
}, globalSettings:globalSettings.Object);
|
||||
|
||||
SetDomains2();
|
||||
|
||||
@@ -227,14 +237,19 @@ namespace Umbraco.Tests.Routing
|
||||
[TestCase(1002, "http://domain1.com", false, "/1002/")]
|
||||
public void Get_Nice_Url_DeepDomain(int nodeId, string currentUrl, bool absolute, string expected)
|
||||
{
|
||||
var settings = SettingsForTests.GenerateMockSettings();
|
||||
var settings = SettingsForTests.GenerateMockUmbracoSettings();
|
||||
var request = Mock.Get(settings.RequestHandler);
|
||||
request.Setup(x => x.UseDomainPrefixes).Returns(false);
|
||||
|
||||
var umbracoContext = GetUmbracoContext("/test", 1111, umbracoSettings: settings, urlProviders: new[] { new DefaultUrlProvider(settings.RequestHandler, Logger) });
|
||||
var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container
|
||||
globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true);
|
||||
globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); // ignored w/domains
|
||||
SettingsForTests.ConfigureSettings(globalSettings.Object);
|
||||
|
||||
SettingsForTests.UseDirectoryUrls = true;
|
||||
SettingsForTests.HideTopLevelNodeFromPath = false; // ignored w/domains
|
||||
var umbracoContext = GetUmbracoContext("/test", 1111, umbracoSettings: settings, urlProviders: new[]
|
||||
{
|
||||
new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object)
|
||||
}, globalSettings:globalSettings.Object);
|
||||
|
||||
SetDomains3();
|
||||
|
||||
@@ -256,14 +271,19 @@ namespace Umbraco.Tests.Routing
|
||||
[TestCase(100321, "http://domain3.com", false, "/fr/1003-2-1/")]
|
||||
public void Get_Nice_Url_NestedDomains(int nodeId, string currentUrl, bool absolute, string expected)
|
||||
{
|
||||
var settings = SettingsForTests.GenerateMockSettings();
|
||||
var settings = SettingsForTests.GenerateMockUmbracoSettings();
|
||||
var request = Mock.Get(settings.RequestHandler);
|
||||
request.Setup(x => x.UseDomainPrefixes).Returns(false);
|
||||
|
||||
var umbracoContext = GetUmbracoContext("/test", 1111, umbracoSettings: settings, urlProviders: new[] { new DefaultUrlProvider(settings.RequestHandler, Logger) });
|
||||
var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container
|
||||
globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true);
|
||||
globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); // ignored w/domains
|
||||
SettingsForTests.ConfigureSettings(globalSettings.Object);
|
||||
|
||||
SettingsForTests.UseDirectoryUrls = true;
|
||||
SettingsForTests.HideTopLevelNodeFromPath = false; // ignored w/domains
|
||||
var umbracoContext = GetUmbracoContext("/test", 1111, umbracoSettings: settings, urlProviders: new[]
|
||||
{
|
||||
new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object)
|
||||
}, globalSettings:globalSettings.Object);
|
||||
|
||||
SetDomains4();
|
||||
|
||||
@@ -275,14 +295,19 @@ namespace Umbraco.Tests.Routing
|
||||
[Test]
|
||||
public void Get_Nice_Url_DomainsAndCache()
|
||||
{
|
||||
var settings = SettingsForTests.GenerateMockSettings();
|
||||
var settings = SettingsForTests.GenerateMockUmbracoSettings();
|
||||
var request = Mock.Get(settings.RequestHandler);
|
||||
request.Setup(x => x.UseDomainPrefixes).Returns(false);
|
||||
|
||||
var umbracoContext = GetUmbracoContext("/test", 1111, umbracoSettings: settings, urlProviders: new[] { new DefaultUrlProvider(settings.RequestHandler, Logger) });
|
||||
var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container
|
||||
globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true);
|
||||
globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); // ignored w/domains
|
||||
SettingsForTests.ConfigureSettings(globalSettings.Object);
|
||||
|
||||
SettingsForTests.UseDirectoryUrls = true;
|
||||
SettingsForTests.HideTopLevelNodeFromPath = false; // ignored w/domains
|
||||
var umbracoContext = GetUmbracoContext("/test", 1111, umbracoSettings: settings, urlProviders: new[]
|
||||
{
|
||||
new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object)
|
||||
}, globalSettings:globalSettings.Object);
|
||||
|
||||
SetDomains4();
|
||||
|
||||
@@ -337,14 +362,19 @@ namespace Umbraco.Tests.Routing
|
||||
[Test]
|
||||
public void Get_Nice_Url_Relative_Or_Absolute()
|
||||
{
|
||||
var settings = SettingsForTests.GenerateMockSettings();
|
||||
var settings = SettingsForTests.GenerateMockUmbracoSettings();
|
||||
var requestMock = Mock.Get(settings.RequestHandler);
|
||||
requestMock.Setup(x => x.UseDomainPrefixes).Returns(false);
|
||||
|
||||
var umbracoContext = GetUmbracoContext("http://domain1.com/test", 1111, umbracoSettings: settings, urlProviders: new[] { new DefaultUrlProvider(settings.RequestHandler, Logger) });
|
||||
var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container
|
||||
globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true);
|
||||
globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); // ignored w/domains
|
||||
SettingsForTests.ConfigureSettings(globalSettings.Object);
|
||||
|
||||
SettingsForTests.UseDirectoryUrls = true;
|
||||
SettingsForTests.HideTopLevelNodeFromPath = false;
|
||||
var umbracoContext = GetUmbracoContext("http://domain1.com/test", 1111, umbracoSettings: settings, urlProviders: new[]
|
||||
{
|
||||
new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object)
|
||||
}, globalSettings:globalSettings.Object);
|
||||
|
||||
SetDomains4();
|
||||
|
||||
@@ -366,11 +396,17 @@ namespace Umbraco.Tests.Routing
|
||||
[Test]
|
||||
public void Get_Nice_Url_Alternate()
|
||||
{
|
||||
var settings = SettingsForTests.GenerateMockSettings();
|
||||
var umbracoContext = GetUmbracoContext("http://domain1.com/en/test", 1111, umbracoSettings: settings, urlProviders: new[] { new DefaultUrlProvider(settings.RequestHandler, Logger) });
|
||||
var settings = SettingsForTests.GenerateMockUmbracoSettings();
|
||||
|
||||
SettingsForTests.UseDirectoryUrls = true;
|
||||
SettingsForTests.HideTopLevelNodeFromPath = false;
|
||||
var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container
|
||||
globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true);
|
||||
globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); // ignored w/domains
|
||||
SettingsForTests.ConfigureSettings(globalSettings.Object);
|
||||
|
||||
var umbracoContext = GetUmbracoContext("http://domain1.com/en/test", 1111, umbracoSettings: settings, urlProviders: new[]
|
||||
{
|
||||
new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object)
|
||||
}, globalSettings:globalSettings.Object);
|
||||
|
||||
SetDomains5();
|
||||
|
||||
|
||||
@@ -31,10 +31,9 @@ namespace Umbraco.Tests.Routing
|
||||
{
|
||||
base.SetUp();
|
||||
|
||||
SettingsForTests.UmbracoPath = "~/umbraco";
|
||||
|
||||
WebRuntimeComponent.CreateRoutes(
|
||||
new TestUmbracoContextAccessor(),
|
||||
new TestUmbracoContextAccessor(),
|
||||
TestObjects.GetGlobalSettings(),
|
||||
new SurfaceControllerTypeCollection(Enumerable.Empty<Type>()),
|
||||
new UmbracoApiControllerTypeCollection(Enumerable.Empty<Type>()));
|
||||
}
|
||||
@@ -71,7 +70,7 @@ namespace Umbraco.Tests.Routing
|
||||
var umbracoApiControllerTypes = new UmbracoApiControllerTypeCollection(Current.TypeLoader.GetUmbracoApiControllers());
|
||||
Container.RegisterInstance(umbracoApiControllerTypes);
|
||||
|
||||
Container.RegisterSingleton<IShortStringHelper>(_ => new DefaultShortStringHelper(SettingsForTests.GetDefault()));
|
||||
Container.RegisterSingleton<IShortStringHelper>(_ => new DefaultShortStringHelper(SettingsForTests.GetDefaultUmbracoSettings()));
|
||||
}
|
||||
|
||||
public override void TearDown()
|
||||
|
||||
@@ -31,8 +31,8 @@ namespace Umbraco.Tests.Routing
|
||||
var runtime = new RuntimeState(_module.Logger, new Lazy<IServerRegistrar>(), new Lazy<MainDom>());
|
||||
_module.Runtime = runtime;
|
||||
runtime.Level = RuntimeLevel.Run;
|
||||
_module.GlobalSettings = TestObjects.GetGlobalSettings();
|
||||
|
||||
SettingsForTests.ConfigurationStatus = UmbracoVersion.SemanticVersion.ToSemanticString();
|
||||
//SettingsForTests.ReservedPaths = "~/umbraco,~/install/";
|
||||
//SettingsForTests.ReservedUrls = "~/config/splashes/booting.aspx,~/install/default.aspx,~/config/splashes/noNodes.aspx,~/VSEnterpriseHelper.axd";
|
||||
|
||||
|
||||
@@ -28,10 +28,12 @@ namespace Umbraco.Tests.Routing
|
||||
[Test]
|
||||
public void DoNotPolluteCache()
|
||||
{
|
||||
SettingsForTests.UseDirectoryUrls = true;
|
||||
SettingsForTests.HideTopLevelNodeFromPath = false; // ignored w/domains
|
||||
var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container
|
||||
globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true);
|
||||
globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false);
|
||||
SettingsForTests.ConfigureSettings(globalSettings.Object);
|
||||
|
||||
var settings = SettingsForTests.GenerateMockSettings();
|
||||
var settings = SettingsForTests.GenerateMockUmbracoSettings();
|
||||
var request = Mock.Get(settings.RequestHandler);
|
||||
request.Setup(x => x.UseDomainPrefixes).Returns(true);
|
||||
|
||||
@@ -40,7 +42,10 @@ namespace Umbraco.Tests.Routing
|
||||
const string url = "http://domain1.com/1001-1/1001-1-1";
|
||||
|
||||
// get the nice url for 100111
|
||||
var umbracoContext = GetUmbracoContext(url, 9999, umbracoSettings: settings, urlProviders: new [] { new DefaultUrlProvider(settings.RequestHandler, Logger) });
|
||||
var umbracoContext = GetUmbracoContext(url, 9999, umbracoSettings: settings, urlProviders: new []
|
||||
{
|
||||
new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object)
|
||||
}, globalSettings:globalSettings.Object);
|
||||
Assert.AreEqual("http://domain2.com/1001-1-1/", umbracoContext.UrlProvider.GetUrl(100111, true));
|
||||
|
||||
// check that the proper route has been cached
|
||||
|
||||
@@ -163,7 +163,7 @@ namespace Umbraco.Tests.Runtimes
|
||||
{
|
||||
base.Compose(composition);
|
||||
|
||||
composition.Container.Register(factory => SettingsForTests.GetDefault());
|
||||
composition.Container.Register(factory => SettingsForTests.GetDefaultUmbracoSettings());
|
||||
composition.Container.RegisterSingleton<IExamineManager, TestExamineManager>();
|
||||
|
||||
Composed = true;
|
||||
|
||||
@@ -8,6 +8,7 @@ using NUnit.Framework;
|
||||
using Umbraco.Core;
|
||||
using Umbraco.Core.Cache;
|
||||
using Umbraco.Core.Composing;
|
||||
using Umbraco.Core.Configuration;
|
||||
using Umbraco.Core.Configuration.UmbracoSettings;
|
||||
using Umbraco.Core.Events;
|
||||
using Umbraco.Core.Models;
|
||||
@@ -89,7 +90,7 @@ namespace Umbraco.Tests.Scoping
|
||||
publishedSnapshotAccessor,
|
||||
Logger,
|
||||
ScopeProvider,
|
||||
documentRepository, mediaRepository, memberRepository);
|
||||
documentRepository, mediaRepository, memberRepository, Container.GetInstance<IGlobalSettings>());
|
||||
}
|
||||
|
||||
protected UmbracoContext GetUmbracoContextNu(string url, int templateId = 1234, RouteData routeData = null, bool setSingleton = false, IUmbracoSettingsSection umbracoSettings = null, IEnumerable<IUrlProvider> urlProviders = null)
|
||||
@@ -102,9 +103,10 @@ namespace Umbraco.Tests.Scoping
|
||||
var umbracoContext = new UmbracoContext(
|
||||
httpContext,
|
||||
service,
|
||||
new WebSecurity(httpContext, Current.Services.UserService),
|
||||
umbracoSettings ?? SettingsForTests.GetDefault(),
|
||||
urlProviders ?? Enumerable.Empty<IUrlProvider>());
|
||||
new WebSecurity(httpContext, Current.Services.UserService, TestObjects.GetGlobalSettings()),
|
||||
umbracoSettings ?? SettingsForTests.GetDefaultUmbracoSettings(),
|
||||
urlProviders ?? Enumerable.Empty<IUrlProvider>(),
|
||||
TestObjects.GetGlobalSettings());
|
||||
|
||||
if (setSingleton)
|
||||
Umbraco.Web.Composing.Current.UmbracoContextAccessor.UmbracoContext = umbracoContext;
|
||||
|
||||
@@ -79,7 +79,7 @@ namespace Umbraco.Tests.Scoping
|
||||
Assert.AreSame(XmlStore, ((PublishedContentCache) umbracoContext.ContentCache).XmlStore);
|
||||
|
||||
// settings
|
||||
var settings = SettingsForTests.GenerateMockSettings();
|
||||
var settings = SettingsForTests.GenerateMockUmbracoSettings();
|
||||
var contentMock = Mock.Get(settings.Content);
|
||||
contentMock.Setup(x => x.XmlCacheEnabled).Returns(false);
|
||||
SettingsForTests.ConfigureSettings(settings);
|
||||
@@ -201,7 +201,7 @@ namespace Umbraco.Tests.Scoping
|
||||
Assert.AreSame(XmlStore, ((PublishedContentCache)umbracoContext.ContentCache).XmlStore);
|
||||
|
||||
// settings
|
||||
var settings = SettingsForTests.GenerateMockSettings();
|
||||
var settings = SettingsForTests.GenerateMockUmbracoSettings();
|
||||
var contentMock = Mock.Get(settings.Content);
|
||||
contentMock.Setup(x => x.XmlCacheEnabled).Returns(false);
|
||||
SettingsForTests.ConfigureSettings(settings);
|
||||
|
||||
@@ -29,11 +29,12 @@ namespace Umbraco.Tests.Security
|
||||
var umbracoContext = new UmbracoContext(
|
||||
Mock.Of<HttpContextBase>(),
|
||||
Mock.Of<IPublishedSnapshotService>(),
|
||||
new WebSecurity(Mock.Of<HttpContextBase>(), Current.Services.UserService),
|
||||
TestObjects.GetUmbracoSettings(), new List<IUrlProvider>());
|
||||
new WebSecurity(Mock.Of<HttpContextBase>(), Current.Services.UserService, TestObjects.GetGlobalSettings()),
|
||||
TestObjects.GetUmbracoSettings(), new List<IUrlProvider>(),TestObjects.GetGlobalSettings());
|
||||
|
||||
var runtime = Mock.Of<IRuntimeState>(x => x.Level == RuntimeLevel.Install);
|
||||
var mgr = new BackOfficeCookieManager(Mock.Of<IUmbracoContextAccessor>(accessor => accessor.UmbracoContext == umbracoContext), runtime);
|
||||
var mgr = new BackOfficeCookieManager(
|
||||
Mock.Of<IUmbracoContextAccessor>(accessor => accessor.UmbracoContext == umbracoContext), runtime, TestObjects.GetGlobalSettings());
|
||||
|
||||
var result = mgr.ShouldAuthenticateRequest(Mock.Of<IOwinContext>(), new Uri("http://localhost/umbraco"));
|
||||
|
||||
@@ -46,11 +47,11 @@ namespace Umbraco.Tests.Security
|
||||
var umbCtx = new UmbracoContext(
|
||||
Mock.Of<HttpContextBase>(),
|
||||
Mock.Of<IPublishedSnapshotService>(),
|
||||
new WebSecurity(Mock.Of<HttpContextBase>(), Current.Services.UserService),
|
||||
TestObjects.GetUmbracoSettings(), new List<IUrlProvider>());
|
||||
new WebSecurity(Mock.Of<HttpContextBase>(), Current.Services.UserService, TestObjects.GetGlobalSettings()),
|
||||
TestObjects.GetUmbracoSettings(), new List<IUrlProvider>(), TestObjects.GetGlobalSettings());
|
||||
|
||||
var runtime = Mock.Of<IRuntimeState>(x => x.Level == RuntimeLevel.Run);
|
||||
var mgr = new BackOfficeCookieManager(Mock.Of<IUmbracoContextAccessor>(accessor => accessor.UmbracoContext == umbCtx), runtime);
|
||||
var mgr = new BackOfficeCookieManager(Mock.Of<IUmbracoContextAccessor>(accessor => accessor.UmbracoContext == umbCtx), runtime, TestObjects.GetGlobalSettings());
|
||||
|
||||
var request = new Mock<OwinRequest>();
|
||||
request.Setup(owinRequest => owinRequest.Uri).Returns(new Uri("http://localhost/umbraco"));
|
||||
|
||||
@@ -30,8 +30,9 @@ namespace Umbraco.Tests.Security
|
||||
//This is the id that 'identity' uses to check for the username
|
||||
new Claim(ClaimTypes.Name, "testing", ClaimValueTypes.String, TestIssuer, TestIssuer),
|
||||
new Claim(ClaimTypes.GivenName, "hello world", ClaimValueTypes.String, TestIssuer, TestIssuer),
|
||||
new Claim(Constants.Security.StartContentNodeIdClaimType, "[-1]", ClaimValueTypes.Integer32, TestIssuer, TestIssuer),
|
||||
new Claim(Constants.Security.StartMediaNodeIdClaimType, "[5543]", ClaimValueTypes.Integer32, TestIssuer, TestIssuer),
|
||||
new Claim(Constants.Security.StartContentNodeIdClaimType, "-1", ClaimValueTypes.Integer32, TestIssuer, TestIssuer),
|
||||
new Claim(Constants.Security.StartMediaNodeIdClaimType, "5543", ClaimValueTypes.Integer32, TestIssuer, TestIssuer),
|
||||
new Claim(Constants.Security.StartMediaNodeIdClaimType, "5555", ClaimValueTypes.Integer32, TestIssuer, TestIssuer),
|
||||
new Claim(Constants.Security.AllowedApplicationsClaimType, "content", ClaimValueTypes.String, TestIssuer, TestIssuer),
|
||||
new Claim(Constants.Security.AllowedApplicationsClaimType, "media", ClaimValueTypes.String, TestIssuer, TestIssuer),
|
||||
new Claim(ClaimTypes.Locality, "en-us", ClaimValueTypes.String, TestIssuer, TestIssuer),
|
||||
@@ -42,18 +43,18 @@ namespace Umbraco.Tests.Security
|
||||
|
||||
var backofficeIdentity = UmbracoBackOfficeIdentity.FromClaimsIdentity(claimsIdentity);
|
||||
|
||||
Assert.AreEqual("1234", backofficeIdentity.Id);
|
||||
Assert.AreEqual(1234, backofficeIdentity.Id);
|
||||
Assert.AreEqual(sessionId, backofficeIdentity.SessionId);
|
||||
Assert.AreEqual(securityStamp, backofficeIdentity.SecurityStamp);
|
||||
Assert.AreEqual("testing", backofficeIdentity.Username);
|
||||
Assert.AreEqual("hello world", backofficeIdentity.RealName);
|
||||
Assert.AreEqual(1, backofficeIdentity.StartContentNodes.Length);
|
||||
Assert.IsTrue(backofficeIdentity.StartMediaNodes.UnsortedSequenceEqual(new[] { 5543 }));
|
||||
Assert.IsTrue(backofficeIdentity.StartMediaNodes.UnsortedSequenceEqual(new[] { 5543, 5555 }));
|
||||
Assert.IsTrue(new[] {"content", "media"}.SequenceEqual(backofficeIdentity.AllowedApplications));
|
||||
Assert.AreEqual("en-us", backofficeIdentity.Culture);
|
||||
Assert.IsTrue(new[] { "admin" }.SequenceEqual(backofficeIdentity.Roles));
|
||||
|
||||
Assert.AreEqual(11, backofficeIdentity.Claims.Count());
|
||||
Assert.AreEqual(12, backofficeIdentity.Claims.Count());
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -90,102 +91,36 @@ namespace Umbraco.Tests.Security
|
||||
Assert.Throws<InvalidOperationException>(() => UmbracoBackOfficeIdentity.FromClaimsIdentity(claimsIdentity));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Create_With_User_Data()
|
||||
{
|
||||
var sessionId = Guid.NewGuid().ToString();
|
||||
var userData = new UserData(sessionId)
|
||||
{
|
||||
SecurityStamp = sessionId,
|
||||
AllowedApplications = new[] {"content", "media"},
|
||||
Culture = "en-us",
|
||||
Id = 1234,
|
||||
RealName = "hello world",
|
||||
Roles = new[] {"admin"},
|
||||
StartMediaNodes = new[] { 654 },
|
||||
Username = "testing"
|
||||
};
|
||||
|
||||
var identity = new UmbracoBackOfficeIdentity(userData);
|
||||
|
||||
Assert.AreEqual(11, identity.Claims.Count());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Create_With_Claims_And_User_Data()
|
||||
{
|
||||
var sessionId = Guid.NewGuid().ToString();
|
||||
var userData = new UserData(sessionId)
|
||||
{
|
||||
SecurityStamp = sessionId,
|
||||
AllowedApplications = new[] { "content", "media" },
|
||||
Culture = "en-us",
|
||||
Id = 1234,
|
||||
RealName = "hello world",
|
||||
Roles = new[] { "admin" },
|
||||
StartMediaNodes = new[] { 654 },
|
||||
Username = "testing"
|
||||
};
|
||||
|
||||
|
||||
var claimsIdentity = new ClaimsIdentity(new[]
|
||||
{
|
||||
new Claim("TestClaim1", "test", ClaimValueTypes.Integer32, TestIssuer, TestIssuer),
|
||||
new Claim("TestClaim1", "test", ClaimValueTypes.Integer32, TestIssuer, TestIssuer)
|
||||
});
|
||||
|
||||
var backofficeIdentity = new UmbracoBackOfficeIdentity(claimsIdentity, userData);
|
||||
|
||||
Assert.AreEqual(13, backofficeIdentity.Claims.Count());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Create_With_Forms_Ticket()
|
||||
{
|
||||
var sessionId = Guid.NewGuid().ToString();
|
||||
var userData = new UserData(sessionId)
|
||||
{
|
||||
SecurityStamp = sessionId,
|
||||
AllowedApplications = new[] { "content", "media" },
|
||||
Culture = "en-us",
|
||||
Id = 1234,
|
||||
RealName = "hello world",
|
||||
Roles = new[] { "admin" },
|
||||
StartMediaNodes = new[] { 654 },
|
||||
Username = "testing"
|
||||
};
|
||||
|
||||
var ticket = new FormsAuthenticationTicket(1, userData.Username, DateTime.Now, DateTime.Now.AddDays(1), true,
|
||||
JsonConvert.SerializeObject(userData));
|
||||
|
||||
var identity = new UmbracoBackOfficeIdentity(ticket);
|
||||
var identity = new UmbracoBackOfficeIdentity(claimsIdentity,
|
||||
1234, "testing", "hello world", new[] { 654 }, new[] { 654 }, "en-us", sessionId, sessionId, new[] { "content", "media" }, new[] { "admin" });
|
||||
|
||||
Assert.AreEqual(12, identity.Claims.Count());
|
||||
}
|
||||
|
||||
|
||||
[Test]
|
||||
public void Clone()
|
||||
{
|
||||
var sessionId = Guid.NewGuid().ToString();
|
||||
var userData = new UserData(sessionId)
|
||||
{
|
||||
SecurityStamp = sessionId,
|
||||
AllowedApplications = new[] { "content", "media" },
|
||||
Culture = "en-us",
|
||||
Id = 1234,
|
||||
RealName = "hello world",
|
||||
Roles = new[] { "admin" },
|
||||
StartMediaNodes = new[] { 654 },
|
||||
Username = "testing"
|
||||
};
|
||||
|
||||
var ticket = new FormsAuthenticationTicket(1, userData.Username, DateTime.Now, DateTime.Now.AddDays(1), true,
|
||||
JsonConvert.SerializeObject(userData));
|
||||
|
||||
var identity = new UmbracoBackOfficeIdentity(ticket);
|
||||
var identity = new UmbracoBackOfficeIdentity(
|
||||
1234, "testing", "hello world", new[] { 654 }, new[] { 654 }, "en-us", sessionId, sessionId, new[] { "content", "media" }, new[] { "admin" });
|
||||
|
||||
var cloned = identity.Clone();
|
||||
|
||||
Assert.AreEqual(12, cloned.Claims.Count());
|
||||
Assert.AreEqual(10, cloned.Claims.Count());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -76,7 +76,7 @@ namespace Umbraco.Tests.Services
|
||||
private static string GetTestPackagePath(string packageName)
|
||||
{
|
||||
const string testPackagesDirName = "Packaging\\Packages";
|
||||
string path = Path.Combine(Core.Configuration.GlobalSettings.FullpathToRoot, testPackagesDirName, packageName);
|
||||
string path = Path.Combine(Core.Configuration.GlobalSettings.FullPathToRoot, testPackagesDirName, packageName);
|
||||
return path;
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ namespace Umbraco.Tests.Strings
|
||||
public void Setup()
|
||||
{
|
||||
//set default config
|
||||
var config = SettingsForTests.GetDefault();
|
||||
var config = SettingsForTests.GetDefaultUmbracoSettings();
|
||||
SettingsForTests.ConfigureSettings(config);
|
||||
|
||||
}
|
||||
@@ -39,7 +39,7 @@ namespace Umbraco.Tests.Strings
|
||||
[TestCase("WhoIsNumber6InTheVillage", "Who Is Number6 In The Village")] // issue is fixed
|
||||
public void CompatibleDefaultReplacement(string input, string expected)
|
||||
{
|
||||
var helper = new DefaultShortStringHelper(SettingsForTests.GetDefault());
|
||||
var helper = new DefaultShortStringHelper(SettingsForTests.GetDefaultUmbracoSettings());
|
||||
var output = input.Length < 2 ? input : helper.SplitPascalCasing(input, ' ').ToFirstUpperInvariant();
|
||||
Assert.AreEqual(expected, output);
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ namespace Umbraco.Tests.Strings
|
||||
// NOTE pre-filters runs _before_ Recode takes place
|
||||
// so there still may be utf8 chars even though you want ascii
|
||||
|
||||
_helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault())
|
||||
_helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings())
|
||||
.WithConfig(CleanStringType.FileName, new DefaultShortStringHelperConfig.Config
|
||||
{
|
||||
//PreFilter = ClearFileChars, // done in IsTerm
|
||||
@@ -96,7 +96,7 @@ namespace Umbraco.Tests.Strings
|
||||
[Test]
|
||||
public void U4_4056()
|
||||
{
|
||||
var settings = SettingsForTests.GenerateMockSettings();
|
||||
var settings = SettingsForTests.GenerateMockUmbracoSettings();
|
||||
var contentMock = Mock.Get(settings.RequestHandler);
|
||||
contentMock.Setup(x => x.CharCollection).Returns(Enumerable.Empty<IChar>());
|
||||
contentMock.Setup(x => x.ConvertUrlsToAscii).Returns(false);
|
||||
@@ -121,7 +121,7 @@ namespace Umbraco.Tests.Strings
|
||||
[Test]
|
||||
public void U4_4056_TryAscii()
|
||||
{
|
||||
var settings = SettingsForTests.GenerateMockSettings();
|
||||
var settings = SettingsForTests.GenerateMockUmbracoSettings();
|
||||
var contentMock = Mock.Get(settings.RequestHandler);
|
||||
contentMock.Setup(x => x.CharCollection).Returns(Enumerable.Empty<IChar>());
|
||||
contentMock.Setup(x => x.ConvertUrlsToAscii).Returns(false);
|
||||
@@ -148,7 +148,7 @@ namespace Umbraco.Tests.Strings
|
||||
[Test]
|
||||
public void CleanStringUnderscoreInTerm()
|
||||
{
|
||||
var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault())
|
||||
var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings())
|
||||
.WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config
|
||||
{
|
||||
// underscore is accepted within terms
|
||||
@@ -158,7 +158,7 @@ namespace Umbraco.Tests.Strings
|
||||
}));
|
||||
Assert.AreEqual("foo_bar*nil", helper.CleanString("foo_bar nil", CleanStringType.Alias));
|
||||
|
||||
helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault())
|
||||
helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings())
|
||||
.WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config
|
||||
{
|
||||
// underscore is not accepted within terms
|
||||
@@ -172,7 +172,7 @@ namespace Umbraco.Tests.Strings
|
||||
[Test]
|
||||
public void CleanStringLeadingChars()
|
||||
{
|
||||
var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault())
|
||||
var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings())
|
||||
.WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config
|
||||
{
|
||||
// letters and digits are valid leading chars
|
||||
@@ -182,7 +182,7 @@ namespace Umbraco.Tests.Strings
|
||||
}));
|
||||
Assert.AreEqual("0123foo*bar*543*nil*321", helper.CleanString("0123foo_bar 543 nil 321", CleanStringType.Alias));
|
||||
|
||||
helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault())
|
||||
helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings())
|
||||
.WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config
|
||||
{
|
||||
// only letters are valid leading chars
|
||||
@@ -193,14 +193,14 @@ namespace Umbraco.Tests.Strings
|
||||
Assert.AreEqual("foo*bar*543*nil*321", helper.CleanString("0123foo_bar 543 nil 321", CleanStringType.Alias));
|
||||
Assert.AreEqual("foo*bar*543*nil*321", helper.CleanString("0123 foo_bar 543 nil 321", CleanStringType.Alias));
|
||||
|
||||
helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault()));
|
||||
helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings()));
|
||||
Assert.AreEqual("child2", helper.CleanStringForSafeAlias("1child2"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CleanStringTermOnUpper()
|
||||
{
|
||||
var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault())
|
||||
var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings())
|
||||
.WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config
|
||||
{
|
||||
StringType = CleanStringType.Utf8 | CleanStringType.Unchanged,
|
||||
@@ -210,7 +210,7 @@ namespace Umbraco.Tests.Strings
|
||||
}));
|
||||
Assert.AreEqual("foo*Bar", helper.CleanString("fooBar", CleanStringType.Alias));
|
||||
|
||||
helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault())
|
||||
helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings())
|
||||
.WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config
|
||||
{
|
||||
StringType = CleanStringType.Utf8 | CleanStringType.Unchanged,
|
||||
@@ -224,7 +224,7 @@ namespace Umbraco.Tests.Strings
|
||||
[Test]
|
||||
public void CleanStringAcronymOnNonUpper()
|
||||
{
|
||||
var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault())
|
||||
var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings())
|
||||
.WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config
|
||||
{
|
||||
StringType = CleanStringType.Utf8 | CleanStringType.Unchanged,
|
||||
@@ -237,7 +237,7 @@ namespace Umbraco.Tests.Strings
|
||||
Assert.AreEqual("foo*BAnil", helper.CleanString("foo BAnil", CleanStringType.Alias));
|
||||
Assert.AreEqual("foo*Bnil", helper.CleanString("foo Bnil", CleanStringType.Alias));
|
||||
|
||||
helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault())
|
||||
helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings())
|
||||
.WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config
|
||||
{
|
||||
StringType = CleanStringType.Utf8 | CleanStringType.Unchanged,
|
||||
@@ -254,7 +254,7 @@ namespace Umbraco.Tests.Strings
|
||||
[Test]
|
||||
public void CleanStringGreedyAcronyms()
|
||||
{
|
||||
var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault())
|
||||
var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings())
|
||||
.WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config
|
||||
{
|
||||
StringType = CleanStringType.Utf8 | CleanStringType.Unchanged,
|
||||
@@ -267,7 +267,7 @@ namespace Umbraco.Tests.Strings
|
||||
Assert.AreEqual("foo*BA*nil", helper.CleanString("foo BAnil", CleanStringType.Alias));
|
||||
Assert.AreEqual("foo*Bnil", helper.CleanString("foo Bnil", CleanStringType.Alias));
|
||||
|
||||
helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault())
|
||||
helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings())
|
||||
.WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config
|
||||
{
|
||||
StringType = CleanStringType.Utf8 | CleanStringType.Unchanged,
|
||||
@@ -284,7 +284,7 @@ namespace Umbraco.Tests.Strings
|
||||
[Test]
|
||||
public void CleanStringWhiteSpace()
|
||||
{
|
||||
var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault())
|
||||
var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings())
|
||||
.WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config
|
||||
{
|
||||
StringType = CleanStringType.Utf8 | CleanStringType.Unchanged,
|
||||
@@ -297,7 +297,7 @@ namespace Umbraco.Tests.Strings
|
||||
[Test]
|
||||
public void CleanStringSeparator()
|
||||
{
|
||||
var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault())
|
||||
var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings())
|
||||
.WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config
|
||||
{
|
||||
StringType = CleanStringType.Utf8 | CleanStringType.Unchanged,
|
||||
@@ -305,7 +305,7 @@ namespace Umbraco.Tests.Strings
|
||||
}));
|
||||
Assert.AreEqual("foo*bar", helper.CleanString("foo bar", CleanStringType.Alias));
|
||||
|
||||
helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault())
|
||||
helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings())
|
||||
.WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config
|
||||
{
|
||||
StringType = CleanStringType.Utf8 | CleanStringType.Unchanged,
|
||||
@@ -313,14 +313,14 @@ namespace Umbraco.Tests.Strings
|
||||
}));
|
||||
Assert.AreEqual("foo bar", helper.CleanString("foo bar", CleanStringType.Alias));
|
||||
|
||||
helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault())
|
||||
helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings())
|
||||
.WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config
|
||||
{
|
||||
StringType = CleanStringType.Utf8 | CleanStringType.Unchanged
|
||||
}));
|
||||
Assert.AreEqual("foobar", helper.CleanString("foo bar", CleanStringType.Alias));
|
||||
|
||||
helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault())
|
||||
helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings())
|
||||
.WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config
|
||||
{
|
||||
StringType = CleanStringType.Utf8 | CleanStringType.Unchanged,
|
||||
@@ -332,7 +332,7 @@ namespace Umbraco.Tests.Strings
|
||||
[Test]
|
||||
public void CleanStringSymbols()
|
||||
{
|
||||
var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault())
|
||||
var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings())
|
||||
.WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config
|
||||
{
|
||||
StringType = CleanStringType.Utf8 | CleanStringType.Unchanged,
|
||||
@@ -386,7 +386,7 @@ namespace Umbraco.Tests.Strings
|
||||
[Test]
|
||||
public void CleanStringEncoding()
|
||||
{
|
||||
var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault())
|
||||
var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings())
|
||||
.WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config
|
||||
{
|
||||
StringType = CleanStringType.Utf8 | CleanStringType.Unchanged,
|
||||
@@ -395,7 +395,7 @@ namespace Umbraco.Tests.Strings
|
||||
Assert.AreEqual("中文测试", helper.CleanString("中文测试", CleanStringType.Alias));
|
||||
Assert.AreEqual("léger*中文测试*ZÔRG", helper.CleanString("léger 中文测试 ZÔRG", CleanStringType.Alias));
|
||||
|
||||
helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault())
|
||||
helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings())
|
||||
.WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config
|
||||
{
|
||||
StringType = CleanStringType.Ascii | CleanStringType.Unchanged,
|
||||
@@ -408,7 +408,7 @@ namespace Umbraco.Tests.Strings
|
||||
[Test]
|
||||
public void CleanStringDefaultConfig()
|
||||
{
|
||||
var settings = SettingsForTests.GenerateMockSettings();
|
||||
var settings = SettingsForTests.GenerateMockUmbracoSettings();
|
||||
var contentMock = Mock.Get(settings.RequestHandler);
|
||||
contentMock.Setup(x => x.CharCollection).Returns(Enumerable.Empty<IChar>());
|
||||
contentMock.Setup(x => x.ConvertUrlsToAscii).Returns(false);
|
||||
@@ -434,7 +434,7 @@ namespace Umbraco.Tests.Strings
|
||||
[Test]
|
||||
public void CleanStringCasing()
|
||||
{
|
||||
var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault())
|
||||
var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings())
|
||||
.WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config
|
||||
{
|
||||
StringType = CleanStringType.Utf8 | CleanStringType.Unchanged,
|
||||
|
||||
@@ -41,7 +41,8 @@ namespace Umbraco.Tests.TestHelpers
|
||||
container.RegisterSingleton<IProfiler>(factory => Mock.Of<IProfiler>());
|
||||
|
||||
var logger = new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>());
|
||||
var pluginManager = new TypeLoader(NullCacheProvider.Instance,
|
||||
var pluginManager = new TypeLoader(NullCacheProvider.Instance,
|
||||
SettingsForTests.GenerateMockGlobalSettings(),
|
||||
logger,
|
||||
false);
|
||||
container.RegisterInstance(pluginManager);
|
||||
|
||||
+1
-10
@@ -26,16 +26,7 @@ namespace Umbraco.Tests.TestHelpers.ControllerTesting
|
||||
{
|
||||
var sessionId = Guid.NewGuid().ToString();
|
||||
var identity = new UmbracoBackOfficeIdentity(
|
||||
new UserData(sessionId)
|
||||
{
|
||||
SecurityStamp = sessionId,
|
||||
Id = 0,
|
||||
Roles = new[] { "admin" },
|
||||
AllowedApplications = new[] { "content", "media", "members" },
|
||||
Culture = "en-US",
|
||||
RealName = "Admin",
|
||||
Username = "admin"
|
||||
});
|
||||
-1, "admin", "Admin", null, null, "en-US", sessionId, sessionId, new[] { "content", "media", "members" }, new[] { "admin" });
|
||||
|
||||
return Task.FromResult(new AuthenticationTicket(identity,
|
||||
new AuthenticationProperties()
|
||||
|
||||
@@ -68,8 +68,7 @@ namespace Umbraco.Tests.TestHelpers.ControllerTesting
|
||||
localizedTextService:Mock.Of<ILocalizedTextService>(),
|
||||
sectionService:Mock.Of<ISectionService>());
|
||||
|
||||
//ensure the configuration matches the current version for tests
|
||||
SettingsForTests.ConfigurationStatus = UmbracoVersion.SemanticVersion.ToSemanticString();
|
||||
var globalSettings = SettingsForTests.GenerateMockGlobalSettings();
|
||||
|
||||
// fixme v8?
|
||||
////new app context
|
||||
@@ -85,19 +84,25 @@ namespace Umbraco.Tests.TestHelpers.ControllerTesting
|
||||
// new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()),
|
||||
// true);
|
||||
|
||||
var httpContextItems = new Dictionary<string, object>
|
||||
{
|
||||
//add the special owin environment to the httpcontext items, this is how the GetOwinContext works
|
||||
["owin.Environment"] = new Dictionary<string, object>()
|
||||
};
|
||||
|
||||
//httpcontext with an auth'd user
|
||||
var httpContext = Mock.Of<HttpContextBase>(
|
||||
http => http.User == owinContext.Authentication.User
|
||||
//ensure the request exists with a cookies collection
|
||||
&& http.Request == Mock.Of<HttpRequestBase>(r => r.Cookies == new HttpCookieCollection())
|
||||
//ensure the request exists with an items collection
|
||||
&& http.Items == Mock.Of<IDictionary>());
|
||||
&& http.Items == httpContextItems);
|
||||
//chuck it into the props since this is what MS does when hosted and it's needed there
|
||||
request.Properties["MS_HttpContext"] = httpContext;
|
||||
|
||||
var backofficeIdentity = (UmbracoBackOfficeIdentity) owinContext.Authentication.User.Identity;
|
||||
|
||||
var webSecurity = new Mock<WebSecurity>(null, null);
|
||||
var webSecurity = new Mock<WebSecurity>(null, null, globalSettings);
|
||||
|
||||
//mock CurrentUser
|
||||
var groups = new List<ReadOnlyUserGroup>();
|
||||
@@ -142,6 +147,7 @@ namespace Umbraco.Tests.TestHelpers.ControllerTesting
|
||||
webSecurity.Object,
|
||||
Mock.Of<IUmbracoSettingsSection>(section => section.WebRouting == Mock.Of<IWebRoutingSection>(routingSection => routingSection.UrlProviderMode == UrlProviderMode.Auto.ToString())),
|
||||
Enumerable.Empty<IUrlProvider>(),
|
||||
globalSettings,
|
||||
true); //replace it
|
||||
|
||||
var urlHelper = new Mock<IUrlProvider>();
|
||||
|
||||
@@ -5,11 +5,17 @@ using Moq;
|
||||
using Umbraco.Core;
|
||||
using Umbraco.Core.Configuration;
|
||||
using Umbraco.Core.Configuration.UmbracoSettings;
|
||||
using Umbraco.Core.IO;
|
||||
|
||||
namespace Umbraco.Tests.TestHelpers
|
||||
{
|
||||
public class SettingsForTests
|
||||
{
|
||||
public static void ConfigureSettings(IGlobalSettings settings)
|
||||
{
|
||||
UmbracoConfig.For.SetGlobalConfig(settings);
|
||||
}
|
||||
|
||||
// umbracoSettings
|
||||
|
||||
/// <summary>
|
||||
@@ -21,11 +27,28 @@ namespace Umbraco.Tests.TestHelpers
|
||||
UmbracoConfig.For.SetUmbracoSettings(settings);
|
||||
}
|
||||
|
||||
public static IGlobalSettings GenerateMockGlobalSettings()
|
||||
{
|
||||
var config = Mock.Of<IGlobalSettings>(
|
||||
settings =>
|
||||
settings.ConfigurationStatus == UmbracoVersion.SemanticVersion.ToSemanticString() &&
|
||||
settings.UseHttps == false &&
|
||||
settings.HideTopLevelNodeFromPath == false &&
|
||||
settings.Path == IOHelper.ResolveUrl("~/umbraco") &&
|
||||
settings.UseDirectoryUrls == true &&
|
||||
settings.TimeOutInMinutes == 20 &&
|
||||
settings.DefaultUILanguage == "en" &&
|
||||
settings.LocalTempStorageLocation == LocalTempStorage.Default &&
|
||||
settings.ReservedPaths == (GlobalSettings.StaticReservedPaths + "~/umbraco") &&
|
||||
settings.ReservedUrls == GlobalSettings.StaticReservedUrls);
|
||||
return config;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns generated settings which can be stubbed to return whatever values necessary
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static IUmbracoSettingsSection GenerateMockSettings()
|
||||
public static IUmbracoSettingsSection GenerateMockUmbracoSettings()
|
||||
{
|
||||
var settings = new Mock<IUmbracoSettingsSection>();
|
||||
|
||||
@@ -68,103 +91,83 @@ namespace Umbraco.Tests.TestHelpers
|
||||
return settings.Object;
|
||||
}
|
||||
|
||||
// from appSettings
|
||||
//// from appSettings
|
||||
|
||||
private static readonly IDictionary<string, string> SavedAppSettings = new Dictionary<string, string>();
|
||||
//private static readonly IDictionary<string, string> SavedAppSettings = new Dictionary<string, string>();
|
||||
|
||||
static void SaveSetting(string key)
|
||||
{
|
||||
SavedAppSettings[key] = ConfigurationManager.AppSettings[key];
|
||||
}
|
||||
//static void SaveSetting(string key)
|
||||
//{
|
||||
// SavedAppSettings[key] = ConfigurationManager.AppSettings[key];
|
||||
//}
|
||||
|
||||
static void SaveSettings()
|
||||
{
|
||||
SaveSetting("umbracoHideTopLevelNodeFromPath");
|
||||
SaveSetting("umbracoUseDirectoryUrls");
|
||||
SaveSetting("umbracoPath");
|
||||
SaveSetting("umbracoReservedPaths");
|
||||
SaveSetting("umbracoReservedUrls");
|
||||
SaveSetting("umbracoConfigurationStatus");
|
||||
}
|
||||
//static void SaveSettings()
|
||||
//{
|
||||
// SaveSetting("umbracoHideTopLevelNodeFromPath");
|
||||
// SaveSetting("umbracoUseDirectoryUrls");
|
||||
// SaveSetting("umbracoPath");
|
||||
// SaveSetting("umbracoReservedPaths");
|
||||
// SaveSetting("umbracoReservedUrls");
|
||||
// SaveSetting("umbracoConfigurationStatus");
|
||||
//}
|
||||
|
||||
public static bool HideTopLevelNodeFromPath
|
||||
{
|
||||
get { return GlobalSettings.HideTopLevelNodeFromPath; }
|
||||
set { ConfigurationManager.AppSettings.Set("umbracoHideTopLevelNodeFromPath", value ? "true" : "false"); }
|
||||
}
|
||||
|
||||
public static bool UseDirectoryUrls
|
||||
{
|
||||
get { return GlobalSettings.UseDirectoryUrls; }
|
||||
set { ConfigurationManager.AppSettings.Set("umbracoUseDirectoryUrls", value ? "true" : "false"); }
|
||||
}
|
||||
|
||||
public static string UmbracoPath
|
||||
{
|
||||
get { return GlobalSettings.Path; }
|
||||
set { ConfigurationManager.AppSettings.Set("umbracoPath", value); }
|
||||
}
|
||||
|
||||
public static string ReservedPaths
|
||||
{
|
||||
get { return GlobalSettings.ReservedPaths; }
|
||||
set { GlobalSettings.ReservedPaths = value; }
|
||||
}
|
||||
|
||||
public static string ReservedUrls
|
||||
{
|
||||
get { return GlobalSettings.ReservedUrls; }
|
||||
set { GlobalSettings.ReservedUrls = value; }
|
||||
}
|
||||
|
||||
public static string ConfigurationStatus
|
||||
{
|
||||
get { return GlobalSettings.ConfigurationStatus; }
|
||||
set { ConfigurationManager.AppSettings.Set("umbracoConfigurationStatus", value); }
|
||||
}
|
||||
|
||||
|
||||
// reset & defaults
|
||||
|
||||
static SettingsForTests()
|
||||
{
|
||||
SaveSettings();
|
||||
}
|
||||
//static SettingsForTests()
|
||||
//{
|
||||
// //SaveSettings();
|
||||
//}
|
||||
|
||||
public static void Reset()
|
||||
{
|
||||
ResetUmbracoSettings();
|
||||
ResetSettings();
|
||||
GlobalSettings.Reset();
|
||||
|
||||
foreach (var kvp in SavedAppSettings)
|
||||
ConfigurationManager.AppSettings.Set(kvp.Key, kvp.Value);
|
||||
//foreach (var kvp in SavedAppSettings)
|
||||
// ConfigurationManager.AppSettings.Set(kvp.Key, kvp.Value);
|
||||
|
||||
// set some defaults that are wrong in the config file?!
|
||||
// this is annoying, really
|
||||
HideTopLevelNodeFromPath = false;
|
||||
//// set some defaults that are wrong in the config file?!
|
||||
//// this is annoying, really
|
||||
//HideTopLevelNodeFromPath = false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This sets all settings back to default settings
|
||||
/// </summary>
|
||||
private static void ResetUmbracoSettings()
|
||||
private static void ResetSettings()
|
||||
{
|
||||
ConfigureSettings(GetDefault());
|
||||
_defaultGlobalSettings = null;
|
||||
ConfigureSettings(GetDefaultUmbracoSettings());
|
||||
ConfigureSettings(GetDefaultGlobalSettings());
|
||||
}
|
||||
|
||||
private static IUmbracoSettingsSection _defaultSettings;
|
||||
private static IUmbracoSettingsSection _defaultUmbracoSettings;
|
||||
private static IGlobalSettings _defaultGlobalSettings;
|
||||
|
||||
internal static IUmbracoSettingsSection GetDefault()
|
||||
internal static IGlobalSettings GetDefaultGlobalSettings()
|
||||
{
|
||||
if (_defaultSettings == null)
|
||||
if (_defaultGlobalSettings == null)
|
||||
{
|
||||
_defaultGlobalSettings = GenerateMockGlobalSettings();
|
||||
}
|
||||
return _defaultGlobalSettings;
|
||||
}
|
||||
|
||||
internal static IUmbracoSettingsSection GetDefaultUmbracoSettings()
|
||||
{
|
||||
if (_defaultUmbracoSettings == null)
|
||||
{
|
||||
//TODO: Just make this mocks instead of reading from the config
|
||||
|
||||
var config = new FileInfo(TestHelper.MapPathForTest("~/Configurations/UmbracoSettings/web.config"));
|
||||
|
||||
var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = config.FullName };
|
||||
var configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
|
||||
_defaultSettings = configuration.GetSection("umbracoConfiguration/defaultSettings") as UmbracoSettingsSection;
|
||||
_defaultUmbracoSettings = configuration.GetSection("umbracoConfiguration/defaultSettings") as UmbracoSettingsSection;
|
||||
}
|
||||
|
||||
return _defaultSettings;
|
||||
return _defaultUmbracoSettings;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ using System.Web;
|
||||
using LightInject;
|
||||
using Moq;
|
||||
using Umbraco.Core;
|
||||
using Umbraco.Core.Configuration;
|
||||
using Umbraco.Core.Configuration.UmbracoSettings;
|
||||
using Umbraco.Core.Events;
|
||||
using Umbraco.Core.Logging;
|
||||
@@ -112,16 +113,20 @@ namespace Umbraco.Tests.TestHelpers
|
||||
publishedSnapshotServiceMock.Setup(x => x.CreatePublishedSnapshot(It.IsAny<string>())).Returns(publishedSnapshot);
|
||||
var publishedSnapshotService = publishedSnapshotServiceMock.Object;
|
||||
|
||||
var webSecurity = new Mock<WebSecurity>(null, null).Object;
|
||||
var settings = GetUmbracoSettings();
|
||||
var umbracoSettings = GetUmbracoSettings();
|
||||
var globalSettings = GetGlobalSettings();
|
||||
var webSecurity = new Mock<WebSecurity>(null, null, globalSettings).Object;
|
||||
var urlProviders = Enumerable.Empty<IUrlProvider>();
|
||||
|
||||
if (accessor == null) accessor = new TestUmbracoContextAccessor();
|
||||
return UmbracoContext.EnsureContext(accessor, httpContext, publishedSnapshotService, webSecurity, settings, urlProviders, true);
|
||||
return UmbracoContext.EnsureContext(accessor, httpContext, publishedSnapshotService, webSecurity, umbracoSettings, urlProviders, globalSettings, true);
|
||||
}
|
||||
|
||||
public IUmbracoSettingsSection GetUmbracoSettings()
|
||||
{
|
||||
//fixme Why not use the SettingsForTest.GenerateMock ... ?
|
||||
//fixme Shouldn't we use the default ones so they are the same instance for each test?
|
||||
|
||||
var umbracoSettingsMock = new Mock<IUmbracoSettingsSection>();
|
||||
var webRoutingSectionMock = new Mock<IWebRoutingSection>();
|
||||
webRoutingSectionMock.Setup(x => x.UrlProviderMode).Returns(UrlProviderMode.Auto.ToString());
|
||||
@@ -129,6 +134,11 @@ namespace Umbraco.Tests.TestHelpers
|
||||
return umbracoSettingsMock.Object;
|
||||
}
|
||||
|
||||
public IGlobalSettings GetGlobalSettings()
|
||||
{
|
||||
return SettingsForTests.GetDefaultGlobalSettings();
|
||||
}
|
||||
|
||||
#region Inner classes
|
||||
|
||||
private class MockDbConnection : DbConnection
|
||||
|
||||
@@ -9,6 +9,7 @@ using NPoco;
|
||||
using Umbraco.Core;
|
||||
using Umbraco.Core.Cache;
|
||||
using Umbraco.Core.Composing;
|
||||
using Umbraco.Core.Configuration;
|
||||
using Umbraco.Core.Events;
|
||||
using Umbraco.Core.IO;
|
||||
using Umbraco.Core.Logging;
|
||||
@@ -89,13 +90,14 @@ namespace Umbraco.Tests.TestHelpers
|
||||
/// <summary>
|
||||
/// Gets a ServiceContext.
|
||||
/// </summary>
|
||||
/// <param name="repositoryFactory">A repository factory.</param>
|
||||
/// <param name="dbUnitOfWorkProvider">A database unit of work provider.</param>
|
||||
/// <param name="scopeAccessor"></param>
|
||||
/// <param name="cache">A cache.</param>
|
||||
/// <param name="logger">A logger.</param>
|
||||
/// <param name="globalSettings"></param>
|
||||
/// <param name="eventMessagesFactory">An event messages factory.</param>
|
||||
/// <param name="urlSegmentProviders">Some url segment providers.</param>
|
||||
/// <param name="container">A container.</param>
|
||||
/// <param name="scopeProvider"></param>
|
||||
/// <returns>A ServiceContext.</returns>
|
||||
/// <remarks>Should be used sparingly for integration tests only - for unit tests
|
||||
/// just mock the services to be passed to the ctor of the ServiceContext.</remarks>
|
||||
@@ -103,6 +105,7 @@ namespace Umbraco.Tests.TestHelpers
|
||||
IScopeProvider scopeProvider, IScopeAccessor scopeAccessor,
|
||||
CacheHelper cache,
|
||||
ILogger logger,
|
||||
IGlobalSettings globalSettings,
|
||||
IEventMessagesFactory eventMessagesFactory,
|
||||
IEnumerable<IUrlSegmentProvider> urlSegmentProviders,
|
||||
IServiceFactory container = null)
|
||||
@@ -156,10 +159,10 @@ namespace Umbraco.Tests.TestHelpers
|
||||
var runtimeState = Mock.Of<IRuntimeState>();
|
||||
var idkMap = new IdkMap(scopeProvider);
|
||||
|
||||
var userService = GetLazyService<IUserService>(container, c => new UserService(scopeProvider, logger, eventMessagesFactory, runtimeState, GetRepo<IUserRepository>(c), GetRepo<IUserGroupRepository>(c)));
|
||||
var userService = GetLazyService<IUserService>(container, c => new UserService(scopeProvider, logger, eventMessagesFactory, runtimeState, GetRepo<IUserRepository>(c), GetRepo<IUserGroupRepository>(c),globalSettings));
|
||||
var dataTypeService = GetLazyService<IDataTypeService>(container, c => new DataTypeService(scopeProvider, logger, eventMessagesFactory, GetRepo<IDataTypeRepository>(c), GetRepo<IDataTypeContainerRepository>(c), GetRepo<IAuditRepository>(c), GetRepo<IEntityRepository>(c), GetRepo<IContentTypeRepository>(c)));
|
||||
var contentService = GetLazyService<IContentService>(container, c => new ContentService(scopeProvider, logger, eventMessagesFactory, mediaFileSystem, GetRepo<IDocumentRepository>(c), GetRepo<IEntityRepository>(c), GetRepo<IAuditRepository>(c), GetRepo<IContentTypeRepository>(c), GetRepo<IDocumentBlueprintRepository>(c)));
|
||||
var notificationService = GetLazyService<INotificationService>(container, c => new NotificationService(scopeProvider, userService.Value, contentService.Value, logger, GetRepo<INotificationsRepository>(c)));
|
||||
var notificationService = GetLazyService<INotificationService>(container, c => new NotificationService(scopeProvider, userService.Value, contentService.Value, logger, GetRepo<INotificationsRepository>(c),globalSettings));
|
||||
var serverRegistrationService = GetLazyService<IServerRegistrationService>(container, c => new ServerRegistrationService(scopeProvider, logger, eventMessagesFactory, GetRepo<IServerRegistrationRepository>(c)));
|
||||
var memberGroupService = GetLazyService<IMemberGroupService>(container, c => new MemberGroupService(scopeProvider, logger, eventMessagesFactory, GetRepo<IMemberGroupRepository>(c)));
|
||||
var memberService = GetLazyService<IMemberService>(container, c => new MemberService(scopeProvider, logger, eventMessagesFactory, memberGroupService.Value, mediaFileSystem, GetRepo<IMemberRepository>(c), GetRepo<IMemberTypeRepository>(c), GetRepo<IMemberGroupRepository>(c), GetRepo<IAuditRepository>(c)));
|
||||
|
||||
@@ -134,7 +134,9 @@ namespace Umbraco.Tests.TestHelpers
|
||||
}
|
||||
|
||||
// ensure the configuration matches the current version for tests
|
||||
SettingsForTests.ConfigurationStatus = UmbracoVersion.Current.ToString(3);
|
||||
var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container
|
||||
globalSettingsMock.Setup(x => x.ConfigurationStatus).Returns(UmbracoVersion.Current.ToString(3));
|
||||
SettingsForTests.ConfigureSettings(globalSettingsMock.Object);
|
||||
|
||||
using (ProfilingLogger.TraceDuration<TestWithDatabaseBase>("Initialize database."))
|
||||
{
|
||||
@@ -247,22 +249,25 @@ namespace Umbraco.Tests.TestHelpers
|
||||
var cache = NullCacheProvider.Instance;
|
||||
|
||||
ContentTypesCache = new PublishedContentTypeCache(
|
||||
Current.Services.ContentTypeService,
|
||||
Current.Services.MediaTypeService,
|
||||
Current.Services.MemberTypeService,
|
||||
Container.GetInstance<IContentTypeService>(),
|
||||
Container.GetInstance<IMediaTypeService>(),
|
||||
Container.GetInstance<IMemberTypeService>(),
|
||||
Container.GetInstance<IPublishedContentTypeFactory>(),
|
||||
Current.Logger);
|
||||
Logger);
|
||||
|
||||
// testing=true so XmlStore will not use the file nor the database
|
||||
|
||||
var publishedSnapshotAccessor = new UmbracoContextPublishedSnapshotAccessor(Umbraco.Web.Composing.Current.UmbracoContextAccessor);
|
||||
var service = new PublishedSnapshotService(
|
||||
Current.Services,
|
||||
ServiceContext,
|
||||
Container.GetInstance<IPublishedContentTypeFactory>(),
|
||||
(ScopeProvider) Current.ScopeProvider,
|
||||
ScopeProvider,
|
||||
cache, publishedSnapshotAccessor,
|
||||
Current.Container.GetInstance<IDocumentRepository>(), Current.Container.GetInstance<IMediaRepository>(), Current.Container.GetInstance<IMemberRepository>(),
|
||||
Current.Logger, ContentTypesCache, null, true, Options.PublishedRepositoryEvents);
|
||||
Container.GetInstance<IDocumentRepository>(), Container.GetInstance<IMediaRepository>(), Container.GetInstance<IMemberRepository>(),
|
||||
Logger,
|
||||
Container.GetInstance<IGlobalSettings>(),
|
||||
ContentTypesCache,
|
||||
null, true, Options.PublishedRepositoryEvents);
|
||||
|
||||
// initialize PublishedCacheService content with an Xml source
|
||||
service.XmlStore.GetXmlDocument = () =>
|
||||
@@ -331,14 +336,14 @@ namespace Umbraco.Tests.TestHelpers
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Core.Composing.Current.Logger.Error<TestWithDatabaseBase>("Could not remove the old database file", ex);
|
||||
Logger.Error<TestWithDatabaseBase>("Could not remove the old database file", ex);
|
||||
|
||||
// swallow this exception - that's because a sub class might require further teardown logic
|
||||
onFail?.Invoke(ex);
|
||||
}
|
||||
}
|
||||
|
||||
protected UmbracoContext GetUmbracoContext(string url, int templateId = 1234, RouteData routeData = null, bool setSingleton = false, IUmbracoSettingsSection umbracoSettings = null, IEnumerable<IUrlProvider> urlProviders = null)
|
||||
protected UmbracoContext GetUmbracoContext(string url, int templateId = 1234, RouteData routeData = null, bool setSingleton = false, IUmbracoSettingsSection umbracoSettings = null, IEnumerable<IUrlProvider> urlProviders = null, IGlobalSettings globalSettings = null)
|
||||
{
|
||||
// ensure we have a PublishedCachesService
|
||||
var service = PublishedSnapshotService as PublishedSnapshotService;
|
||||
@@ -358,9 +363,10 @@ namespace Umbraco.Tests.TestHelpers
|
||||
var umbracoContext = new UmbracoContext(
|
||||
httpContext,
|
||||
service,
|
||||
new WebSecurity(httpContext, Core.Composing.Current.Services.UserService),
|
||||
umbracoSettings ?? SettingsForTests.GetDefault(),
|
||||
urlProviders ?? Enumerable.Empty<IUrlProvider>());
|
||||
new WebSecurity(httpContext, Container.GetInstance<IUserService>(), Container.GetInstance<IGlobalSettings>()),
|
||||
umbracoSettings ?? Container.GetInstance<IUmbracoSettingsSection>(),
|
||||
urlProviders ?? Enumerable.Empty<IUrlProvider>(),
|
||||
globalSettings ?? Container.GetInstance<IGlobalSettings>());
|
||||
|
||||
if (setSingleton)
|
||||
Umbraco.Web.Composing.Current.UmbracoContextAccessor.UmbracoContext = umbracoContext;
|
||||
|
||||
@@ -12,6 +12,7 @@ using Umbraco.Core.Cache;
|
||||
using Umbraco.Core.Components;
|
||||
using Umbraco.Core.Composing;
|
||||
using Umbraco.Core.Composing.CompositionRoots;
|
||||
using Umbraco.Core.Configuration;
|
||||
using Umbraco.Core.Events;
|
||||
using Umbraco.Core.IO;
|
||||
using Umbraco.Core.Logging;
|
||||
@@ -225,7 +226,7 @@ namespace Umbraco.Tests.Testing
|
||||
|
||||
private static TypeLoader CreateCommonPluginManager(IServiceFactory f)
|
||||
{
|
||||
return new TypeLoader(f.GetInstance<CacheHelper>().RuntimeCache, f.GetInstance<ProfilingLogger>(), false)
|
||||
return new TypeLoader(f.GetInstance<CacheHelper>().RuntimeCache, f.GetInstance<IGlobalSettings>(), f.GetInstance<ProfilingLogger>(), false)
|
||||
{
|
||||
AssembliesToScan = new[]
|
||||
{
|
||||
@@ -249,15 +250,20 @@ namespace Umbraco.Tests.Testing
|
||||
{
|
||||
if (withApplication == false) return;
|
||||
|
||||
var settings = SettingsForTests.GetDefault();
|
||||
var umbracoSettings = SettingsForTests.GetDefaultUmbracoSettings();
|
||||
var globalSettings = SettingsForTests.GetDefaultGlobalSettings();
|
||||
//apply these globally
|
||||
SettingsForTests.ConfigureSettings(umbracoSettings);
|
||||
SettingsForTests.ConfigureSettings(globalSettings);
|
||||
|
||||
// default Datalayer/Repositories/SQL/Database/etc...
|
||||
Container.RegisterFrom<RepositoryCompositionRoot>();
|
||||
|
||||
// register basic stuff that might need to be there for some container resolvers to work
|
||||
Container.RegisterSingleton(factory => SettingsForTests.GetDefault());
|
||||
Container.RegisterSingleton(factory => settings.Content);
|
||||
Container.RegisterSingleton(factory => settings.Templates);
|
||||
Container.RegisterSingleton(factory => umbracoSettings);
|
||||
Container.RegisterSingleton(factory => globalSettings);
|
||||
Container.RegisterSingleton(factory => umbracoSettings.Content);
|
||||
Container.RegisterSingleton(factory => umbracoSettings.Templates);
|
||||
Container.Register(factory => new MediaFileSystem(Mock.Of<IFileSystem>()));
|
||||
Container.RegisterSingleton<IExamineManager>(factory => ExamineManager.Instance);
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<Project ToolsVersion="15.0">
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
@@ -602,20 +603,27 @@
|
||||
<ItemGroup>
|
||||
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
|
||||
</ItemGroup>
|
||||
<!-- get NuGet packages directory -->
|
||||
<PropertyGroup>
|
||||
<NuGetPackages>$(NuGetPackageFolders.Split(';')[0])</NuGetPackages>
|
||||
</PropertyGroup>
|
||||
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<PropertyGroup>
|
||||
<PostBuildEvent>
|
||||
</PostBuildEvent>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup>
|
||||
<PreBuildEvent>REM xcopy "$(NugetPackages)\SqlServerCE.4.0.0.1\amd64\*.*" "$(TargetDir)amd64\" /Y /F /E /I /C /D
|
||||
REM xcopy "$(NugetPackages)\SqlServerCE.4.0.0.1\x86\*.*" "$(TargetDir)x86\" /Y /F /E /I /C /D</PreBuildEvent>
|
||||
</PropertyGroup>
|
||||
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
||||
Other similar extension points exist, see Microsoft.Common.targets.
|
||||
|
||||
<Target Name="BeforeBuild">
|
||||
<Message Text="-BeforeBuild-" Importance="high" />
|
||||
<Message Text="MSBuildExtensionsPath: $(MSBuildExtensionsPath)" Importance="high" />
|
||||
<Message Text="WebPublishingTasks: $(WebPublishingTasks)" Importance="high" />
|
||||
<Message Text="NuGetPackageFolders: $(NuGetPackageFolders)" Importance="high" />
|
||||
<Message Text="NuGetPackages: $(NuGetPackages)" Importance="high" />
|
||||
<!-- copy SqlCe -->
|
||||
<ItemGroup>
|
||||
<SqlCE64 Include="$(NuGetPackages)SqlServerCE\4.0.0.1\amd64\*.*" />
|
||||
<SqlCE86 Include="$(NuGetPackages)SqlServerCE\4.0.0.1\x86\*.*" />
|
||||
</ItemGroup>
|
||||
<Message Text="Copy SqlCe files to $(TargetDir)" Importance="high" />
|
||||
<Copy SourceFiles="@(SqlCe64)" DestinationFolder="$(TargetDir)amd64" OverwriteReadOnlyFiles="true" SkipUnchangedFiles="true" />
|
||||
<Copy SourceFiles="@(SqlCe86)" DestinationFolder="$(TargetDir)x86" OverwriteReadOnlyFiles="true" SkipUnchangedFiles="true" />
|
||||
</Target>
|
||||
<Target Name="AfterBuild">
|
||||
</Target>
|
||||
-->
|
||||
|
||||
</Project>
|
||||
@@ -32,7 +32,7 @@ namespace Umbraco.Tests.UmbracoExamine
|
||||
{
|
||||
base.Compose();
|
||||
|
||||
Container.RegisterSingleton<IShortStringHelper>(_ => new DefaultShortStringHelper(SettingsForTests.GetDefault()));
|
||||
Container.RegisterSingleton<IShortStringHelper>(_ => new DefaultShortStringHelper(SettingsForTests.GetDefaultUmbracoSettings()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,8 @@ namespace Umbraco.Tests.Web.Controllers
|
||||
public void Ensure_Same_Area1()
|
||||
{
|
||||
Assert.Throws<InvalidOperationException>(() =>
|
||||
new PluginControllerArea(new PluginControllerMetadata[]
|
||||
new PluginControllerArea(TestObjects.GetGlobalSettings(),
|
||||
new PluginControllerMetadata[]
|
||||
{
|
||||
PluginController.GetMetadata(typeof(Plugin1Controller)),
|
||||
PluginController.GetMetadata(typeof(Plugin2Controller)),
|
||||
@@ -26,7 +27,8 @@ namespace Umbraco.Tests.Web.Controllers
|
||||
public void Ensure_Same_Area3()
|
||||
{
|
||||
Assert.Throws<InvalidOperationException>(() =>
|
||||
new PluginControllerArea(new PluginControllerMetadata[]
|
||||
new PluginControllerArea(TestObjects.GetGlobalSettings(),
|
||||
new PluginControllerMetadata[]
|
||||
{
|
||||
PluginController.GetMetadata(typeof(Plugin1Controller)),
|
||||
PluginController.GetMetadata(typeof(Plugin2Controller)),
|
||||
@@ -37,7 +39,8 @@ namespace Umbraco.Tests.Web.Controllers
|
||||
[Test]
|
||||
public void Ensure_Same_Area2()
|
||||
{
|
||||
var area = new PluginControllerArea(new PluginControllerMetadata[]
|
||||
var area = new PluginControllerArea(TestObjects.GetGlobalSettings(),
|
||||
new PluginControllerMetadata[]
|
||||
{
|
||||
PluginController.GetMetadata(typeof(Plugin1Controller)),
|
||||
PluginController.GetMetadata(typeof(Plugin2Controller))
|
||||
|
||||
@@ -58,6 +58,7 @@ namespace Umbraco.Tests.Web.Mvc
|
||||
[Test]
|
||||
public void Matches_Default_Index()
|
||||
{
|
||||
var globalSettings = TestObjects.GetGlobalSettings();
|
||||
var attr = new RenderIndexActionSelectorAttribute();
|
||||
var req = new RequestContext();
|
||||
//var appCtx = new ApplicationContext(
|
||||
@@ -67,9 +68,10 @@ namespace Umbraco.Tests.Web.Mvc
|
||||
Current.UmbracoContextAccessor,
|
||||
Mock.Of<HttpContextBase>(),
|
||||
Mock.Of<IPublishedSnapshotService>(),
|
||||
new Mock<WebSecurity>(null, null).Object,
|
||||
new Mock<WebSecurity>(null, null, globalSettings).Object,
|
||||
TestObjects.GetUmbracoSettings(),
|
||||
Enumerable.Empty<IUrlProvider>(),
|
||||
globalSettings,
|
||||
true);
|
||||
var ctrl = new MatchesDefaultIndexController { UmbracoContext = umbCtx };
|
||||
var controllerCtx = new ControllerContext(req, ctrl);
|
||||
@@ -82,15 +84,17 @@ namespace Umbraco.Tests.Web.Mvc
|
||||
[Test]
|
||||
public void Matches_Overriden_Index()
|
||||
{
|
||||
var globalSettings = TestObjects.GetGlobalSettings();
|
||||
var attr = new RenderIndexActionSelectorAttribute();
|
||||
var req = new RequestContext();
|
||||
var umbCtx = UmbracoContext.EnsureContext(
|
||||
Current.UmbracoContextAccessor,
|
||||
Mock.Of<HttpContextBase>(),
|
||||
Mock.Of<IPublishedSnapshotService>(),
|
||||
new Mock<WebSecurity>(null, null).Object,
|
||||
new Mock<WebSecurity>(null, null, globalSettings).Object,
|
||||
TestObjects.GetUmbracoSettings(),
|
||||
Enumerable.Empty<IUrlProvider>(),
|
||||
globalSettings,
|
||||
true);
|
||||
var ctrl = new MatchesOverriddenIndexController { UmbracoContext = umbCtx };
|
||||
var controllerCtx = new ControllerContext(req, ctrl);
|
||||
@@ -103,15 +107,17 @@ namespace Umbraco.Tests.Web.Mvc
|
||||
[Test]
|
||||
public void Matches_Custom_Index()
|
||||
{
|
||||
var globalSettings = TestObjects.GetGlobalSettings();
|
||||
var attr = new RenderIndexActionSelectorAttribute();
|
||||
var req = new RequestContext();
|
||||
var umbCtx = UmbracoContext.EnsureContext(
|
||||
Current.UmbracoContextAccessor,
|
||||
Mock.Of<HttpContextBase>(),
|
||||
Mock.Of<IPublishedSnapshotService>(),
|
||||
new Mock<WebSecurity>(null, null).Object,
|
||||
new Mock<WebSecurity>(null, null, globalSettings).Object,
|
||||
TestObjects.GetUmbracoSettings(),
|
||||
Enumerable.Empty<IUrlProvider>(),
|
||||
globalSettings,
|
||||
true);
|
||||
var ctrl = new MatchesCustomIndexController { UmbracoContext = umbCtx };
|
||||
var controllerCtx = new ControllerContext(req, ctrl);
|
||||
@@ -124,15 +130,17 @@ namespace Umbraco.Tests.Web.Mvc
|
||||
[Test]
|
||||
public void Matches_Async_Index_Same_Signature()
|
||||
{
|
||||
var globalSettings = TestObjects.GetGlobalSettings();
|
||||
var attr = new RenderIndexActionSelectorAttribute();
|
||||
var req = new RequestContext();
|
||||
var umbCtx = UmbracoContext.EnsureContext(
|
||||
Current.UmbracoContextAccessor,
|
||||
Mock.Of<HttpContextBase>(),
|
||||
Mock.Of<IPublishedSnapshotService>(),
|
||||
new Mock<WebSecurity>(null, null).Object,
|
||||
new Mock<WebSecurity>(null, null, globalSettings).Object,
|
||||
TestObjects.GetUmbracoSettings(),
|
||||
Enumerable.Empty<IUrlProvider>(),
|
||||
globalSettings,
|
||||
true);
|
||||
var ctrl = new MatchesAsyncIndexController { UmbracoContext = umbCtx };
|
||||
var controllerCtx = new ControllerContext(req, ctrl);
|
||||
|
||||
@@ -36,13 +36,15 @@ namespace Umbraco.Tests.Web.Mvc
|
||||
[Test]
|
||||
public void Can_Construct_And_Get_Result()
|
||||
{
|
||||
var globalSettings = TestObjects.GetGlobalSettings();
|
||||
var umbracoContext = UmbracoContext.EnsureContext(
|
||||
Current.UmbracoContextAccessor,
|
||||
new Mock<HttpContextBase>().Object,
|
||||
Mock.Of<IPublishedSnapshotService>(),
|
||||
new Mock<WebSecurity>(null, null).Object,
|
||||
new Mock<WebSecurity>(null, null, globalSettings).Object,
|
||||
TestObjects.GetUmbracoSettings(),
|
||||
Enumerable.Empty<IUrlProvider>(),
|
||||
globalSettings,
|
||||
true);
|
||||
|
||||
var ctrl = new TestSurfaceController { UmbracoContext = umbracoContext };
|
||||
@@ -55,13 +57,15 @@ namespace Umbraco.Tests.Web.Mvc
|
||||
[Test]
|
||||
public void Umbraco_Context_Not_Null()
|
||||
{
|
||||
var globalSettings = TestObjects.GetGlobalSettings();
|
||||
var umbCtx = UmbracoContext.EnsureContext(
|
||||
Current.UmbracoContextAccessor,
|
||||
new Mock<HttpContextBase>().Object,
|
||||
Mock.Of<IPublishedSnapshotService>(),
|
||||
new Mock<WebSecurity>(null, null).Object,
|
||||
new Mock<WebSecurity>(null, null, globalSettings).Object,
|
||||
TestObjects.GetUmbracoSettings(),
|
||||
Enumerable.Empty<IUrlProvider>(),
|
||||
globalSettings,
|
||||
true);
|
||||
|
||||
var ctrl = new TestSurfaceController { UmbracoContext = umbCtx };
|
||||
@@ -72,13 +76,15 @@ namespace Umbraco.Tests.Web.Mvc
|
||||
[Test]
|
||||
public void Umbraco_Helper_Not_Null()
|
||||
{
|
||||
var globalSettings = TestObjects.GetGlobalSettings();
|
||||
var umbracoContext = UmbracoContext.EnsureContext(
|
||||
Current.UmbracoContextAccessor,
|
||||
new Mock<HttpContextBase>().Object,
|
||||
Mock.Of<IPublishedSnapshotService>(),
|
||||
new Mock<WebSecurity>(null, null).Object,
|
||||
new Mock<WebSecurity>(null, null, globalSettings).Object,
|
||||
TestObjects.GetUmbracoSettings(),
|
||||
Enumerable.Empty<IUrlProvider>(),
|
||||
globalSettings,
|
||||
true);
|
||||
|
||||
var controller = new TestSurfaceController { UmbracoContext = umbracoContext };
|
||||
@@ -95,14 +101,16 @@ namespace Umbraco.Tests.Web.Mvc
|
||||
publishedSnapshot.Setup(x => x.Members).Returns(Mock.Of<IPublishedMemberCache>());
|
||||
var publishedSnapshotService = new Mock<IPublishedSnapshotService>();
|
||||
publishedSnapshotService.Setup(x => x.CreatePublishedSnapshot(It.IsAny<string>())).Returns(publishedSnapshot.Object);
|
||||
var globalSettings = TestObjects.GetGlobalSettings();
|
||||
|
||||
var umbracoContext = UmbracoContext.EnsureContext(
|
||||
Current.UmbracoContextAccessor,
|
||||
new Mock<HttpContextBase>().Object,
|
||||
publishedSnapshotService.Object,
|
||||
new Mock<WebSecurity>(null, null).Object,
|
||||
new Mock<WebSecurity>(null, null, globalSettings).Object,
|
||||
Mock.Of<IUmbracoSettingsSection>(section => section.WebRouting == Mock.Of<IWebRoutingSection>(routingSection => routingSection.UrlProviderMode == "AutoLegacy")),
|
||||
Enumerable.Empty<IUrlProvider>(),
|
||||
globalSettings,
|
||||
true);
|
||||
|
||||
var helper = new UmbracoHelper(
|
||||
@@ -130,14 +138,16 @@ namespace Umbraco.Tests.Web.Mvc
|
||||
public void Mock_Current_Page()
|
||||
{
|
||||
var webRoutingSettings = Mock.Of<IWebRoutingSection>(section => section.UrlProviderMode == "AutoLegacy");
|
||||
var globalSettings = TestObjects.GetGlobalSettings();
|
||||
|
||||
var umbracoContext = UmbracoContext.EnsureContext(
|
||||
Current.UmbracoContextAccessor,
|
||||
new Mock<HttpContextBase>().Object,
|
||||
Mock.Of<IPublishedSnapshotService>(),
|
||||
new Mock<WebSecurity>(null, null).Object,
|
||||
new Mock<WebSecurity>(null, null, globalSettings).Object,
|
||||
Mock.Of<IUmbracoSettingsSection>(section => section.WebRouting == webRoutingSettings),
|
||||
Enumerable.Empty<IUrlProvider>(),
|
||||
globalSettings,
|
||||
true);
|
||||
|
||||
var content = Mock.Of<IPublishedContent>(publishedContent => publishedContent.Id == 12345);
|
||||
|
||||
@@ -388,7 +388,7 @@ namespace Umbraco.Tests.Web.Mvc
|
||||
|
||||
ViewContext GetViewContext()
|
||||
{
|
||||
var settings = SettingsForTests.GetDefault();
|
||||
var settings = SettingsForTests.GetDefaultUmbracoSettings();
|
||||
var logger = Mock.Of<ILogger>();
|
||||
var umbracoContext = GetUmbracoContext(
|
||||
logger, settings,
|
||||
@@ -425,16 +425,17 @@ namespace Umbraco.Tests.Web.Mvc
|
||||
var factory = Mock.Of<IPublishedContentTypeFactory>();
|
||||
_service = new PublishedSnapshotService(svcCtx, factory, scopeProvider, cache, Enumerable.Empty<IUrlSegmentProvider>(), null,
|
||||
null, null, null,
|
||||
Current.Logger, null, true, false); // no events
|
||||
Current.Logger, TestObjects.GetGlobalSettings(), null, true, false); // no events
|
||||
|
||||
var http = GetHttpContextFactory(url, routeData).HttpContext;
|
||||
|
||||
var ctx = new UmbracoContext(
|
||||
GetHttpContextFactory(url, routeData).HttpContext,
|
||||
_service,
|
||||
new WebSecurity(http, Current.Services.UserService),
|
||||
new WebSecurity(http, Current.Services.UserService, TestObjects.GetGlobalSettings()),
|
||||
TestObjects.GetUmbracoSettings(),
|
||||
Enumerable.Empty<IUrlProvider>());
|
||||
Enumerable.Empty<IUrlProvider>(),
|
||||
TestObjects.GetGlobalSettings());
|
||||
|
||||
//if (setSingleton)
|
||||
//{
|
||||
|
||||
@@ -36,7 +36,8 @@ namespace Umbraco.Tests.Web
|
||||
|
||||
// fixme - bad in a unit test - but Udi has a static ctor that wants it?!
|
||||
var container = new Mock<IServiceContainer>();
|
||||
container.Setup(x => x.GetInstance(typeof(TypeLoader))).Returns(new TypeLoader(NullCacheProvider.Instance, new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>())));
|
||||
container.Setup(x => x.GetInstance(typeof(TypeLoader))).Returns(
|
||||
new TypeLoader(NullCacheProvider.Instance, SettingsForTests.GenerateMockGlobalSettings(), new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>())));
|
||||
container.Setup(x => x.GetInstance(typeof (ServiceContext))).Returns(serviceContext);
|
||||
Current.Container = container.Object;
|
||||
|
||||
@@ -77,15 +78,18 @@ namespace Umbraco.Tests.Web
|
||||
return "/my-test-url";
|
||||
});
|
||||
|
||||
var globalSettings = SettingsForTests.GenerateMockGlobalSettings();
|
||||
|
||||
using (var umbCtx = UmbracoContext.EnsureContext(
|
||||
Umbraco.Web.Composing.Current.UmbracoContextAccessor,
|
||||
Mock.Of<HttpContextBase>(),
|
||||
Mock.Of<IPublishedSnapshotService>(),
|
||||
new Mock<WebSecurity>(null, null).Object,
|
||||
new Mock<WebSecurity>(null, null, globalSettings).Object,
|
||||
//setup a quick mock of the WebRouting section
|
||||
Mock.Of<IUmbracoSettingsSection>(section => section.WebRouting == Mock.Of<IWebRoutingSection>(routingSection => routingSection.UrlProviderMode == "AutoLegacy")),
|
||||
//pass in the custom url provider
|
||||
new[]{ testUrlProvider.Object },
|
||||
globalSettings,
|
||||
true))
|
||||
{
|
||||
var output = TemplateUtilities.ParseInternalLinks(input, umbCtx.UrlProvider);
|
||||
|
||||
@@ -26,9 +26,10 @@ namespace Umbraco.Tests.Web
|
||||
var umbCtx = new UmbracoContext(
|
||||
Mock.Of<HttpContextBase>(),
|
||||
Mock.Of<IPublishedSnapshotService>(),
|
||||
new WebSecurity(Mock.Of<HttpContextBase>(), Current.Services.UserService),
|
||||
new WebSecurity(Mock.Of<HttpContextBase>(), Current.Services.UserService, TestObjects.GetGlobalSettings()),
|
||||
TestObjects.GetUmbracoSettings(),
|
||||
new List<IUrlProvider>());
|
||||
new List<IUrlProvider>(),
|
||||
TestObjects.GetGlobalSettings());
|
||||
var r1 = new RouteData();
|
||||
r1.DataTokens.Add(Core.Constants.Web.UmbracoContextDataToken, umbCtx);
|
||||
|
||||
@@ -42,9 +43,10 @@ namespace Umbraco.Tests.Web
|
||||
var umbCtx = new UmbracoContext(
|
||||
Mock.Of<HttpContextBase>(),
|
||||
Mock.Of<IPublishedSnapshotService>(),
|
||||
new WebSecurity(Mock.Of<HttpContextBase>(), Current.Services.UserService),
|
||||
new WebSecurity(Mock.Of<HttpContextBase>(), Current.Services.UserService, TestObjects.GetGlobalSettings()),
|
||||
TestObjects.GetUmbracoSettings(),
|
||||
new List<IUrlProvider>());
|
||||
new List<IUrlProvider>(),
|
||||
TestObjects.GetGlobalSettings());
|
||||
|
||||
var r1 = new RouteData();
|
||||
r1.DataTokens.Add(Core.Constants.Web.UmbracoContextDataToken, umbCtx);
|
||||
@@ -68,9 +70,10 @@ namespace Umbraco.Tests.Web
|
||||
var umbCtx = new UmbracoContext(
|
||||
Mock.Of<HttpContextBase>(),
|
||||
Mock.Of<IPublishedSnapshotService>(),
|
||||
new WebSecurity(Mock.Of<HttpContextBase>(), Current.Services.UserService),
|
||||
new WebSecurity(Mock.Of<HttpContextBase>(), Current.Services.UserService, TestObjects.GetGlobalSettings()),
|
||||
TestObjects.GetUmbracoSettings(),
|
||||
new List<IUrlProvider>());
|
||||
new List<IUrlProvider>(),
|
||||
TestObjects.GetGlobalSettings());
|
||||
|
||||
var httpContext = Mock.Of<HttpContextBase>();
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"author": "Umbraco HQ",
|
||||
"name": "umbraco",
|
||||
"homepage": "https://github.com/umbraco/umbraco-cms/",
|
||||
"version": "7.1.2",
|
||||
"version": "0.0.0",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user