new mailling for not confirmed emails

This commit is contained in:
Paul Schneider
2021-05-30 12:30:39 +01:00
parent 79d4d64071
commit 0201ea64e6
25 changed files with 46 additions and 31 deletions

View File

@ -0,0 +1,26 @@
using System;
using Microsoft.Dnx.Compilation.CSharp;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.PlatformAbstractions;
using Xunit.Abstractions;
namespace test
{
public class BaseTestContext {
protected IApplicationEnvironment applicationEnvironment = null;
protected IServiceProvider serviceProvider = null;
protected IConfigurationRoot configurationRoot;
protected BeforeCompileContext beforeCompileContext;
protected IServiceProvider provider;
protected IConfigurationRoot configuration;
protected readonly ITestOutputHelper _output;
protected ServerSideFixture _serverFixture;
public BaseTestContext(ITestOutputHelper output, ServerSideFixture serverFixture)
{
this._output = output;
this._serverFixture = serverFixture;
}
}
}

37
test/yavscTests/Makefile Normal file
View File

@ -0,0 +1,37 @@
CONFIGURATION=Debug
BINTARGET=bin/$(CONFIGURATION)/dnx451/test.dll
SOURCE_DIR=../..
MAKEFILE_DIR=$(SOURCE_DIR)/scripts/make
MSBUILD=msbuild
all: test
include $(MAKEFILE_DIR)/dnx.mk
../Yavsc/bin/$(CONFIGURATION)/dnx451/Yavsc.dll:
make -C ../Yavsc
../Yavsc.Abstract/bin/$(CONFIGURATION)/dnx451/Yavsc.Abstract.dll:
make -C ../Yavsc.Abstract
../Yavsc.Server/bin/$(CONFIGURATION)/dnx451/Yavsc.Server.dll:
make -C ../Yavsc.Server
$(BINTARGET): project.lock.json ../Yavsc/bin/$(CONFIGURATION)/dnx451/Yavsc.dll ../Yavsc.Abstract/bin/$(CONFIGURATION)/dnx451/Yavsc.Abstract.dll ../Yavsc.Server/bin/$(CONFIGURATION)/dnx451/Yavsc.Server.dll
dnu build --configuration $(CONFIGURATION)
non-regression: $(BINTARGET)
ASPNET_ENV=Development dnx test -maxthreads 1 -trait regression=non
regression: $(BINTARGET)
ASPNET_ENV=Development dnx test -maxthreads 1 -trait regression=oui
test: non-regression
testdev: $(BINTARGET)
ASPNET_ENV=Development dnx test -maxthreads 1 -trait dev=wip
clean:
rm -rf bin obj testingrepo
.PHONY: test

View File

@ -0,0 +1,203 @@
using System;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Builder.Internal;
using Microsoft.AspNet.Razor;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.PlatformAbstractions;
using Xunit;
using Yavsc;
using Yavsc.Models;
using Yavsc.Services;
using System.Runtime.Versioning;
using Microsoft.AspNet.Mvc.Razor;
using System.Diagnostics;
using Microsoft.Dnx.Compilation.CSharp;
using Microsoft.Extensions.OptionsModel;
using Yavsc.Helpers;
using Microsoft.Data.Entity;
using Xunit.Abstractions;
using System.IO;
using System.Linq;
using Yavsc.Server.Models.IT.SourceCode;
namespace test
{
[Collection("Yavsc mandatory success story")]
[Trait("regression", "oui")]
public class BatchTests: BaseTestContext, IClassFixture<ServerSideFixture>, IDisposable
{
ServerSideFixture _fixture;
public BatchTests(ITestOutputHelper output, ServerSideFixture fixture) : base (output, fixture)
{
_fixture = fixture;
}
[Fact]
public void GitClone()
{
Assert.True(_serverFixture.EnsureTestDb());
Assert.NotNull (_fixture.DbContext.Project);
var firstProject = _fixture.DbContext.Project.Include(p=>p.Repository).FirstOrDefault();
Assert.NotNull (firstProject);
var di = new DirectoryInfo(_serverFixture.SiteSetup.GitRepository);
if (!di.Exists) di.Create();
var clone = new GitClone(_serverFixture.SiteSetup.GitRepository);
clone.Launch(firstProject);
gitRepo = di.FullName;
}
string gitRepo=null;
[Fact]
void AnsiToHtml()
{
var procStart = new ProcessStartInfo("ls", "-l --color=always")
{
UseShellExecute = false,
RedirectStandardInput = false,
RedirectStandardOutput = true
};
var proc = Process.Start(procStart);
var encoded = AnsiToHtmlEncoder.GetStream(proc.StandardOutput);
using (var reader = new StreamReader(encoded))
{
var txt = reader.ReadToEnd();
_output.WriteLine(txt);
}
}
[Fact]
public void MvcRazorHostAndParser()
{
string cache = System.IO.Directory.GetCurrentDirectory();
MvcRazorHost host = new MvcRazorHost(cache);
var parser = host.CreateMarkupParser();
}
[Fact]
void HaveHost()
{
}
[Fact]
public void EnsureConfigurationRoot()
{
var builder = new ConfigurationBuilder();
builder.AddJsonFile( "appsettings.json", false);
builder.AddJsonFile( "appsettings.Development.json", true);
configurationRoot = builder.Build();
}
internal static BeforeCompileContext CreateYavscCompilationContext()
{
var projectContext = new ProjectContext
{
Name = "Yavsc",
ProjectDirectory = "../Yavsc",
ProjectFilePath = "../Yavsc/project.json",
TargetFramework = new FrameworkName("DNX", new Version(4, 5, 1)),
Configuration = Environment.GetEnvironmentVariable("ASPNET_ENV")
};
return new BeforeCompileContext(
null, projectContext, () => null, () => null, () => null);
}
internal static IConfigurationRoot CreateConfiguration(string prjDir)
{
var builder = new ConfigurationBuilder();
builder.AddJsonFile(Path.Combine(prjDir, "appsettings.json"), false);
builder.AddJsonFile(Path.Combine(prjDir, "appsettings.Development.json"), true);
return builder.Build();
}
internal static void ConfigureServices
(ServiceCollection serviceCollection,
string prjDir,
out IConfigurationRoot configuration,
out IServiceProvider provider)
{
configuration = CreateConfiguration(prjDir);
serviceCollection.AddOptions();
var siteSettingsconf = configuration.GetSection("Site");
serviceCollection.Configure<SiteSettings>(siteSettingsconf);
var smtpSettingsconf = configuration.GetSection("Smtp");
serviceCollection.Configure<SmtpSettings>(smtpSettingsconf);
var locOptions = configuration.GetSection("Localization");
serviceCollection.Configure<LocalizationOptions>(locOptions);
serviceCollection.AddSingleton(typeof(ILoggerFactory), typeof(LoggerFactory));
serviceCollection.AddTransient(typeof(IEmailSender), typeof(MailSender));
serviceCollection.AddTransient(typeof(RazorEngineHost));
serviceCollection.AddTransient((s) => new RazorTemplateEngine(s.GetService<RazorEngineHost>()));
serviceCollection.AddLogging();
serviceCollection.AddMvcCore();
serviceCollection.AddLocalization(options =>
{
options.ResourcesPath = "Resources";
});
AppDomain.CurrentDomain.SetData("YAVSC_DB_CONNECTION", Startup.Testing.ConnectionStrings.Default);
serviceCollection.AddEntityFramework()
.AddNpgsql()
.AddDbContext<ApplicationDbContext>(
db => db.UseNpgsql(Startup.Testing.ConnectionStrings.Default)
);
provider = serviceCollection.BuildServiceProvider();
}
[Fact]
public void ARequestAppDelegate()
{
var services = new ServiceCollection();
services.AddTransient<IRuntimeEnvironment>(
svs => PlatformServices.Default.Runtime
);
beforeCompileContext = CreateYavscCompilationContext();
var prjDir = this.beforeCompileContext.ProjectContext.ProjectDirectory;
ConfigureServices(services, prjDir, out configurationRoot, out serviceProvider);
IApplicationBuilder app = new ApplicationBuilder(serviceProvider);
var rtd = app.Build();
}
[Fact]
public void InitApplicationBuilder()
{
var services = new ServiceCollection();
services.AddTransient<IRuntimeEnvironment>(
svs => PlatformServices.Default.Runtime
);
beforeCompileContext = CreateYavscCompilationContext();
var prjDir = beforeCompileContext.ProjectContext.ProjectDirectory;
ConfigureServices(services, prjDir, out configuration, out provider);
IApplicationBuilder app = new ApplicationBuilder(provider);
app.UseMvc();
var rtd = app.Build();
IOptions<LocalizationOptions> localOptions = ActivatorUtilities.GetServiceOrCreateInstance<IOptions<LocalizationOptions>>(provider); ;
}
public void Dispose()
{
if (gitRepo!=null)
{
Directory.Delete(Path.Combine(gitRepo,"yavsc"), true);
}
_fixture.DropTestDb();
}
}
}

View File

@ -0,0 +1,46 @@
// // YavscWorkInProgress.cs
// /*
// paul 21/06/2018 10:11 20182018 6 21
// */
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.PlatformAbstractions;
using Xunit;
using Xunit.Abstractions;
using Yavsc.Authentication;
using static OAuth.AspNet.AuthServer.Constants;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Filters;
using Microsoft.AspNet.Mvc.Razor;
namespace test
{
[Collection("Yavsc Work In Progress")]
[Trait("regression", "oui")]
[Trait("module", "api")]
public class RegiserAPI : BaseTestContext, IClassFixture<ServerSideFixture>
{
public RegiserAPI(ServerSideFixture serverFixture, ITestOutputHelper output)
: base(output, serverFixture)
{
}
[Fact]
public void EnsureWeb()
{
var host = new WebHostBuilder();
host.UseEnvironment("Development")
.UseServer("Microsoft.AspNet.Server.Kestrel")
.UseStartup<test.Startup>()
.Build().Start();
}
}
}

View File

@ -0,0 +1,114 @@
// // YavscWorkInProgress.cs
// /*
// paul 21/06/2018 10:11 20182018 6 21
// */
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.PlatformAbstractions;
using Xunit;
using Xunit.Abstractions;
using Yavsc.Authentication;
using static OAuth.AspNet.AuthServer.Constants;
namespace test
{
[Collection("Yavsc Work In Progress")]
[Trait("regression", "oui")]
public class Remoting : BaseTestContext, IClassFixture<ServerSideFixture>
{
readonly RegiserAPI r;
public Remoting(ServerSideFixture serverFixture, ITestOutputHelper output)
: base(output, serverFixture)
{
r = new RegiserAPI(serverFixture, output);
}
[Theory]
[MemberData(nameof(GetLoginIntentData), parameters: 1)]
public async Task TestUserMayLogin
(
string clientId,
string clientSecret,
string scope,
string authorizeUrl,
string redirectUrl,
string accessTokenUrl,
string login,
string pass
)
{
try
{
r.EnsureWeb();
var oauthor = new OAuthenticator(clientId, clientSecret, scope,
new Uri(authorizeUrl), new Uri(redirectUrl), new Uri(accessTokenUrl));
var query = new Dictionary<string, string>
{
[Parameters.Username] = Startup.Testing.ValidCreds[0].UserName,
[Parameters.Password] = Startup.Testing.ValidCreds[0].Password,
[Parameters.GrantType] = GrantTypes.Password
};
var result = await oauthor.RequestAccessTokenAsync(query);
Console.WriteLine(">> Got an output");
Console.WriteLine(Parameters.AccessToken + ": " + result[Parameters.AccessToken]);
Console.WriteLine(Parameters.TokenType + ": " + result[Parameters.TokenType]);
Console.WriteLine(Parameters.ExpiresIn + ": " + result[Parameters.ExpiresIn]);
Console.WriteLine(Parameters.RefreshToken + ": " + result[Parameters.RefreshToken]);
}
catch (Exception ex)
{
var webex = ex as WebException;
if (webex != null && webex.Status == (WebExceptionStatus)400)
{
if (login == "joe")
{
Console.WriteLine("Bad pass joe!");
return;
}
}
throw;
}
}
public static IEnumerable<object[]> GetLoginIntentData(int numTests)
{
var allData = new List<object[]>();
for (int iTest=0; iTest < numTests && iTest < Startup.Testing.ValidCreds.Length; iTest++)
{
var login = Startup.Testing.ValidCreds[iTest].UserName;
var pass = Startup.Testing.ValidCreds[iTest].Password;
allData.Add(new object[] { ServerSideFixture.ApiKey, "blouh", "profile",
"http://localhost:5000/authorize", "http://localhost:5000/oauth/success",
"http://localhost:5000/token",login, pass});
}
var valid = allData.Count;
for (int iTest=0; iTest + valid < numTests && iTest < Startup.Testing.InvalidCreds.Length; iTest++)
{
var login = Startup.Testing.InvalidCreds[iTest].UserName;
var pass = Startup.Testing.InvalidCreds[iTest].Password;
allData.Add(new object[] { ServerSideFixture.ApiKey, "blouh", "profile",
"http://localhost:5000/authorize", "http://localhost:5000/oauth/success",
"http://localhost:5000/token",login, 0 });
}
return allData.Take(numTests);
}
}
}

View File

@ -0,0 +1,22 @@
namespace test {
public class ResxResources {
const string resPath = "Resources/Test.TestResources.resx";
public void HaveAResxLoader()
{
System.Resources.ResourceReader loader = new System.Resources.ResourceReader(resPath);
// IDictionary
var etor = loader.GetEnumerator();
while (etor.Current !=null)
{
byte[] data;
string stringdata;
string resName = etor.Key.ToString();
loader.GetResourceData(resName, out stringdata, out data);
}
}
}
}

View File

@ -0,0 +1,221 @@
using System;
using System.Data.Common;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Hosting.Internal;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.OptionsModel;
using Yavsc.Lib;
using Yavsc.Services;
using Yavsc;
using Yavsc.Models;
using Xunit;
using Npgsql;
using test.Settings;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata.Conventions;
namespace test
{
[Trait("regression", "II")]
public class ServerSideFixture : IDisposable
{
SiteSettings _siteSetup;
ILogger _logger;
IApplication _app;
readonly EMailer _mailer;
readonly ILoggerFactory _loggerFactory;
IEmailSender _mailSender;
public static string ApiKey => "53f4d5da-93a9-4584-82f9-b8fdf243b002";
public ApplicationDbContext DbContext { get; private set; }
public SiteSettings SiteSetup
{
get
{
return _siteSetup;
}
set
{
_siteSetup = value;
}
}
/// <summary>
/// initialized by Init
/// </summary>
/// <value></value>
public static object TestingSetup { get; private set; }
public IEmailSender MailSender
{
get
{
return _mailSender;
}
set
{
_mailSender = value;
}
}
public IApplication App
{
get
{
return _app;
}
set
{
_app = value;
}
}
internal void UpgradeDb()
{
Microsoft.Data.Entity.Commands.Program.Main(
new string[] { "database", "update" });
}
public ILogger Logger
{
get
{
return _logger;
}
set
{
_logger = value;
}
}
bool dbCreated;
private readonly WebHostBuilder host;
private readonly IHostingEngine hostengnine;
void AssertNotNull(object obj, string msg)
{
if (obj == null)
throw new Exception(msg);
}
//
public ServerSideFixture()
{
host = new WebHostBuilder();
AssertNotNull(host, nameof(host));
hostengnine = host
.UseEnvironment("Development")
.UseServer("test")
.UseStartup<test.Startup>()
.Build();
AssertNotNull(hostengnine, nameof(hostengnine));
App = hostengnine.Start();
AssertNotNull(App, nameof(App));
// hostengnine.ApplicationServices
_mailer = App.Services.GetService(typeof(EMailer)) as EMailer;
AssertNotNull(_mailer, nameof(_mailer));
MailSender = App.Services.GetService(typeof(IEmailSender)) as IEmailSender;
AssertNotNull(MailSender, nameof(MailSender));
_loggerFactory = App.Services.GetService(typeof(ILoggerFactory)) as ILoggerFactory;
AssertNotNull(_loggerFactory, nameof(_loggerFactory));
var siteSetup = App.Services.GetService(typeof(IOptions<SiteSettings>)) as IOptions<SiteSettings>;
AssertNotNull(siteSetup, nameof(siteSetup));
var testingSetup = App.Services.GetService(typeof(IOptions<Testing>)) as IOptions<Testing>;
DbContext = App.Services.GetService(typeof(ApplicationDbContext)) as ApplicationDbContext;
SiteSetup = siteSetup.Value;
TestingSetup = testingSetup.Value;
Logger = _loggerFactory.CreateLogger<ServerSideFixture>();
var builder = new DbConnectionStringBuilder
{
ConnectionString = Startup.Testing.ConnectionStrings.Default
};
ConventionSet conventions = new ConventionSet();
modelBuilder = new ModelBuilder(conventions);
ApplicationDbContext context = new ApplicationDbContext();
TestingDatabase = (string)builder["Database"];
Logger.LogInformation("ServerSideFixture created.");
}
private readonly ModelBuilder modelBuilder;
public string TestingDatabase { get; private set; }
public void CheckDbExistence()
{
using (
NpgsqlConnection cx = new NpgsqlConnection(Startup.Testing.ConnectionStrings.DatabaseCtor))
{
cx.Open();
_logger.LogInformation($"check db for TestingDatabase:{TestingDatabase}");
var command = cx.CreateCommand();
command.CommandText = $"SELECT 1 FROM pg_database WHERE datname='{TestingDatabase}';";
dbCreated = (command.ExecuteScalar()!=null);
_logger.LogInformation($"DbCreated:{dbCreated}");
cx.Close();
}
}
public bool EnsureTestDb()
{
if (!DbCreated)
{
using (NpgsqlConnection cx = new NpgsqlConnection(Startup.Testing.ConnectionStrings.DatabaseCtor))
{
_logger.LogInformation($"create database for TestingDatabase : {TestingDatabase}");
cx.Open();
var command = cx.CreateCommand();
using (NpgsqlConnection ownercx = new NpgsqlConnection(Startup.Testing.ConnectionStrings.Default))
command.CommandText = $"create database \"{TestingDatabase}\" OWNER \"{ownercx.UserName}\";";
_logger.LogInformation(command.CommandText);
command.ExecuteNonQuery();
}
dbCreated = true;
}
return dbCreated;
}
public void DropTestDb()
{
if (dbCreated)
DbContext.Database.EnsureDeleted();
dbCreated = false;
}
public void Dispose()
{
Logger.LogInformation("Disposing");
}
public bool DbCreated { get {
CheckDbExistence();
return dbCreated; } }
}
}

View File

@ -0,0 +1,29 @@
using System;
using Xunit;
using Xunit.Abstractions;
using Yavsc.Helpers;
namespace test
{
[Collection("Yavsc Abstract tests")]
[Trait("regression", "II")]
public class AbstractTests
{
readonly ITestOutputHelper output;
public AbstractTests(ITestOutputHelper output)
{
this.output = output;
}
[Fact]
public void UniquePathesAfterFileNameCleaning()
{
var name1 = "content:///scanned_files/2020-06-02/00.11.02.JPG";
var name2 = "content:///scanned_files/2020-06-02/00.11.03.JPG";
var cleanName1 = AbstractFileSystemHelpers.FilterFileName(name1);
var cleanName2 = AbstractFileSystemHelpers.FilterFileName(name2);
output.WriteLine($"{name1} => {cleanName1}");
output.WriteLine($"{name2} => {cleanName2}");
Assert.True(cleanName1 != cleanName2);
}
}
}

View File

@ -0,0 +1,48 @@
using System;
using Xunit;
using Xunit.Abstractions;
namespace test.Mandatory
{
[Collection("Database")]
[Trait("regression", "II")]
[Trait("dev", "wip")]
public class Database: IClassFixture<ServerSideFixture>, IDisposable
{
readonly ServerSideFixture _serverFixture;
readonly ITestOutputHelper output;
public Database(ServerSideFixture serverFixture, ITestOutputHelper output)
{
this.output = output;
_serverFixture = serverFixture;
try {
if (_serverFixture.DbCreated)
_serverFixture.DropTestDb();
}
catch (Exception)
{
output.WriteLine("db not dropped");
}
output.WriteLine($"Startup.Testing.ConnectionStrings.DatabaseCtor is {Startup.Testing.ConnectionStrings.DatabaseCtor}");
}
/// <summary>
/// Assuming we're using an account that may create databases,
/// Install all our migrations in a fresh new database.
/// </summary>
[Fact]
public void InstallFromScratchUsingPoweredNpgsqlUser()
{
_serverFixture.EnsureTestDb();
_serverFixture.UpgradeDb();
}
public void Dispose()
{
_serverFixture.DropTestDb();
}
}
}

View File

@ -0,0 +1,44 @@
using Microsoft.Extensions.Logging;
using Xunit;
using Xunit.Abstractions;
using Yavsc.Abstract.Manage;
namespace test
{
[Collection("EMaillingTeststCollection")]
[Trait("regression", "II")]
public class EMaillingTests : IClassFixture<ServerSideFixture>
{
readonly ServerSideFixture _serverFixture;
readonly ITestOutputHelper output;
readonly ILogger _logger;
public EMaillingTests(ServerSideFixture serverFixture, ITestOutputHelper output)
{
this.output = output;
_serverFixture = serverFixture;
_logger = serverFixture.Logger;
}
[Fact]
public void SendEMailSynchrone()
{
AssertAsync.CompletesIn(2, () =>
{
output.WriteLine("SendEMailSynchrone ...");
EmailSentViewModel mailSentInfo = _serverFixture.MailSender.SendEmailAsync
(_serverFixture.SiteSetup.Owner.Name, _serverFixture.SiteSetup.Owner.EMail, $"monthly email", "test boby monthly email").Result;
if (mailSentInfo==null)
_logger.LogError("No info on sending");
else if (!mailSentInfo.Sent)
_logger.LogError($"{mailSentInfo.ErrorMessage}");
else
_logger.LogInformation($"mailId:{mailSentInfo.MessageId} \nto:{_serverFixture.SiteSetup.Owner.Name}");
Assert.NotNull(mailSentInfo);
output.WriteLine($">>done with {mailSentInfo.EMail} {mailSentInfo.Sent} {mailSentInfo.MessageId} {mailSentInfo.ErrorMessage}");
});
}
}
}

View File

@ -0,0 +1,66 @@
using System;
using Xunit;
using System.IO;
using System.Diagnostics;
namespace test
{
/// <summary>
/// Since node isn't any requirement by here,
/// It may regress
/// </summary>
[Trait("regression", "allways")]
public class NodeTests
{
void TestNodeJsForAnsitohtml ()
{
var procStart = new ProcessStartInfo("node", "node_modules/ansi-to-html/bin/ansi-to-html")
{
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true
};
var proc = Process.Start(procStart);
proc.StandardInput.WriteLine("\x001b[30mblack\x1b[37mwhite");
proc.StandardInput.Close();
while (!proc.StandardOutput.EndOfStream)
{
Console.Write(proc.StandardOutput.ReadToEnd());
}
}
void AnsiToHtml()
{
var procStart = new ProcessStartInfo("ls", "-l --color=always")
{
UseShellExecute = false,
RedirectStandardInput = false,
RedirectStandardOutput = true
};
var proc = Process.Start(procStart);
var encoded = GetStream(proc.StandardOutput);
var reader = new StreamReader(encoded);
var txt = reader.ReadToEnd();
Console.WriteLine(txt);
}
public static Stream GetStream(StreamReader reader)
{
var procStart = new ProcessStartInfo("node", "node_modules/ansi-to-html/bin/ansi-to-html");
procStart.UseShellExecute = false;
procStart.RedirectStandardInput = true;
procStart.RedirectStandardOutput = true;
procStart.RedirectStandardError = true;
var mem = new MemoryStream();
StreamWriter writer = new StreamWriter(mem);
var proc = Process.Start(procStart);
var text = reader.ReadToEnd();
proc.StandardInput.WriteLine(text);
proc.StandardInput.Close();
return proc.StandardOutput.BaseStream;
}
}
}

View File

@ -0,0 +1,66 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<!--
route name for the api controller used to tag the 'BlogPost' entity
-->
<data name="ErrMessageTooLong"><value>Too Long ({MaxLen} at maximum, {ecart} in excess))</value></data>
<data name="ErrMessageTooShort"><value>Too Short ({MinLen} at minus, {ecart} missing)</value></data>
</root>

View File

@ -0,0 +1,8 @@
namespace test.Settings
{
public class DbConnectionSettings
{
public string DatabaseCtor { get; set; }
public string Default { get; set; }
}
}

View File

@ -0,0 +1,22 @@
namespace test.Settings
{
public class PasswordCreds
{
public string UserName { get; set; }
public string Password { get; set; }
}
public class Testing
{
public DbConnectionSettings ConnectionStrings { get; set; }
public PasswordCreds[] ValidCreds
{
get; set;
}
public PasswordCreds[] InvalidCreds
{
get; set;
}
}
}

653
test/yavscTests/Startup.cs Normal file
View File

@ -0,0 +1,653 @@
using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.OptionsModel;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Razor;
using Microsoft.Extensions.PlatformAbstractions;
using Yavsc;
using Yavsc.Models;
using Yavsc.Services;
using Microsoft.Data.Entity;
using Microsoft.Extensions.WebEncoders;
using test.Settings;
using Microsoft.AspNet.Diagnostics;
using System.Net;
using Yavsc.Extensions;
using Microsoft.AspNet.Authentication.Cookies;
using Microsoft.AspNet.Authentication.JwtBearer;
using OAuth.AspNet.Tokens;
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Authentication.OAuth;
using Yavsc.Helpers.Auth;
using Google.Apis.Util.Store;
using System.Security.Claims;
using Google.Apis.Auth.OAuth2.Responses;
using Constants = Yavsc.Constants;
using OAuth.AspNet.AuthServer;
using Yavsc.Models.Auth;
using Microsoft.AspNet.Identity;
using System.Collections.Concurrent;
using System.Security.Principal;
using System.Linq;
using System.Collections.Generic;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Filters;
using Microsoft.AspNet.Mvc.Razor;
using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Authorization;
using Yavsc.AuthorizationHandlers;
using Yavsc.Formatters;
using Microsoft.Net.Http.Headers;
using static Yavsc.Startup;
using Microsoft.AspNet.DataProtection.Infrastructure;
using System.IO;
using Microsoft.AspNet.Identity.EntityFramework;
using Yavsc.Auth;
using Yavsc.Lib;
namespace test
{
public class Startup
{
public static IConfiguration Configuration { get; set; }
public static string HostingFullName { get; private set; }
public ApplicationDbContext DbContext { get; private set; }
public static Testing Testing { get; private set; }
public static IConfigurationRoot GoogleWebClientConfiguration { get; set; }
public static CookieAuthenticationOptions ExternalCookieAppOptions { get; private set; }
public MonoDataProtectionProvider ProtectionProvider { get; private set; }
public static OAuth.AspNet.AuthServer.OAuthAuthorizationServerOptions OAuthServerAppOptions { get; private set; }
public Yavsc.Auth.YavscGoogleOptions YavscGoogleAppOptions { get; private set; }
private static ILogger logger;
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
var devtag = env.IsDevelopment() ? "D" : "";
var prodtag = env.IsProduction() ? "P" : "";
var stagetag = env.IsStaging() ? "S" : "";
HostingFullName = $"{appEnv.RuntimeFramework.FullName} [{env.EnvironmentName}:{prodtag}{devtag}{stagetag}]";
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
if (env.IsDevelopment())
{
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
}
Configuration = builder.Build();
var googleClientFile = Configuration["Authentication:Google:GoogleWebClientJson"];
var googleServiceAccountJsonFile = Configuration["Authentication:Google:GoogleServiceAccountJson"];
if (googleClientFile != null)
GoogleWebClientConfiguration = new ConfigurationBuilder().AddJsonFile(googleClientFile).Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
var siteSettingsconf = Configuration.GetSection("Site");
services.Configure<SiteSettings>(siteSettingsconf);
var smtpSettingsconf = Configuration.GetSection("Smtp");
services.Configure<SmtpSettings>(smtpSettingsconf);
var dbSettingsconf = Configuration.GetSection("ConnectionStrings");
services.Configure<DbConnectionSettings>(dbSettingsconf);
var testingconf = Configuration.GetSection("Testing");
services.Configure<Testing>(testingconf);
services.AddInstance(typeof(ILoggerFactory), new LoggerFactory());
services.AddTransient(typeof(IEmailSender), typeof(MailSender));
services.AddEntityFramework().AddNpgsql().AddDbContext<ApplicationDbContext>();
services.AddTransient((s) => new RazorTemplateEngine(s.GetService<RazorEngineHost>()));
services.AddLogging();
services.AddTransient<ServerSideFixture>();
services.AddTransient<MailSender>();
services.AddTransient<EMailer>();
services.AddLocalization(options =>
{
options.ResourcesPath = "Resources";
});
// Add memory cache services
services.AddCaching();
// Add session related services.
services.AddSession();
// Add the system clock service
services.AddSingleton<ISystemClock, SystemClock>();
services.AddAuthorization(options =>
{
options.AddPolicy("AdministratorOnly", policy =>
{
policy.RequireClaim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", Constants.AdminGroupName);
});
options.AddPolicy("FrontOffice", policy => policy.RequireRole(Constants.FrontOfficeGroupName));
options.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes("yavsc")
.RequireAuthenticatedUser().Build());
// options.AddPolicy("EmployeeId", policy => policy.RequireClaim("EmployeeId", "123", "456"));
// options.AddPolicy("BuildingEntry", policy => policy.Requirements.Add(new OfficeEntryRequirement()));
options.AddPolicy("Authenticated", policy => policy.RequireAuthenticatedUser());
});
services.AddDataProtection();
services.ConfigureDataProtection(configure =>
{
configure.SetApplicationName(Configuration["Site:Title"]);
configure.SetDefaultKeyLifetime(TimeSpan.FromDays(45));
configure.PersistKeysToFileSystem(
new DirectoryInfo(Configuration["DataProtection:Keys:Dir"]));
});
services.Add(ServiceDescriptor.Singleton(typeof(IApplicationDiscriminator),
typeof(SystemWebApplicationDiscriminator)));
services.AddSingleton<IAuthorizationHandler, HasBadgeHandler>();
services.AddSingleton<IAuthorizationHandler, HasTemporaryPassHandler>();
services.AddSingleton<IAuthorizationHandler, BlogEditHandler>();
services.AddSingleton<IAuthorizationHandler, BlogViewHandler>();
services.AddSingleton<IAuthorizationHandler, BillEditHandler>();
services.AddSingleton<IAuthorizationHandler, BillViewHandler>();
services.AddSingleton<IAuthorizationHandler, PostUserFileHandler>();
services.AddSingleton<IAuthorizationHandler, ViewFileHandler>();
services.AddSingleton<IAuthorizationHandler, SendMessageHandler>();
services.AddSingleton<IConnexionManager, HubConnectionManager>();
services.AddSingleton<ILiveProcessor, LiveProcessor>();
services.AddSingleton<IFileSystemAuthManager, FileSystemAuthManager>();
services.AddSingleton<UserManager<ApplicationDbContext>>();
services.AddIdentity<ApplicationUser, IdentityRole>(
option =>
{
IdentityAppOptions = option;
option.User.AllowedUserNameCharacters += " ";
option.User.RequireUniqueEmail = true;
option.Cookies.ApplicationCookie.LoginPath = "/signin";
// option.Cookies.TwoFactorRememberMeCookie.ExpireTimeSpan = TimeSpan.FromDays(30);
// option.Cookies.TwoFactorRememberMeCookie.DataProtectionProvider = ProtectionProvider;
// option.Cookies.ApplicationCookie.DataProtectionProvider = ProtectionProvider;
// option.Cookies.ExternalCookie.DataProtectionProvider = ProtectionProvider;
// option.Cookies.ApplicationCookie.AuthenticationScheme = Constants.ApplicationAuthenticationSheme;
/*
option.Cookies.ApplicationCookie.LoginPath = new PathString(Constants.LoginPath.Substring(1));
option.Cookies.ApplicationCookie.AccessDeniedPath = new PathString(Constants.AccessDeniedPath.Substring(1));
option.Cookies.ApplicationCookie.AutomaticAuthenticate = true;
option.Cookies.ApplicationCookie.AuthenticationScheme = Constants.ApplicationAuthenticationSheme;
option.Cookies.ApplicationCookieAuthenticationScheme = Constants.ApplicationAuthenticationSheme;
option.Cookies.ExternalCookieAuthenticationScheme = Constants.ExternalAuthenticationSheme;
option.Cookies.ExternalCookie.AutomaticAuthenticate = true;
option.Cookies.ExternalCookie.AuthenticationScheme = Constants.ExternalAuthenticationSheme;
*/
}
).AddEntityFrameworkStores<ApplicationDbContext>()
.AddTokenProvider<EmailTokenProvider<ApplicationUser>>(Constants.DefaultFactor)
// .AddTokenProvider<UserTokenProvider>(Constants.DefaultFactor)
// .AddTokenProvider<UserTokenProvider>(Constants.SMSFactor)
.AddTokenProvider<UserTokenProvider>(Constants.EMailFactor)
// .AddTokenProvider<UserTokenProvider>(Constants.AppFactor)
//
;
services.AddMvc(config =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
config.Filters.Add(new ProducesAttribute("application/json"));
// config.ModelBinders.Insert(0,new MyDateTimeModelBinder());
// config.ModelBinders.Insert(0,new MyDecimalModelBinder());
config.OutputFormatters.Add(new PdfFormatter());
}).AddFormatterMappings(
config => config.SetMediaTypeMappingForFormat("text/pdf",
new MediaTypeHeaderValue("text/pdf"))
).AddFormatterMappings(
config => config.SetMediaTypeMappingForFormat("text/x-tex",
new MediaTypeHeaderValue("text/x-tex"))
)
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix,
options =>
{
options.ResourcesPath = "Resources";
}).AddDataAnnotationsLocalization();
// services.AddScoped<LanguageActionFilter>();
// Inject ticket formatting
services.AddTransient(typeof(ISecureDataFormat<>), typeof(SecureDataFormat<>));
services.AddTransient<Microsoft.AspNet.Authentication.ISecureDataFormat<AuthenticationTicket>, Microsoft.AspNet.Authentication.SecureDataFormat<AuthenticationTicket>>();
services.AddTransient<ISecureDataFormat<AuthenticationTicket>, TicketDataFormat>();
// Add application services.
services.AddTransient<IEmailSender, MailSender>();
services.AddTransient<IYavscMessageSender, YavscMessageSender>();
services.AddTransient<IBillingService, BillingService>();
services.AddTransient<IDataStore, FileDataStore>((sp) => new FileDataStore("googledatastore", false));
services.AddTransient<ICalendarManager, CalendarManager>();
services.AddTransient<Microsoft.Extensions.WebEncoders.UrlEncoder, UrlEncoder>();
}
#region OAuth Methods
private Client GetApplication(string clientId)
{
if (DbContext == null)
{
logger.LogError("no db!");
return null;
}
Client app = DbContext.Applications.FirstOrDefault(x => x.Id == clientId);
if (app == null) logger.LogError($"no app for <{clientId}>");
return app;
}
private Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
{
if (context == null) throw new InvalidOperationException("context == null");
var app = GetApplication(context.ClientId);
if (app == null) return Task.FromResult(0);
Startup.logger.LogInformation($"ValidateClientRedirectUri: Validated ({app.RedirectUri})");
context.Validated(app.RedirectUri);
return Task.FromResult(0);
}
private Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
string clientId, clientSecret;
if (context.TryGetBasicCredentials(out clientId, out clientSecret) ||
context.TryGetFormCredentials(out clientId, out clientSecret))
{
logger.LogInformation($"ValidateClientAuthentication: Got id: ({clientId} secret: {clientSecret})");
var client = GetApplication(clientId);
if (client == null)
{
context.SetError("invalid_clientId", "Client secret is invalid.");
return Task.FromResult<object>(null);
}
else
if (client.Type == ApplicationTypes.NativeConfidential)
{
logger.LogInformation($"NativeConfidential key");
if (string.IsNullOrWhiteSpace(clientSecret))
{
logger.LogInformation($"invalid_clientId: Client secret should be sent.");
context.SetError("invalid_clientId", "Client secret should be sent.");
return Task.FromResult<object>(null);
}
else
{
// if (client.Secret != Helper.GetHash(clientSecret))
// TODO store a hash in db, not the pass
if (client.Secret != clientSecret)
{
context.SetError("invalid_clientId", "Client secret is invalid.");
logger.LogInformation($"invalid_clientId: Client secret is invalid.");
return Task.FromResult<object>(null);
}
}
}
if (!client.Active)
{
context.SetError("invalid_clientId", "Client is inactive.");
logger.LogInformation($"invalid_clientId: Client is inactive.");
return Task.FromResult<object>(null);
}
if (client != null && client.Secret == clientSecret)
{
logger.LogInformation($"\\o/ ValidateClientAuthentication: Validated ({clientId})");
context.Validated();
}
else logger.LogInformation($":'( ValidateClientAuthentication: KO ({clientId})");
}
else logger.LogWarning($"ValidateClientAuthentication: neither Basic nor Form credential were found");
return Task.FromResult(0);
}
private async Task<Task> GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
logger.LogWarning($"GrantResourceOwnerCredentials task ... {context.UserName}");
ApplicationUser user = null;
user = DbContext.Users.Include(u => u.Membership).First(u => u.UserName == context.UserName);
if (await _usermanager.CheckPasswordAsync(user, context.Password))
{
var claims = new List<Claim>(
context.Scope.Select(x => new Claim("urn:oauth:scope", x))
)
{
new Claim(ClaimTypes.NameIdentifier, user.Id),
new Claim(ClaimTypes.Email, user.Email)
};
claims.AddRange((await _usermanager.GetRolesAsync(user)).Select(
r => new Claim(ClaimTypes.Role, r)
));
claims.AddRange(user.Membership.Select(
m => new Claim(YavscClaimTypes.CircleMembership, m.CircleId.ToString())
));
ClaimsPrincipal principal = new ClaimsPrincipal(
new ClaimsIdentity(
new GenericIdentity(context.UserName, OAuthDefaults.AuthenticationType),
claims)
);
context.HttpContext.User = principal;
context.Validated(principal);
}
#if USERMANAGER
#endif
return Task.FromResult(0);
}
private Task GrantClientCredetails(OAuthGrantClientCredentialsContext context)
{
var id = new GenericIdentity(context.ClientId, OAuthDefaults.AuthenticationType);
var claims = context.Scope.Select(x => new Claim("urn:oauth:scope", x));
var cid = new ClaimsIdentity(id, claims);
ClaimsPrincipal principal = new ClaimsPrincipal(cid);
context.Validated(principal);
return Task.FromResult(0);
}
private readonly ConcurrentDictionary<string, string> _authenticationCodes = new ConcurrentDictionary<string, string>(StringComparer.Ordinal);
private void CreateAuthenticationCode(AuthenticationTokenCreateContext context)
{
logger.LogInformation("CreateAuthenticationCode");
context.SetToken(Guid.NewGuid().ToString("n") + Guid.NewGuid().ToString("n"));
_authenticationCodes[context.Token] = context.SerializeTicket();
}
private void ReceiveAuthenticationCode(AuthenticationTokenReceiveContext context)
{
string value;
if (_authenticationCodes.TryRemove(context.Token, out value))
{
context.DeserializeTicket(value);
logger.LogInformation("ReceiveAuthenticationCode: Success");
}
}
private void CreateRefreshToken(AuthenticationTokenCreateContext context)
{
var uid = context.Ticket.Principal.GetUserId();
logger.LogInformation($"CreateRefreshToken for {uid}");
foreach (var c in context.Ticket.Principal.Claims)
logger.LogInformation($"| User claim: {c.Type} {c.Value}");
context.SetToken(context.SerializeTicket());
}
private void ReceiveRefreshToken(AuthenticationTokenReceiveContext context)
{
var uid = context.Ticket.Principal.GetUserId();
logger.LogInformation($"ReceiveRefreshToken for {uid}");
foreach (var c in context.Ticket.Principal.Claims)
logger.LogInformation($"| User claim: {c.Type} {c.Value}");
context.DeserializeTicket(context.Token);
}
#endregion
UserManager<ApplicationUser> _usermanager;
public void Configure(
IApplicationBuilder app,
IHostingEnvironment env,
ApplicationDbContext dbContext,
IOptions<Testing> testingSettings,
UserManager<ApplicationUser> usermanager,
ILoggerFactory loggerFactory
)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
logger = loggerFactory.CreateLogger<Startup>();
logger.LogInformation(env.EnvironmentName);
this.DbContext = dbContext;
Testing = testingSettings.Value;
_usermanager = usermanager;
#if USERMANAGER
#endif
if (Testing.ConnectionStrings == null)
logger.LogInformation($" Testing.ConnectionStrings is null : ");
else
{
AppDomain.CurrentDomain.SetData("YAVSC_DB_CONNECTION", Testing.ConnectionStrings.Default);
}
var authConf = Configuration.GetSection("Authentication").GetSection("Yavsc");
var clientId = authConf.GetSection("ClientId").Value;
var clientSecret = authConf.GetSection("ClientSecret").Value;
app.UseDeveloperExceptionPage();
app.UseRuntimeInfoPage();
var epo = new ErrorPageOptions
{
SourceCodeLineCount = 20
};
app.UseDeveloperExceptionPage(epo);
app.UseDatabaseErrorPage(
x =>
{
x.EnableAll();
x.ShowExceptionDetails = true;
}
);
app.UseWelcomePage("/welcome");
// before fixing the security protocol, let beleive our lib it's done with it.
var cxmgr = PayPal.Manager.ConnectionManager.Instance;
// then, fix it.
ServicePointManager.SecurityProtocol = (SecurityProtocolType)0xC00; // Tls12, required by PayPal
app.UseIISPlatformHandler(options =>
{
options.AuthenticationDescriptions.Clear();
options.AutomaticAuthentication = false;
});
app.UseSession();
app.UseIdentity();
ProtectionProvider = new MonoDataProtectionProvider(Configuration["Site:Title"]); ;
app.UseWhen(context => context.Request.Path.StartsWithSegments("/api")
|| context.Request.Path.StartsWithSegments("/live"),
branchLiveOrApi =>
{
branchLiveOrApi.UseJwtBearerAuthentication(
options =>
{
options.AuthenticationScheme = JwtBearerDefaults.AuthenticationScheme;
options.AutomaticAuthenticate = true;
options.SecurityTokenValidators.Clear();
var tickeDataProtector = new TicketDataFormatTokenValidator(
ProtectionProvider
);
options.SecurityTokenValidators.Add(tickeDataProtector);
options.Events = new JwtBearerEvents
{
OnReceivingToken = context =>
{
return Task.Run(() =>
{
var signalRTokenHeader = context.Request.Query["signalRTokenHeader"];
if (!string.IsNullOrEmpty(signalRTokenHeader) &&
(context.HttpContext.WebSockets.IsWebSocketRequest || context.Request.Headers["Accept"] == "text/event-stream"))
{
context.Token = context.Request.Query["signalRTokenHeader"];
}
});
}
};
});
});
app.UseWhen(context => !context.Request.Path.StartsWithSegments("/api") && !context.Request.Path.StartsWithSegments("/live"),
branch =>
{
// External authentication shared cookie:
branch.UseCookieAuthentication(options =>
{
ExternalCookieAppOptions = options;
options.AuthenticationScheme = Yavsc.Constants.ExternalAuthenticationSheme;
options.AutomaticAuthenticate = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
options.LoginPath = new PathString(Yavsc.Constants.LoginPath.Substring(1));
options.AccessDeniedPath = new PathString(Yavsc.Constants.LoginPath.Substring(1));
});
YavscGoogleAppOptions = new Yavsc.Auth.YavscGoogleOptions
{
ClientId = GoogleWebClientConfiguration["web:client_id"],
ClientSecret = GoogleWebClientConfiguration["web:client_secret"],
AccessType = "offline",
Scope = {
"profile",
"https://www.googleapis.com/auth/admin.directory.resource.calendar",
"https://www.googleapis.com/auth/calendar",
"https://www.googleapis.com/auth/calendar.events"
},
SaveTokensAsClaims = true,
UserInformationEndpoint = "https://www.googleapis.com/plus/v1/people/me",
Events = new OAuthEvents
{
OnCreatingTicket = async context =>
{
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
.CreateScope())
{
var gcontext = context as Yavsc.Auth.GoogleOAuthCreatingTicketContext;
context.Identity.AddClaim(new Claim(YavscClaimTypes.GoogleUserId, gcontext.GoogleUserId));
var DbContext = serviceScope.ServiceProvider.GetService<ApplicationDbContext>();
var store = serviceScope.ServiceProvider.GetService<IDataStore>();
await store.StoreAsync(gcontext.GoogleUserId, new TokenResponse
{
AccessToken = gcontext.TokenResponse.AccessToken,
RefreshToken = gcontext.TokenResponse.RefreshToken,
TokenType = gcontext.TokenResponse.TokenType,
ExpiresInSeconds = int.Parse(gcontext.TokenResponse.ExpiresIn),
IssuedUtc = DateTime.Now
});
await dbContext.StoreTokenAsync(gcontext.GoogleUserId,
gcontext.TokenResponse.Response,
gcontext.TokenResponse.AccessToken,
gcontext.TokenResponse.TokenType,
gcontext.TokenResponse.RefreshToken,
gcontext.TokenResponse.ExpiresIn);
}
}
}
};
branch.UseMiddleware<Yavsc.Auth.GoogleMiddleware>(YavscGoogleAppOptions);
/* FIXME 403
branch.UseTwitterAuthentication(options=>
{
TwitterAppOptions = options;
options.ConsumerKey = Configuration["Authentication:Twitter:ClientId"];
options.ConsumerSecret = Configuration["Authentication:Twitter:ClientSecret"];
}); */
branch.UseOAuthAuthorizationServer(
options =>
{
OAuthServerAppOptions = options;
options.AuthorizeEndpointPath = new PathString(Constants.AuthorizePath.Substring(1));
options.TokenEndpointPath = new PathString(Constants.TokenPath.Substring(1));
options.ApplicationCanDisplayErrors = true;
options.AllowInsecureHttp = true;
options.AuthenticationScheme = OAuthDefaults.AuthenticationType;
options.TokenDataProtector = ProtectionProvider.CreateProtector("Bearer protection");
options.Provider = new OAuthAuthorizationServerProvider
{
OnValidateClientRedirectUri = ValidateClientRedirectUri,
OnValidateClientAuthentication = ValidateClientAuthentication,
OnGrantResourceOwnerCredentials = GrantResourceOwnerCredentials,
OnGrantClientCredentials = GrantClientCredetails
};
options.AuthorizationCodeProvider = new AuthenticationTokenProvider
{
OnCreate = CreateAuthenticationCode,
OnReceive = ReceiveAuthenticationCode,
};
options.RefreshTokenProvider = new AuthenticationTokenProvider
{
OnCreate = CreateRefreshToken,
OnReceive = ReceiveRefreshToken,
};
options.AutomaticAuthenticate = true;
options.AutomaticChallenge = true;
}
);
});
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", "google-secret.json");
/* TODO
ConfigureFileServerApp(app, SiteSetup, env, authorizationService);
app.UseRequestLocalization(localizationOptions.Value, (RequestCulture)new RequestCulture((string)"en-US"));
ConfigureWorkflow();
*/
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}

View File

@ -0,0 +1,33 @@
using System;
using System.Threading.Tasks;
namespace test {
public static class AssertAsync {
public static void CompletesIn(int timeout, Action action)
{
var task = Task.Run(action);
var completedInTime = Task.WaitAll(new[] { task }, TimeSpan.FromSeconds(timeout));
if (task.Exception != null)
{
if (task.Exception.InnerExceptions.Count == 1)
{
throw task.Exception.InnerExceptions[0];
}
throw task.Exception;
}
if (!completedInTime)
{
throw new TimeoutException($"Task did not complete in {timeout} seconds.");
}
}
}
}

View File

@ -0,0 +1,48 @@
// // NotWorking.cs
// /*
// paul 21/06/2018 10:16 20182018 6 21
// */
using System;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.OptionsModel;
using Xunit;
using Yavsc;
using Microsoft.AspNet.Hosting;
using Microsoft.Dnx.TestHost.TestAdapter;
using Xunit.Abstractions;
namespace test
{
[Collection("Yavsc dropped intents")]
[Trait("regres", "yes")]
public class NotWorking : BaseTestContext
{
readonly SourceInformationProvider _sourceInfoProvider;
readonly IOptions<LocalizationOptions> _localizationOptions;
public NotWorking(
SourceInformationProvider sourceInfoProvider,
IOptions<LocalizationOptions> localizationOptions,
ServerSideFixture serverFixture, ITestOutputHelper output
) : base(output, serverFixture)
{
_sourceInfoProvider = sourceInfoProvider;
_localizationOptions = localizationOptions;
}
public void StringLocalizer()
{
// TODO build applicationEnvironment
ResourceManagerStringLocalizerFactory strFact = new ResourceManagerStringLocalizerFactory
(applicationEnvironment, _localizationOptions);
IStringLocalizer stringLocalizer = strFact.Create(typeof(NotWorking));
}
public void NoDnxEnv()
{
IOptions<LocalizationOptions> localOptions = Activator.CreateInstance<IOptions<LocalizationOptions>>();
ResourceManagerStringLocalizerFactory strFact = new ResourceManagerStringLocalizerFactory(applicationEnvironment, localOptions);
IStringLocalizer stringLocalizer = strFact.Create(typeof(NotWorking));
}
}
}

View File

@ -0,0 +1,23 @@
using System;
using System.Threading.Tasks;
using Microsoft.AspNet.Hosting.Server;
using Microsoft.AspNet.Http.Features;
using Microsoft.Extensions.Configuration;
namespace Yavsc.Server
{
public class CliServerFactory : IServerFactory
{
public IFeatureCollection Initialize(IConfiguration configuration)
{
FeatureCollection featureCollection = new FeatureCollection();
return featureCollection;
}
public IDisposable Start(IFeatureCollection serverFeatures, Func<IFeatureCollection, Task> application)
{
var task = application(serverFeatures);
return task;
}
}
}

View File

@ -0,0 +1,66 @@
{
"Site": {
"Authority": "dev.pschneider.fr",
"Title": "Yavsc dev",
"Slogan": "Yavsc : WIP.",
"Banner": "/images/yavsc.png",
"HomeViewName": "Home",
"FavIcon": "/favicon.ico",
"Icon": "/images/yavsc.png",
"GitRepository": "testingrepo",
"Owner": {
"Name": "Site Owner Name",
"EMail": "your@email",
"PostalAddress": {
"Street1": "Your Address",
"Street2": "your street",
"PostalCode": "543 21~3",
"City": "",
"State": "",
"Province": null
}
},
"Admin": {
"Name": "Administrator name",
"EMail": "daAdmin@e.mail"
}
},
"Smtp": {
"Host": "localhost",
"Port": 25,
"EnableSSL": false
},
"Logging": {
"IncludeScopes": true,
"LogLevel": {
"Default": "Debug",
"System": "Warning",
"Microsoft": "Warning"
}
},
"Testing": {
"ConnectionStrings": {
"Default": "Server=lame-NpgsqlHostName;Port=5432;Database=lame-DataBase;Username=lame-Username;Password=lame-dbPassword;",
"DatabaseCtor": "Server=lame-NpgsqlHostName;Port=5432;Database=lame-ctor-DataBase;Username=lame-ctor-Username;Password=lame-ctordbPassword;"
},
"ValidCreds": [
{
"UserName": "lame-user",
"Password": "lame-password"
}
],
"InvalidCreds": [
{
"UserName": "lame-fakeuser",
"Password": "lame-fakepassword"
}
]
},
"DataProtection": {
"Keys": {
"Dir": "DataProtection-Keys"
},
"RSAParamFile": "ls ",
"ExpiresInHours": 168
}
}

View File

@ -0,0 +1,20 @@
0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Programs\\nodejs\\node.exe',
1 verbose cli 'C:\\Programs\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli 'install' ]
2 info using npm@1.4.9
3 info using node@v8.11.3
4 error install Couldn't read dependencies
5 error package.json ENOENT: no such file or directory, open 'C:\Users\paul\Documents\GitHub\yavsc\test\package.json'
5 error package.json This is most likely not a problem with npm itself.
5 error package.json npm can't find a package.json file in your current directory.
6 error System Windows_NT 6.1.7601
7 error command "C:\\Programs\\nodejs\\node.exe" "C:\\Programs\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install"
8 error cwd C:\Users\paul\Documents\GitHub\yavsc\test
9 error node -v v8.11.3
10 error npm -v 1.4.9
11 error path C:\Users\paul\Documents\GitHub\yavsc\test\package.json
12 error syscall open
13 error code ENOPACKAGEJSON
14 error errno -4058
15 verbose exit [ -4058, true ]

19
test/yavscTests/package-lock.json generated Normal file
View File

@ -0,0 +1,19 @@
{
"requires": true,
"lockfileVersion": 1,
"dependencies": {
"ansi-to-html": {
"version": "0.6.9",
"resolved": "https://registry.npmjs.org/ansi-to-html/-/ansi-to-html-0.6.9.tgz",
"integrity": "sha512-hwNdg2DNgCzsrvaNc+LDqSxJkpxf9oEt4R7KE0IeURXhEOlontEqNpXNiGeFBpSes8TZF+ZZ9sjB85QzjPsI6A==",
"requires": {
"entities": "^1.1.1"
}
},
"entities": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/entities/-/entities-1.1.2.tgz",
"integrity": "sha512-f2LZMYl1Fzu7YSBKg+RoROelpOaNrcGmE9AZubeDfrCEia483oW4MI4VyFd5VNHIgQ/7qm1I0wUHK1eJnn2y2w=="
}
}
}

View File

@ -0,0 +1,95 @@
{
"version": "1.0.5-*",
"title": "Yavsc - les tests",
"description": "Yavsc xUnit testing",
"authors": [
"Paul Schneider <paul@pschneider.fr>"
],
"resource": "Resources/**/*.resx",
"buildOptions": {
"debugType": "full",
"emitEntryPoint": true,
"compile": {
"include": "*.cs",
"exclude": [
"contrib"
]
},
"embed": [
"Resources/**/*.resx"
],
"define": ["USERMANAGER"]
},
"frameworks": {
"dnx451": {}
},
"commands": {
"web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.Kestrel --server.urls https://*:5001",
"test": "xunit.runner.dnx"
},
"packOptions": {
"repository": {
"type": "git",
"url": "https://github.com/pazof/yavsc"
},
"licenseUrl": "https://github.com/pazof/yavsc/blob/vnext/LICENSE",
"requireLicenseAcceptance": true,
"owners": [
"Paul Schneider <paul@pschneider.fr>"
],
"summary": "Yet another very small company",
"projectUrl": "http://yavsc.pschneider.fr",
"tags": [
"Blog",
"PoS",
"Chat"
]
},
"exclude": [
"bin",
"wwwroot",
"node_modules",
"bower_components",
"contrib",
"testingrepo"
],
"tooling": {
"defaultNamespace": "test"
},
"dependencies": {
"EntityFramework.Commands": "7.0.0-rc1-final",
"EntityFramework7.Npgsql": "3.1.0-rc1-3",
"EntityFramework7.Npgsql.Design": "3.1.0-rc1-5",
"Newtonsoft.Json": "7.0.1",
"Microsoft.AspNet.Mvc": "6.0.0-rc1-*",
"Microsoft.AspNet.StaticFiles": "1.0.0-rc1-*",
"Microsoft.AspNet.Tooling.Razor": "1.0.0-rc1-*",
"Microsoft.AspNet.Identity.EntityFramework": "3.0.0-rc1-*",
"xunit": "2.1.0",
"xunit.analyzers": "0.9.0",
"xunit.assert": "2.1.0",
"xunit.runner.console": "2.4.0-rc.2.build4045",
"Microsoft.Dnx.TestHost": "1.0.0-rc1-final",
"Microsoft.Dnx.Runtime": "1.0.0-rc1-final",
"xunit.runner.dnx": "2.1.0-rc1-build204",
"Yavsc.Server": {
"target": "project",
"type": "build"
},
"Yavsc.Abstract": {
"target": "project",
"type": "build"
},
"Yavsc": {
"target": "project",
"type": "build"
}
},
"userSecretsId": "aspnet5-YavscWeb-a0dadd21-2ced-43d3-96f9-7e504345102f",
"scripts": {
"postrestore": [
"grep -v '\\.\\.dll' project.lock.json > new.project.lock.json",
"mv new.project.lock.json project.lock.json"
]
}
}