fixes, refacts

vnext
Paul Schneider 6 years ago
parent 1f6aaac1fe
commit 0c69d5abbc
19 changed files with 193 additions and 85 deletions

@ -35,7 +35,7 @@ namespace Yavsc.ViewModels.UserFiles
$"File name contains invalid chars, using path {finalPath}"); $"File name contains invalid chars, using path {finalPath}");
dInfo = new DirectoryInfo( dInfo = new DirectoryInfo(
userReposPath+FileSystemConstants.RemoteDirectorySeparator+finalPath); userReposPath+Path.DirectorySeparatorChar+finalPath);
if (dInfo.Exists) { if (dInfo.Exists) {
Files = dInfo.GetFiles().Select Files = dInfo.GetFiles().Select
@ -43,7 +43,11 @@ namespace Yavsc.ViewModels.UserFiles
CreationTime = entry.CreationTime, LastModified = entry.LastWriteTime }).ToArray(); CreationTime = entry.CreationTime, LastModified = entry.LastWriteTime }).ToArray();
SubDirectories = dInfo.GetDirectories().Select SubDirectories = dInfo.GetDirectories().Select
( d=> new DirectoryShortInfo { Name= d.Name, IsEmpty=false } ).ToArray(); ( d=> new DirectoryShortInfo { Name= d.Name, IsEmpty=false } ).ToArray();
}
else {
// don't return null, but empty arrays
Files = new RemoteFileInfo[0];
SubDirectories = new DirectoryShortInfo[0];
} }
} }
} }

@ -27,7 +27,6 @@ namespace Yavsc.ViewModels.Account
[Compare("Password")] [Compare("Password")]
public string ConfirmPassword { get; set; } public string ConfirmPassword { get; set; }
public string GoogleRegId { get; set; }
} }
} }

@ -225,7 +225,7 @@ namespace Yavsc.Controllers
{ {
if (ModelState.IsValid) if (ModelState.IsValid)
{ {
var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var user = new ApplicationUser { UserName = model.UserName, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password); var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded) if (result.Succeeded)
{ {
@ -240,7 +240,8 @@ namespace Yavsc.Controllers
var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
var emailSent = await _emailSender.SendEmailAsync(model.UserName, model.Email, _localizer["ConfirmYourAccountTitle"], var emailSent = await _emailSender.SendEmailAsync(model.UserName, model.Email, _localizer["ConfirmYourAccountTitle"],
string.Format(_localizer["ConfirmYourAccountBody"], _siteSettings.Title, callbackUrl, _siteSettings.Slogan, _siteSettings.Audience)); string.Format(_localizer["ConfirmYourAccountBody"], _siteSettings.Title, callbackUrl, _siteSettings.Slogan, _siteSettings.Audience));
await _signInManager.SignInAsync(user, isPersistent: false); // No, wait for more than a login pass submission:
// do not await _signInManager.SignInAsync(user, isPersistent: false);
if (emailSent==null) if (emailSent==null)
{ {
_logger.LogWarning("User created with error sending email confirmation request"); _logger.LogWarning("User created with error sending email confirmation request");
@ -249,7 +250,7 @@ namespace Yavsc.Controllers
_localizer["ErrorSendingEmailForConfirm"] _localizer["ErrorSendingEmailForConfirm"]
); );
} }
else else
this.NotifyInfo( this.NotifyInfo(
"E-mail confirmation", "E-mail confirmation",
_localizer["EmailSentForConfirm"] _localizer["EmailSentForConfirm"]

@ -8,7 +8,7 @@
Merci d’avoir confirmé votre e-mail. Merci d’avoir confirmé votre e-mail.
@if (User.GetUserId()==null) { @if (User.GetUserId()==null) {
<text>S&rsquo;il vous plait, <text>S&rsquo;il vous plait,
<a asp-controller="Account" asp-action="Login">Cliquez ici pour vous connecter</a>. <a asp-controller="Account" asp-action="SignIn">Cliquez ici pour vous connecter</a>.
</text> </text>
} }
</p> </p>

@ -24,6 +24,7 @@
}, },
"userSecretsId": "aspnet5-YavscWeb-a0dadd21-2ced-43d3-96f9-7e504345102f", "userSecretsId": "aspnet5-YavscWeb-a0dadd21-2ced-43d3-96f9-7e504345102f",
"exclude": [ "exclude": [
"bin",
"wwwroot", "wwwroot",
"node_modules", "node_modules",
"bower_components", "bower_components",

@ -0,0 +1,31 @@
using cli.Model;
using Microsoft.Extensions.CommandLineUtils;
namespace cli.Commands
{
public class AuthCommander : ICommander
{
public CommandLineApplication Integrate(CommandLineApplication rootApp)
{
CommandLineApplication authApp = rootApp.Command("auth",
(target) =>
{
target.FullName = "Authentication methods";
target.Description = "Login, save credentials and get authorized.";
target.HelpOption("-? | -h | --help");
var loginCommand = target.Command("login", app => {
var loginarg = app.Argument("login", "login to use", true);
app.Option( "-s | --save", "Save authentication token to file", CommandOptionType.NoValue);
app.HelpOption("-? | -h | --help");
} );
}, false);
authApp.OnExecute(()=>
{
return 0;
});
return authApp;
}
}
}

@ -1,12 +1,28 @@
using cli.Model;
using Microsoft.Extensions.CommandLineUtils; using Microsoft.Extensions.CommandLineUtils;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using cli.Services;
namespace cli { namespace cli
{
public class CiBuildCommand {
public class CiBuildCommand : ICommander
{
public CommandLineApplication Integrate(CommandLineApplication rootApp)
{
CommandLineApplication ciBuildApp = rootApp.Command("build",
(target) =>
{
target.FullName = "Build this project.";
target.Description = "Build this project, as specified in .paul-ci.json";
target.HelpOption("-? | -h | --help");
}, false);
ciBuildApp.OnExecute(()=>
{
return 0;
});
return ciBuildApp;
}
} }
} }

@ -1,19 +1,15 @@
using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.CommandLineUtils; using Microsoft.Extensions.CommandLineUtils;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using cli.Services;
using System.Threading.Tasks; using System.Threading.Tasks;
using NJsonSchema; using NJsonSchema;
using System.IO; using System.IO;
using cli.Model;
namespace cli namespace cli
{ {
public class GenerateJsonSchema public class GenerateJsonSchema : ICommander
{ {
public CommandLineApplication Integrates(CommandLineApplication rootApp) public CommandLineApplication Integrate(CommandLineApplication rootApp)
{ {
CommandArgument genargclass = null; CommandArgument genargclass = null;
CommandArgument genargjson = null; CommandArgument genargjson = null;

@ -4,11 +4,12 @@ using Microsoft.Extensions.CommandLineUtils;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using cli.Services; using cli.Services;
using cli.Model;
namespace cli { namespace cli {
public class SendMailCommandProvider : ICliCommand { public class SendMailCommandProvider : ICommander {
public CommandLineApplication Integrates(CommandLineApplication rootApp) public CommandLineApplication Integrate(CommandLineApplication rootApp)
{ {
CommandArgument sendMailCommandArg = null; CommandArgument sendMailCommandArg = null;
CommandOption sendHelpOption = null; CommandOption sendHelpOption = null;

@ -0,0 +1,76 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using cli.Model;
using Microsoft.Extensions.CommandLineUtils;
using Yavsc.Authentication;
using static OAuth.AspNet.AuthServer.Constants;
namespace cli.Helpers
{
public static class ConsoleHelpers
{
public static CommandLineApplication Integrate(this CommandLineApplication rootApp, ICommander commander)
{
return commander.Integrate(rootApp);
}
static OAuthenticator OAuthorInstance { get; set; }
public static OAuthenticator InitAuthor(
this ConnectionSettings settings,
string clientId,
string clientSecret,
string scope,
string authorizeUrl,
string redirectUrl,
string accessTokenUrl)
{
return OAuthorInstance = new OAuthenticator(settings.ClientId,
settings.ClientSecret,
settings.Scope,
new Uri(settings.AuthorizeUrl), new Uri(settings.RedirectUrl), new Uri(settings.AccessTokenUrl));
}
public static async Task<IDictionary<string, string>> GetAuthFromPass(
string login,
string pass)
{
var query = new Dictionary<string, string>();
query[Parameters.Username] = login;
query[Parameters.Password] = pass;
query[Parameters.GrantType] = GrantTypes.Password;
return await OAuthorInstance.RequestAccessTokenAsync(query);
}
public static string GetPassword()
{
var pwd = new StringBuilder();
while (true)
{
var len = pwd.ToString().Length;
ConsoleKeyInfo i = Console.ReadKey(true);
if (i.Key == ConsoleKey.Enter)
{
break;
}
else if (i.Key == ConsoleKey.Backspace)
{
if (pwd.Length > 0)
{
pwd.Remove(len - 1, 1);
Console.Write("\b \b");
}
}
else
{
pwd.Append(i.KeyChar);
Console.Write("*");
}
}
return pwd.ToString();
}
}
}

@ -11,8 +11,9 @@ msbuild-restore:
check: run check: run
project.lock.json: project.json project.lock.json: project.json
$(dnu) restore @$(dnu) restore
sed 's/System.XML/System.Xml/' project.lock.json > project.lock.json.new && mv project.lock.json.new project.lock.json @# fixing package id reference case, to System.Xml, from package NJsonSchema.CodeGeneration.CSharp
@sed 's/System.XML/System.Xml/' project.lock.json > project.lock.json.new && mv project.lock.json.new project.lock.json
run: project.lock.json run: project.lock.json
ASPNET_ENV=$(ASPNET_ENV) dnx --configuration=$(CONFIGURATION) run send monthly ASPNET_ENV=$(ASPNET_ENV) dnx --configuration=$(CONFIGURATION) run send monthly
@ -20,6 +21,5 @@ run: project.lock.json
info: info:
@echo $(PRJNAME) @echo $(PRJNAME)
# Due to NJsonSchema.CodeGeneration.CSharp package:
.PHONY: project.lock.json

@ -1,6 +0,0 @@
using Microsoft.Extensions.CommandLineUtils;
public interface ICliCommand
{
CommandLineApplication Integrates(CommandLineApplication rootApp);
}

@ -0,0 +1,9 @@
using Microsoft.Extensions.CommandLineUtils;
namespace cli.Model
{
public interface ICommander
{
CommandLineApplication Integrate(CommandLineApplication rootApp);
}
}

@ -1,9 +1,7 @@
 
using System; using System;
using System.IO; using cli.Commands;
using System.Threading.Tasks;
using Microsoft.Extensions.CommandLineUtils; using Microsoft.Extensions.CommandLineUtils;
using NJsonSchema;
namespace cli namespace cli
{ {
@ -21,10 +19,11 @@ namespace cli
cliapp.ShortVersionGetter = () => "v1.0"; cliapp.ShortVersionGetter = () => "v1.0";
cliapp.LongVersionGetter = () => "version 1.0 (stable)"; cliapp.LongVersionGetter = () => "version 1.0 (stable)";
rootCommandHelpOption = cliapp.HelpOption("-? | -h | --help"); rootCommandHelpOption = cliapp.HelpOption("-? | -h | --help");
var command = new SendMailCommandProvider();
command.Integrates(cliapp); (new SendMailCommandProvider()).Integrate(cliapp);
var gencmd = new GenerateJsonSchema(); (new GenerateJsonSchema()).Integrate(cliapp);
gencmd.Integrates(cliapp); (new AuthCommander()).Integrate(cliapp);
(new CiBuildCommand()).Integrate(cliapp);
if (args.Length == 0) if (args.Length == 0)
{ {

@ -1,56 +1,34 @@
namespace cli namespace cli
{ {
using Yavsc.Abstract.Identity;
using Yavsc;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
using Newtonsoft.Json; using Newtonsoft.Json;
using Yavsc.Authentication;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
public class ConnectionSettings public class ConnectionSettings
{ {
public TokenInfo UserToken { get; set; } public string ClientId { get; set; }
public SiteSettings Site { get; set; } public string ClientSecret { get; set; }
public OAuth2AppSettings ServerApiKey { get; set; } public string Authority { get; set; }
public string Audience { get; set; }
public string SiteAccessSheme { get; set; } = "http"; public string SiteAccessSheme { get; set; } = "http";
public string Scope { get; set; } = "profile"; public string Scope { get; set; } = "profile";
[NotMapped] [NotMapped]
[JsonIgnore] [JsonIgnore]
public string AuthorizeUrl {get { public string AuthorizeUrl {get {
return $"{SiteAccessSheme}://{Site.Authority}/authorize"; return $"{SiteAccessSheme}://{Authority}/authorize";
} } } }
[NotMapped] [NotMapped]
[JsonIgnore] [JsonIgnore]
public string RedirectUrl {get { public string RedirectUrl {get {
return $"{SiteAccessSheme}://{Site.Authority}/oauth/success"; return $"{SiteAccessSheme}://{Authority}/oauth/success";
} } } }
[NotMapped] [NotMapped]
[JsonIgnore] [JsonIgnore]
public string AccessTokenUrl {get { public string AccessTokenUrl {get {
return $"{SiteAccessSheme}://{Site.Authority}/token"; return $"{SiteAccessSheme}://{Authority}/token";
} } } }
public async Task InitUserTokenFromLoginPass(string login, string pass)
{
var oauthor =new OAuthenticator( ServerApiKey.ClientId, ServerApiKey.ClientSecret, Scope,
new Uri( AuthorizeUrl) , new Uri(RedirectUrl) , new Uri(AccessTokenUrl));
var query = new Dictionary<string,string>();
query["username"]=login;
query["password"]=pass;
query["grant_type"]="password";
var result = await oauthor.RequestAccessTokenAsync(query);
UserToken = new TokenInfo {
AccessToken = result["access_token"],
RefreshToken = result["refresh_token"],
Received = DateTime.Now,
ExpiresIn = int.Parse(result["expires_in"]),
TokenType = result["token_type"]
};
}
} }
} }

@ -1,19 +1,18 @@
using System; using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Razor;
using Microsoft.Data.Entity;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.OptionsModel; using Microsoft.Extensions.OptionsModel;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Razor;
using Microsoft.Extensions.PlatformAbstractions; using Microsoft.Extensions.PlatformAbstractions;
using cli.Services; using Microsoft.Extensions.WebEncoders;
using Yavsc; using Yavsc;
using Yavsc.Models; using Yavsc.Models;
using Yavsc.Services; using Yavsc.Services;
using Microsoft.Data.Entity; using cli.Services;
using Microsoft.AspNet.Authentication;
using Microsoft.Extensions.WebEncoders;
namespace cli namespace cli
{ {
@ -24,8 +23,7 @@ namespace cli
get ; set; get ; set;
} }
public static SiteSettings SiteSetup { get; private set; } public static ConnectionSettings Settings { get; private set; }
public static SmtpSettings SmtpSettup { get; private set; }
public static IConfiguration Configuration { get; set; } public static IConfiguration Configuration { get; set; }
public static string HostingFullName { get; private set; } public static string HostingFullName { get; private set; }
@ -44,24 +42,24 @@ namespace cli
.AddEnvironmentVariables() .AddEnvironmentVariables()
.AddJsonFile("appsettings.json") .AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true); .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
Configuration = builder.Build(); Configuration = builder.Build();
ConnectionString = Configuration["Data:DefaultConnection:ConnectionString"]; ConnectionString = Configuration["Data:DefaultConnection:ConnectionString"];
AppDomain.CurrentDomain.SetData("YAVSC_CONNECTION", ConnectionString);
} }
public void ConfigureServices (IServiceCollection services) public void ConfigureServices (IServiceCollection services)
{ {
services.AddOptions(); services.AddOptions();
var siteSettingsconf = Configuration.GetSection("Site"); var cxSettings = Configuration.GetSection("Connection");
services.Configure<SiteSettings>(siteSettingsconf); services.Configure<ConnectionSettings>(cxSettings);
var smtpSettingsconf = Configuration.GetSection("Smtp"); var smtpSettingsconf = Configuration.GetSection("Smtp");
services.Configure<SmtpSettings>(smtpSettingsconf); services.Configure<SmtpSettings>(smtpSettingsconf);
services.AddInstance(typeof(ILoggerFactory), new LoggerFactory()); services.AddInstance(typeof(ILoggerFactory), new LoggerFactory());
services.AddTransient(typeof(IEmailSender), typeof(MailSender)); services.AddTransient(typeof(IEmailSender), typeof(MailSender));
services.AddTransient(typeof(RazorEngineHost), typeof(YaRazorEngineHost)); services.AddTransient(typeof(RazorEngineHost), typeof(YaRazorEngineHost));
services.AddEntityFramework().AddNpgsql().AddDbContext<ApplicationDbContext>(); services.AddEntityFramework().AddNpgsql().AddDbContext<ApplicationDbContext>();
services.AddTransient((s) => new RazorTemplateEngine(s.GetService<RazorEngineHost>())); services.AddTransient((s) => new RazorTemplateEngine(s.GetService<RazorEngineHost>()));
// services.AddTransient<,>()
services.AddLogging(); services.AddLogging();
services.AddTransient<EMailer>(); services.AddTransient<EMailer>();
services.AddLocalization(options => services.AddLocalization(options =>

@ -58,7 +58,8 @@
"version": "1.0.5-rc22", "version": "1.0.5-rc22",
"target": "package" "target": "package"
}, },
"Yavsc.Lib.Portable": "1.0.2" "Yavsc.Lib.Portable": "1.0.2",
"OAuth.AspNet.AuthServer": { "target": "project" }
}, },
"frameworks": { "frameworks": {
"dnx451": { "dnx451": {

@ -25,6 +25,7 @@
] ]
}, },
"exclude": [ "exclude": [
"bin",
"wwwroot", "wwwroot",
"node_modules", "node_modules",
"bower_components", "bower_components",

@ -23,6 +23,9 @@
}, },
{ {
"path": "test" "path": "test"
},
{
"path": ".vscode"
} }
], ],
"settings": { "settings": {

Loading…