drop obsolete code

This commit is contained in:
2017-03-29 01:55:25 +02:00
parent fed51e87e5
commit 0a73c16191
8 changed files with 49 additions and 107 deletions

View File

@ -20,7 +20,7 @@ using Microsoft.Data.Entity;
namespace Yavsc.Controllers namespace Yavsc.Controllers
{ {
[ServiceFilter(typeof(LanguageActionFilter)), AllowAnonymous] [AllowAnonymous]
public class AccountController : Controller public class AccountController : Controller
{ {
private readonly UserManager<ApplicationUser> _userManager; private readonly UserManager<ApplicationUser> _userManager;
@ -231,12 +231,12 @@ namespace Yavsc.Controllers
// Sign in the user with this external login provider if the user already has a login. // Sign in the user with this external login provider if the user already has a login.
info.ProviderDisplayName = info.ExternalPrincipal.Claims.First(c=>c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name")?.Value; info.ProviderDisplayName = info.ExternalPrincipal.Claims.First(c=>c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name")?.Value;
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false); var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
if (result.Succeeded) if (result.Succeeded)
{ {
_logger.LogInformation(5, $"User logged in with {info.LoginProvider} provider, as {info.ProviderDisplayName} ({info.ProviderKey})." ); _logger.LogInformation(5, $"User logged in with {info.LoginProvider} provider, as {info.ProviderDisplayName} ({info.ProviderKey})." );
var ninfo = _dbContext.UserLogins.First(l=>l.ProviderKey == info.ProviderKey && l.LoginProvider == info.LoginProvider); var ninfo = _dbContext.UserLogins.First(l=>l.ProviderKey == info.ProviderKey && l.LoginProvider == info.LoginProvider);
ninfo.ProviderDisplayName = info.ProviderDisplayName; ninfo.ProviderDisplayName = info.ProviderDisplayName;
@ -361,7 +361,7 @@ namespace Yavsc.Controllers
// Don't reveal that the user does not exist or is not confirmed // Don't reveal that the user does not exist or is not confirmed
if (user == null) if (user == null)
_logger.LogWarning($"ForgotPassword: Email {model.Email} not found"); _logger.LogWarning($"ForgotPassword: Email {model.Email} not found");
else else
_logger.LogWarning($"ForgotPassword: Email {model.Email} not confirmed"); _logger.LogWarning($"ForgotPassword: Email {model.Email} not confirmed");
return View("ForgotPasswordConfirmation"); return View("ForgotPasswordConfirmation");
} }

View File

@ -13,7 +13,7 @@ using Yavsc.ViewModels.Administration;
namespace Yavsc.Controllers namespace Yavsc.Controllers
{ {
[ServiceFilter(typeof(LanguageActionFilter)), Authorize()] [Authorize()]
public class AdministrationController : Controller public class AdministrationController : Controller
{ {
private readonly UserManager<ApplicationUser> _userManager; private readonly UserManager<ApplicationUser> _userManager;
@ -55,7 +55,7 @@ namespace Yavsc.Controllers
} }
return Ok(new { message = "you owned it." }); return Ok(new { message = "you owned it." });
} }
[Authorize(Roles = Constants.AdminGroupName)] [Authorize(Roles = Constants.AdminGroupName)]
[Produces("application/json")] [Produces("application/json")]
public async Task<IActionResult> Index() public async Task<IActionResult> Index()
@ -72,7 +72,7 @@ namespace Yavsc.Controllers
Name = x.Name, Name = x.Name,
Users = x.Users.Select(u=>u.UserId).ToArray() Users = x.Users.Select(u=>u.UserId).ToArray()
}); });
return View(new AdminViewModel return View(new AdminViewModel
{ {
Roles = roles.ToArray(), Roles = roles.ToArray(),
@ -80,7 +80,7 @@ namespace Yavsc.Controllers
YouAreAdmin = youAreAdmin YouAreAdmin = youAreAdmin
}); });
} }
public IActionResult Role(string id) public IActionResult Role(string id)
{ {
IdentityRole role = _roleManager.Roles IdentityRole role = _roleManager.Roles

View File

@ -16,7 +16,6 @@ using Microsoft.AspNet.Mvc.Rendering;
namespace Yavsc.Controllers namespace Yavsc.Controllers
{ {
[ServiceFilter(typeof(LanguageActionFilter))]
public class BlogspotController : Controller public class BlogspotController : Controller
{ {
ILogger _logger; ILogger _logger;
@ -114,7 +113,7 @@ namespace Yavsc.Controllers
} }
if (!await _authorizationService.AuthorizeAsync(User, blog, new ViewRequirement())) if (!await _authorizationService.AuthorizeAsync(User, blog, new ViewRequirement()))
{ {
return new ChallengeResult(); return new ChallengeResult();
} }
return View(blog); return View(blog);
} }
@ -165,11 +164,11 @@ namespace Yavsc.Controllers
ViewBag.ACL = _context.Circle.Where( ViewBag.ACL = _context.Circle.Where(
c=>c.OwnerId == blog.AuthorId) c=>c.OwnerId == blog.AuthorId)
.Select( .Select(
c => new SelectListItem c => new SelectListItem
{ {
Text = c.Name, Text = c.Name,
Value = c.Id.ToString(), Value = c.Id.ToString(),
Selected = blog.AuthorizeCircle(c.Id) Selected = blog.AuthorizeCircle(c.Id)
}  } 
); );
return View(blog); return View(blog);
@ -195,7 +194,7 @@ namespace Yavsc.Controllers
_context.SaveChanges(User.GetUserId()); _context.SaveChanges(User.GetUserId());
ViewData["StatusMessage"] = "Post modified"; ViewData["StatusMessage"] = "Post modified";
return RedirectToAction("Index"); return RedirectToAction("Index");
} }
else else
{ {
ViewData["StatusMessage"] = "Accès restreint"; ViewData["StatusMessage"] = "Accès restreint";

View File

@ -18,8 +18,7 @@ namespace Yavsc.Controllers
using Models.Relationship; using Models.Relationship;
using Models.Workflow; using Models.Workflow;
using Services; using Services;
[ServiceFilter(typeof(LanguageActionFilter))]
public class CommandController : Controller public class CommandController : Controller
{ {
protected UserManager<ApplicationUser> _userManager; protected UserManager<ApplicationUser> _userManager;
@ -128,7 +127,7 @@ namespace Yavsc.Controllers
[ValidateAntiForgeryToken] [ValidateAntiForgeryToken]
public async Task<IActionResult> Create(RdvQuery command) public async Task<IActionResult> Create(RdvQuery command)
{ {
var uid = User.GetUserId(); var uid = User.GetUserId();
var prid = command.PerformerId; var prid = command.PerformerId;
if (string.IsNullOrWhiteSpace(uid) if (string.IsNullOrWhiteSpace(uid)
@ -151,10 +150,10 @@ namespace Yavsc.Controllers
// ModelState.ClearValidationState("Client.Avatar"); // ModelState.ClearValidationState("Client.Avatar");
// ModelState.ClearValidationState("ClientId"); // ModelState.ClearValidationState("ClientId");
ModelState.MarkFieldSkipped("ClientId"); ModelState.MarkFieldSkipped("ClientId");
if (ModelState.IsValid) if (ModelState.IsValid)
{ {
var existingLocation = _context.Locations.FirstOrDefault( x=>x.Address == command.Location.Address var existingLocation = _context.Locations.FirstOrDefault( x=>x.Address == command.Location.Address
&& x.Longitude == command.Location.Longitude && x.Latitude == command.Location.Latitude ); && x.Longitude == command.Location.Longitude && x.Latitude == command.Location.Latitude );
if (existingLocation!=null) { if (existingLocation!=null) {

View File

@ -14,8 +14,8 @@ using System.Threading.Tasks;
namespace Yavsc.Controllers namespace Yavsc.Controllers
{ {
using Models; using Models;
[ServiceFilter(typeof(LanguageActionFilter)),AllowAnonymous] [AllowAnonymous]
public class HomeController : Controller public class HomeController : Controller
{ {
public IHostingEnvironment Hosting { get; set; } public IHostingEnvironment Hosting { get; set; }

View File

@ -26,7 +26,7 @@ namespace Yavsc.Controllers
using PayPal.PayPalAPIInterfaceService; using PayPal.PayPalAPIInterfaceService;
using PayPal.PayPalAPIInterfaceService.Model; using PayPal.PayPalAPIInterfaceService.Model;
[Authorize, ServiceFilter(typeof(LanguageActionFilter))] [Authorize]
public class ManageController : Controller public class ManageController : Controller
{ {
private readonly UserManager<ApplicationUser> _userManager; private readonly UserManager<ApplicationUser> _userManager;
@ -372,14 +372,14 @@ namespace Yavsc.Controllers
if (result.Succeeded) if (result.Succeeded)
{ {
/* Obsolete : files are no more prefixed using the user name. /* Obsolete : files are no more prefixed using the user name.
var userdirinfo = new DirectoryInfo( var userdirinfo = new DirectoryInfo(
Path.Combine(_siteSettings.UserFiles.DirName, Path.Combine(_siteSettings.UserFiles.DirName,
oldUserName)); oldUserName));
var newdir = Path.Combine(_siteSettings.UserFiles.DirName, var newdir = Path.Combine(_siteSettings.UserFiles.DirName,
model.NewUserName); model.NewUserName);
if (userdirinfo.Exists) if (userdirinfo.Exists)
userdirinfo.MoveTo(newdir); userdirinfo.MoveTo(newdir);
*/ */
await _signInManager.SignInAsync(user, isPersistent: false); await _signInManager.SignInAsync(user, isPersistent: false);
@ -529,7 +529,7 @@ namespace Yavsc.Controllers
{ {
if (ModelState.IsValid) if (ModelState.IsValid)
{ {
var exSiren = await _dbContext.ExceptionsSIREN.FirstOrDefaultAsync( var exSiren = await _dbContext.ExceptionsSIREN.FirstOrDefaultAsync(
ex => ex.SIREN == model.SIREN ex => ex.SIREN == model.SIREN
); );
@ -609,12 +609,12 @@ namespace Yavsc.Controllers
[HttpGet, Route("/Manage/Credits")] [HttpGet, Route("/Manage/Credits")]
public IActionResult Credits() public IActionResult Credits()
{ {
return View(); return View();
} }
public Dictionary<string, string> PaypalConfig {  public Dictionary<string, string> PaypalConfig { 
get {  get { 
var config = var config =
new Dictionary<string, string>(); new Dictionary<string, string>();
config.Add("mode", "sandbox"); config.Add("mode", "sandbox");
config.Add("account1.apiUsername", _payPalSettings.UserId); config.Add("account1.apiUsername", _payPalSettings.UserId);
@ -622,7 +622,7 @@ namespace Yavsc.Controllers
config.Add("account1.apiSignature", _payPalSettings.Signature); config.Add("account1.apiSignature", _payPalSettings.Signature);
return config; return config;
} }
} }
protected IActionResult DoDirectCredit(DoDirectCreditViewModel model) protected IActionResult DoDirectCredit(DoDirectCreditViewModel model)
@ -679,7 +679,7 @@ namespace Yavsc.Controllers
// Important: The notify URL applies only to DoExpressCheckoutPayment. This value is ignored when set in SetExpressCheckout or GetExpressCheckoutDetails. // Important: The notify URL applies only to DoExpressCheckoutPayment. This value is ignored when set in SetExpressCheckout or GetExpressCheckoutDetails.
requestDetails.PaymentDetails.NotifyURL = model.IpnNotificationUrl.Trim(); requestDetails.PaymentDetails.NotifyURL = model.IpnNotificationUrl.Trim();
// (Optional) Buyer's shipping address information. // (Optional) Buyer's shipping address information.
AddressType billingAddr = new AddressType(); AddressType billingAddr = new AddressType();
if (model.FirstName != string.Empty && model.LastName != string.Empty if (model.FirstName != string.Empty && model.LastName != string.Empty
&& model.Street1 != string.Empty && model.Country != string.Empty) && model.Street1 != string.Empty && model.Country != string.Empty)
@ -708,7 +708,7 @@ namespace Yavsc.Controllers
// Note: You must set the currencyID attribute to one of the 3-character currency codes for any of the supported PayPal currencies. // Note: You must set the currencyID attribute to one of the 3-character currency codes for any of the supported PayPal currencies.
CurrencyCodeType currency = (CurrencyCodeType) CurrencyCodeType currency = (CurrencyCodeType)
Enum.Parse(typeof(CurrencyCodeType), model.CurrencyCode); Enum.Parse(typeof(CurrencyCodeType), model.CurrencyCode);
BasicAmountType paymentAmount = new BasicAmountType(currency, model.Amount); BasicAmountType paymentAmount = new BasicAmountType(currency, model.Amount);
requestDetails.PaymentDetails.OrderTotal = paymentAmount; requestDetails.PaymentDetails.OrderTotal = paymentAmount;
// Invoke the API // Invoke the API
@ -716,17 +716,17 @@ namespace Yavsc.Controllers
wrapper.DoDirectPaymentRequest = request; wrapper.DoDirectPaymentRequest = request;
// Configuration map containing signature credentials and other required configuration. // Configuration map containing signature credentials and other required configuration.
// For a full list of configuration parameters refer in wiki page // For a full list of configuration parameters refer in wiki page
// [https://github.com/paypal/sdk-core-dotnet/wiki/SDK-Configuration-Parameters] // [https://github.com/paypal/sdk-core-dotnet/wiki/SDK-Configuration-Parameters]
//// TODO clean Dictionary<string, string> configurationMap = Configuration.GetAcctAndConfig(); //// TODO clean Dictionary<string, string> configurationMap = Configuration.GetAcctAndConfig();
// Create the PayPalAPIInterfaceServiceService service object to make the API call // Create the PayPalAPIInterfaceServiceService service object to make the API call
PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(PaypalConfig); PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(PaypalConfig);
// # API call // # API call
// Invoke the DoDirectPayment method in service wrapper object // Invoke the DoDirectPayment method in service wrapper object
DoDirectPaymentResponseType response = service.DoDirectPayment(wrapper); DoDirectPaymentResponseType response = service.DoDirectPayment(wrapper);
// Check for API return status // Check for API return status
return setKeyResponseObjects(service, response); return setKeyResponseObjects(service, response);
} }
@ -749,7 +749,7 @@ namespace Yavsc.Controllers
} }
else else
{ {
HttpContext.Items.Add("Response_error", null); HttpContext.Items.Add("Response_error", null);
responseParams.Add("Transaction Id", response.TransactionID); responseParams.Add("Transaction Id", response.TransactionID);
responseParams.Add("Payment status", response.PaymentStatus.ToString()); responseParams.Add("Payment status", response.PaymentStatus.ToString());
if(response.PendingReason != null) { if(response.PendingReason != null) {
@ -759,7 +759,7 @@ namespace Yavsc.Controllers
HttpContext.Items.Add("Response_keyResponseObject", responseParams); HttpContext.Items.Add("Response_keyResponseObject", responseParams);
return View("APIResponse"); return View("APIResponse");
} }
#region Helpers #region Helpers
private void AddErrors(IdentityResult result) private void AddErrors(IdentityResult result)

View File

@ -1,61 +0,0 @@
using System.Globalization;
namespace Yavsc
{
using Microsoft.AspNet.Mvc.Filters;
using Microsoft.Extensions.Logging;
public class LanguageActionFilter : ActionFilterAttribute
{
private readonly ILogger _logger;
public LanguageActionFilter(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger("LanguageActionFilter");
}
public override void OnActionExecuting(ActionExecutingContext context)
{
string culture = null;
var routedCulture = context.RouteData.Values["culture"];
if (routedCulture != null) {
culture = routedCulture.ToString();
_logger.LogInformation($"Setting the culture from the URL: {culture}");
}
else {
if (context.HttpContext.Request.Headers.ContainsKey("accept-language"))
{
// fr,en-US;q=0.7,en;q=0.3
string spec = context.HttpContext.Request.Headers["accept-language"];
_logger.LogInformation($"Setting the culture from language header spec: {spec}");
string firstpart = spec.Split(';')[0];
foreach (string lang in firstpart.Split(','))
{
// TODO do it from the given options ...
// just take the main part :-)
string mainlang = lang.Split('-')[0];
if (mainlang=="fr"||mainlang=="en") {
culture = mainlang;
_logger.LogInformation($"Setting the culture from header: {culture}");
break;
}
}
}
}
if (culture != null) {
#if DNX451
// System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo(culture);
System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture);
#else
// CultureInfo.CurrentCulture = new CultureInfo(culture);
CultureInfo.CurrentUICulture = new CultureInfo(culture);
#endif
}
base.OnActionExecuting(context);
}
}
}

View File

@ -113,11 +113,16 @@ namespace Yavsc
// - QueryStringRequestCultureProvider, sets culture via "culture" and "ui-culture" query string values, useful for testing // - QueryStringRequestCultureProvider, sets culture via "culture" and "ui-culture" query string values, useful for testing
// - CookieRequestCultureProvider, sets culture via "ASPNET_CULTURE" cookie // - CookieRequestCultureProvider, sets culture via "ASPNET_CULTURE" cookie
// - AcceptLanguageHeaderRequestCultureProvider, sets culture via the "Accept-Language" request header // - AcceptLanguageHeaderRequestCultureProvider, sets culture via the "Accept-Language" request header
//options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(async context => //options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(async context =>
//{ //{
// // My custom request culture logic // // My custom request culture logic
// return new ProviderCultureResult("en"); // return new ProviderCultureResult("fr");
//})); //}));
options.RequestCultureProviders.Insert(0, new AcceptLanguageHeaderRequestCultureProvider());
options.RequestCultureProviders.Insert(0, new CookieRequestCultureProvider());
}); });
@ -184,7 +189,7 @@ namespace Yavsc
services.AddSingleton<IAuthorizationHandler, PostUserFileHandler>(); services.AddSingleton<IAuthorizationHandler, PostUserFileHandler>();
services.AddSingleton<IAuthorizationHandler, EstimateViewHandler>(); services.AddSingleton<IAuthorizationHandler, EstimateViewHandler>();
services.AddSingleton<IAuthorizationHandler, ViewFileHandler>(); services.AddSingleton<IAuthorizationHandler, ViewFileHandler>();
services.AddMvc(config => services.AddMvc(config =>
{ {
var policy = new AuthorizationPolicyBuilder() var policy = new AuthorizationPolicyBuilder()
@ -207,7 +212,7 @@ namespace Yavsc
options.ResourcesPath = "Resources"; options.ResourcesPath = "Resources";
}).AddDataAnnotationsLocalization(); }).AddDataAnnotationsLocalization();
services.AddScoped<LanguageActionFilter>(); // services.AddScoped<LanguageActionFilter>();
// Inject ticket formatting // Inject ticket formatting
services.AddTransient(typeof(ISecureDataFormat<>), typeof(SecureDataFormat<>)); services.AddTransient(typeof(ISecureDataFormat<>), typeof(SecureDataFormat<>));
@ -223,7 +228,7 @@ namespace Yavsc
{ {
options.ResourcesPath = "Resources"; options.ResourcesPath = "Resources";
}); });
} }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
@ -241,7 +246,7 @@ namespace Yavsc
Startup.UserFilesDirName = new DirectoryInfo(siteSettings.Value.UserFiles.Blog).FullName; Startup.UserFilesDirName = new DirectoryInfo(siteSettings.Value.UserFiles.Blog).FullName;
Startup.UserBillsDirName = new DirectoryInfo(siteSettings.Value.UserFiles.Bills).FullName; Startup.UserBillsDirName = new DirectoryInfo(siteSettings.Value.UserFiles.Bills).FullName;
Startup.Temp = siteSettings.Value.TempDir; Startup.Temp = siteSettings.Value.TempDir;
// TODO implement an installation & upgrade procedure // TODO implement an installation & upgrade procedure
// Create required directories // Create required directories
foreach (string dir in new string[] { UserFilesDirName, UserBillsDirName, SiteSetup.TempDir }) foreach (string dir in new string[] { UserFilesDirName, UserBillsDirName, SiteSetup.TempDir })
@ -339,14 +344,14 @@ namespace Yavsc
ConfigureWorkflow(app, SiteSetup, logger); ConfigureWorkflow(app, SiteSetup, logger);
app.UseRequestLocalization(localizationOptions.Value, (RequestCulture) new RequestCulture((string)"fr")); app.UseRequestLocalization(localizationOptions.Value, (RequestCulture) new RequestCulture((string)"fr"));
app.UseSession(); app.UseSession();
app.UseMvc(routes => app.UseMvc(routes =>
{ {
routes.MapRoute( routes.MapRoute(
name: "default", name: "default",
template: "{controller=Home}/{action=Index}/{id?}"); template: "{controller=Home}/{action=Index}/{id?}");
}); });
} }
// Entry point for the application. // Entry point for the application.
@ -354,4 +359,4 @@ namespace Yavsc
} }
} }
// //