files tree made better.

This commit is contained in:
Paul Schneider 2019-01-01 16:28:47 +00:00
commit ccc91bbf19
1630 changed files with 18209 additions and 41860 deletions

View file

@ -0,0 +1,690 @@
using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.OptionsModel;
using Microsoft.AspNet.Http;
using Yavsc.Models;
using Yavsc.Services;
using Yavsc.ViewModels.Account;
using Microsoft.Extensions.Localization;
using Microsoft.Data.Entity;
using Newtonsoft.Json;
namespace Yavsc.Controllers
{
using Yavsc.Abstract.Manage;
using Yavsc.Helpers;
public class AccountController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender;
// private readonly ISmsSender _smsSender;
private readonly ILogger _logger;
SiteSettings _siteSettings;
TwilioSettings _twilioSettings;
IStringLocalizer _localizer;
// TwilioSettings _twilioSettings;
ApplicationDbContext _dbContext;
public AccountController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender,
IOptions<SiteSettings> siteSettings,
ILoggerFactory loggerFactory, IOptions<TwilioSettings> twilioSettings,
IStringLocalizer<Yavsc.Resources.YavscLocalisation> localizer,
ApplicationDbContext dbContext)
{
_userManager = userManager;
_signInManager = signInManager;
// _userManager.RegisterTokenProvider("SMS",new UserTokenProvider());
// _userManager.RegisterTokenProvider("Phone", new UserTokenProvider());
_emailSender = emailSender;
_siteSettings = siteSettings.Value;
_twilioSettings = twilioSettings.Value;
_logger = loggerFactory.CreateLogger<AccountController>();
_localizer = localizer;
_dbContext = dbContext;
}
const string nextPageTokenKey = "nextPageTokenKey";
const int defaultLen = 10;
[Authorize(Roles = Constants.AdminGroupName)]
[Route("Account/UserList/{page?}/{len?}")]
public async Task<IActionResult> UserList(string page, string len)
{
int pageNum = page!=null ? int.Parse(page) : 0;
int pageLen = len!=null ? int.Parse(len) : defaultLen;
var users = _dbContext.Users.OrderBy(u=>u.UserName);
var shown = pageNum * pageLen;
var toShow = users.Skip(shown).Take(pageLen);
ViewBag.page = pageNum;
ViewBag.hasNext = await users.CountAsync() > (toShow.Count() + shown);
ViewBag.nextpage = pageNum+1;
ViewBag.pageLen = pageLen;
return View(toShow.ToArray());
}
string GeneratePageToken() {
return System.Guid.NewGuid().ToString();
}
[AllowAnonymous]
[HttpGet(Constants.LoginPath)]
public ActionResult SignIn(string returnUrl = null)
{
// Note: the "returnUrl" parameter corresponds to the endpoint the user agent
// will be redirected to after a successful authentication and not
// the redirect_uri of the requesting client application against the third
// party identity provider.
return View(new SignInViewModel
{
ReturnUrl = returnUrl ?? "/",
ExternalProviders = HttpContext.GetExternalProviders()
});
/*
Note: When using an external login provider, redirect the query :
var properties = _signInManager.ConfigureExternalAuthenticationProperties(OpenIdConnectDefaults.AuthenticationScheme, returnUrl);
return new ChallengeResult(OpenIdConnectDefaults.AuthenticationScheme, properties);
*/
}
[AllowAnonymous]
public ActionResult AccessDenied(string requestUrl = null)
{
ViewBag.UserIsSignedIn = User.IsSignedIn();
if (string.IsNullOrWhiteSpace(requestUrl))
if (string.IsNullOrWhiteSpace(Request.Headers["Referer"]))
requestUrl = "/";
else requestUrl = Request.Headers["Referer"];
return View("AccessDenied", requestUrl);
}
[AllowAnonymous]
[HttpPost(Constants.LoginPath)]
public async Task<IActionResult> SignIn(SignInViewModel model)
{
if (Request.Method == "POST")
{
if (model.Provider ==null || model.Provider == "LOCAL")
{
if (ModelState.IsValid)
{
var user = await _userManager.FindByNameAsync(model.UserName);
if (user != null)
{
if (!await _userManager.IsEmailConfirmedAsync(user))
{
ModelState.AddModelError(string.Empty,
"You must have a confirmed email to log in.");
return this.ViewOk(model);
}
}
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
return Redirect(model.ReturnUrl ?? "/");
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(SendCode), new { ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning(2, "User account locked out.");
return this.ViewOk("Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
model.ExternalProviders = HttpContext.GetExternalProviders();
return this.ViewOk(model);
}
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError(string.Empty, "Unexpected behavior: something failed ... you could try again, or contact me ...");
}
else
{
// Note: the "provider" parameter corresponds to the external
// authentication provider choosen by the user agent.
if (string.IsNullOrEmpty(model.Provider))
{
_logger.LogWarning("Provider not specified");
return HttpBadRequest();
}
if (!_signInManager.GetExternalAuthenticationSchemes().Any(x => x.AuthenticationScheme == model.Provider))
{
_logger.LogWarning($"Provider not found : {model.Provider}");
return HttpBadRequest();
}
// Instruct the middleware corresponding to the requested external identity
// provider to redirect the user agent to its own authorization endpoint.
// Note: the authenticationScheme parameter must match the value configured in Startup.cs
// Note: the "returnUrl" parameter corresponds to the endpoint the user agent
// will be redirected to after a successful authentication and not
// the redirect_uri of the requesting client application.
if (string.IsNullOrEmpty(model.ReturnUrl))
{
_logger.LogWarning("ReturnUrl not specified");
return HttpBadRequest();
}
// Note: this still is not the redirect uri given to the third party provider, at building the challenge.
var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = model.ReturnUrl });
var properties = _signInManager.ConfigureExternalAuthenticationProperties(model.Provider, redirectUrl);
// var properties = new AuthenticationProperties{RedirectUri=ReturnUrl};
return new ChallengeResult(model.Provider, properties);
}
}
model.ExternalProviders = HttpContext.GetExternalProviders();
return View(model);
}
//
// GET: /Account/Register
[AllowAnonymous]
[HttpGet]
public IActionResult Register()
{
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.UserName, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
_logger.LogInformation(3, "User created a new account with password.");
await _emailSender.SendEmailAsync(Startup.SiteSetup.Owner.Name, Startup.SiteSetup.Owner.EMail,
$"[{_siteSettings.Title}] Inscription avec mot de passe: {user.UserName} ", $"{user.Id}/{user.UserName}/{user.Email}");
// TODO user.DiskQuota = Startup.SiteSetup.UserFiles.Quota;
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: "https");
var emailSent = await _emailSender.SendEmailAsync(model.UserName, model.Email, _localizer["ConfirmYourAccountTitle"],
string.Format(_localizer["ConfirmYourAccountBody"], _siteSettings.Title, callbackUrl, _siteSettings.Slogan, _siteSettings.Audience));
// No, wait for more than a login pass submission:
// do not await _signInManager.SignInAsync(user, isPersistent: false);
if (emailSent==null)
{
_logger.LogWarning("User created with error sending email confirmation request");
this.NotifyWarning(
"E-mail confirmation",
_localizer["ErrorSendingEmailForConfirm"]
);
}
else
this.NotifyInfo(
"E-mail confirmation",
_localizer["EmailSentForConfirm"]
);
return View("AccountCreated");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
[Authorize, HttpPost, ValidateAntiForgeryToken]
public async Task<IActionResult> SendEMailForConfirm()
{
var user = await _userManager.FindByIdAsync(User.GetUserId());
var model = await SendEMailForConfirmAsync(user);
return View("ConfirmEmailSent",model);
}
private async Task<EmailSentViewModel> SendEMailForConfirmAsync(ApplicationUser user)
{
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
var callbackUrl = Url.Action("ConfirmEmail", "Account",
new { userId = user.Id, code = code }, protocol: "https");
var res = await _emailSender.SendEmailAsync(user.UserName, user.Email,
this._localizer["ConfirmYourAccountTitle"],
string.Format(this._localizer["ConfirmYourAccountBody"],
_siteSettings.Title, callbackUrl, _siteSettings.Slogan,
_siteSettings.Audience));
return res;
}
//
// POST: /Account/LogOff
[HttpPost(Constants.LogoutPath)]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LogOff(string returnUrl = null)
{
await _signInManager.SignOutAsync();
_logger.LogInformation(4, "User logged out.");
if (returnUrl == null) return RedirectToAction(nameof(HomeController.Index), "Home");
return Redirect(returnUrl);
}
//
// GET: /Account/ExternalLoginCallback
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null)
{
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
_logger.LogWarning("No external provider info found.");
return Redirect("~/signin"); // RedirectToAction(nameof(OAuthController.SignIn));
}
// 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;
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
if (result.Succeeded)
{
_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);
ninfo.ProviderDisplayName = info.ProviderDisplayName;
_dbContext.Entry(ninfo).State = EntityState.Modified;
_dbContext.SaveChanges(User.GetUserId());
return Redirect(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl });
}
if (result.IsLockedOut)
{
return View("Lockout");
}
else
{
ViewData["jsonres"] = JsonConvert.SerializeObject(result);
// If the user does not have an account, then ask the user to create an account.
ViewData["ReturnUrl"] = returnUrl;
ViewData["LoginProvider"] = info.LoginProvider;
var email = info.ExternalPrincipal.FindFirstValue(ClaimTypes.Email);
var name = info.ExternalPrincipal.FindFirstValue(ClaimTypes.Name);
var avatar = info.ExternalPrincipal.FindFirstValue("urn:google:profile");
/* var phone = info.ExternalPrincipal.FindFirstValue(ClaimTypes.HomePhone);
var mobile = info.ExternalPrincipal.FindFirstValue(ClaimTypes.MobilePhone);
var postalcode = info.ExternalPrincipal.FindFirstValue(ClaimTypes.PostalCode);
var locality = info.ExternalPrincipal.FindFirstValue(ClaimTypes.Locality);
var country = info.ExternalPrincipal.FindFirstValue(ClaimTypes.Country);
foreach (var claim in info.ExternalPrincipal.Claims)
_logger.LogWarning("# {0} Claim: {1} {2}", info.LoginProvider, claim.Type, claim.Value);
*/
var access_token = info.ExternalPrincipal.FindFirstValue("access_token");
var token_type = info.ExternalPrincipal.FindFirstValue("token_type");
var expires_in = info.ExternalPrincipal.FindFirstValue("expires_in");
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel
{
Email = email,
Name = name
});
}
}
//
// POST: /Account/ExternalLoginConfirmation
[HttpPost]
[ValidateAntiForgeryToken]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null)
{
if (User.IsSignedIn())
{
return RedirectToAction(nameof(ManageController.Index), "Manage");
}
if (ModelState.IsValid)
{
// Get the information about the user from the external login provider
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return View("ExternalLoginFailure");
}
var user = new ApplicationUser { UserName = model.Name, Email = model.Email };
var result = await _userManager.CreateAsync(user);
if (result.Succeeded)
{
info.ProviderDisplayName = info.ExternalPrincipal.Claims.First(c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name")?.Value;
result = await _userManager.AddLoginAsync(user, info);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
await _emailSender.SendEmailAsync(Startup.SiteSetup.Owner.Name, Startup.SiteSetup.Owner.EMail,
$"[{_siteSettings.Title}] Inscription via {info.LoginProvider}: {user.UserName} ", $"{user.Id}/{user.UserName}/{user.Email}");
_logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider);
return Redirect(returnUrl);
}
}
AddErrors(result);
}
ViewData["ReturnUrl"] = returnUrl;
return View(model);
}
// GET: /Account/ConfirmEmail
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return View("Error");
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
return View("Error");
}
var result = await _userManager.ConfirmEmailAsync(user, code);
return View(result.Succeeded ? "ConfirmEmail" : "Error");
}
//
// GET: /Account/ForgotPassword
[HttpGet]
[AllowAnonymous]
public IActionResult ForgotPassword()
{
return View();
}
//
// POST: /Account/ForgotPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
ApplicationUser user;
// Username should not contain any '@'
if (model.LoginOrEmail.Contains('@')) {
user = await _userManager.FindByEmailAsync(model.LoginOrEmail);
}
else {
user = await _dbContext.Users.FirstOrDefaultAsync( u => u.UserName == model.LoginOrEmail);
}
// Don't reveal that the user does not exist or is not confirmed
if (user == null)
{
_logger.LogWarning($"ForgotPassword: Email or User name {model.LoginOrEmail} not found");
return View("ForgotPasswordConfirmation");
}
// user != null
// We want him to have a confirmed e-mail, and prevent this script
// to be used to send e-mail to any arbitrary person
if (!await _userManager.IsEmailConfirmedAsync(user))
{
_logger.LogWarning($"ForgotPassword: Email {model.LoginOrEmail} not confirmed");
return View("ForgotPasswordConfirmation");
}
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
var code = await _userManager.GeneratePasswordResetTokenAsync(user);
var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: "https");
await _emailSender.SendEmailAsync(user.UserName, user.Email, _localizer["Reset Password"],
_localizer["Please reset your password by following this link:"] + " <" + callbackUrl + ">");
return View("ForgotPasswordConfirmation");
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/ForgotPasswordConfirmation
[HttpGet]
[AllowAnonymous]
public IActionResult ForgotPasswordConfirmation()
{
return View();
}
//
// GET: /Account/ResetPassword
[HttpGet]
[AllowAnonymous]
public IActionResult ResetPassword(string UserId, string code = null)
{
return code == null ? View("Error") : View();
}
//
// POST: /Account/ResetPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await _userManager.FindByEmailAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account");
}
var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password);
if (result.Succeeded)
{
_logger.LogInformation($"Password reset for {user.UserName}:{model.Password}");
return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account");
}
_logger.LogInformation($"Password reset failed for {user.UserName}:{model.Password}");
AddErrors(result);
return View();
}
//
// GET: /Account/ResetPasswordConfirmation
[HttpGet]
[AllowAnonymous]
public IActionResult ResetPasswordConfirmation()
{
return View();
}
//
// GET: /Account/SendCode
[HttpGet, AllowAnonymous]
public async Task<ActionResult> SendCode(string returnUrl = null, bool rememberMe = false)
{
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error", new Exception("No Two factor authentication user"));
}
var userFactors = await _userManager.GetValidTwoFactorProvidersAsync(user);
var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/SendCode
[HttpPost]
[ValidateAntiForgeryToken, AllowAnonymous]
public async Task<IActionResult> SendCode(SendCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View();
}
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error", new Exception("user is null"));
}
// Generate the token and send it
var code = await _userManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider);
if (string.IsNullOrWhiteSpace(code))
{
return View("Error", new Exception("Code is empty"));
}
var message = "Your security code is: " + code;
if (model.SelectedProvider == Constants.MobileAppFactor)
{
return View("Error", new Exception("No SMS service was activated"));
}
else // if (model.SelectedProvider == Constants.EMailFactor || model.SelectedProvider == "Default" )
if (model.SelectedProvider == Constants.SMSFactor)
{
return View("Error", new Exception("No SMS service was activated"));
// await _smsSender.SendSmsAsync(_twilioSettings, await _userManager.GetPhoneNumberAsync(user), message);
}
else // if (model.SelectedProvider == Constants.EMailFactor || model.SelectedProvider == "Default" )
{
await _emailSender.SendEmailAsync(user.UserName, await _userManager.GetEmailAsync(user), "Security Code", message);
}
return RedirectToAction(nameof(VerifyCode), new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
}
//
// GET: /Account/VerifyCode
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> VerifyCode(string provider, bool rememberMe, string returnUrl = null)
{
// Require that the user has already logged in via username/password or external login
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error", new Exception("user is null"));
}
return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/VerifyCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyCode(VerifyCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// The following code protects for brute force attacks against the two factor codes.
// If a user enters incorrect codes for a specified amount of time then the user account
// will be locked out for a specified amount of time.
_logger.LogWarning("Signin with code: {0} {1}", model.Provider, model.Code);
var result = await _signInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser);
if (result.Succeeded)
{
ViewData["StatusMessage"] = "Your code was verified";
_logger.LogInformation($"Signed in. returning to {model.ReturnUrl}");
return Redirect(model.ReturnUrl);
}
if (result.IsLockedOut)
{
_logger.LogWarning(7, "User account locked out.");
return View("Lockout");
}
else
{
ModelState.AddModelError("", "Code invalide ");
return View(model);
}
}
[HttpGet, Authorize]
public IActionResult Delete()
{
return View();
}
[HttpPost, Authorize]
public async Task<IActionResult> Delete(UnregisterViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await _userManager.FindByIdAsync(User.GetUserId());
var result = await _userManager.DeleteAsync(user);
if (!result.Succeeded)
{
AddErrors(result);
return new BadRequestObjectResult(ModelState);
}
await _signInManager.SignOutAsync();
return RedirectToAction("Index", "Home");
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, _localizer[error.Code]);
}
}
private async Task<ApplicationUser> GetCurrentUserAsync()
{
return await _userManager.FindByIdAsync(HttpContext.User.GetUserId());
}
#endregion
}
}

View file

@ -0,0 +1,752 @@
using System.Linq;
using System.Threading.Tasks;
using System.Security.Claims;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.OptionsModel;
using Microsoft.Data.Entity;
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Localization;
using Yavsc.Models.Workflow;
using Yavsc.Models.Identity;
namespace Yavsc.Controllers
{
using Yavsc.Helpers;
using Models.Relationship;
using Models.Bank;
using ViewModels.Calendar;
using Yavsc.Models;
using Yavsc.Services;
using Yavsc.ViewModels.Manage;
using System.IO;
[Authorize]
public class ManageController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ILogger _logger;
private SiteSettings _siteSettings;
private ApplicationDbContext _dbContext;
private GoogleAuthSettings _googleSettings;
private PayPalSettings _payPalSettings;
private IGoogleCloudMessageSender _GCMSender;
private SIRENChecker _cchecker;
private IStringLocalizer _SR;
private CompanyInfoSettings _cinfoSettings;
ICalendarManager _calendarManager;
public ManageController(
ApplicationDbContext context,
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender,
IGoogleCloudMessageSender GCMSender,
IOptions<SiteSettings> siteSettings,
IOptions<GoogleAuthSettings> googleSettings,
IOptions<PayPalSettings> paypalSettings,
IOptions<CompanyInfoSettings> cinfoSettings,
IStringLocalizer<Yavsc.Resources.YavscLocalisation> SR,
ICalendarManager calendarManager,
ILoggerFactory loggerFactory)
{
_dbContext = context;
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_GCMSender = GCMSender;
_siteSettings = siteSettings.Value;
_googleSettings = googleSettings.Value;
_payPalSettings = paypalSettings.Value;
_cinfoSettings = cinfoSettings.Value;
_cchecker = new SIRENChecker(cinfoSettings.Value);
_SR = SR;
_calendarManager = calendarManager;
_logger = loggerFactory.CreateLogger<ManageController>();
}
//
// GET: /Manage/Index
[HttpGet]
public async Task<IActionResult> Index(ManageMessageId? message = null)
{
ViewData["StatusMessage"] =
message == ManageMessageId.ChangePasswordSuccess ? _SR["Your password has been changed."]
: message == ManageMessageId.SetPasswordSuccess ? _SR["Your password has been set."]
: message == ManageMessageId.SetTwoFactorSuccess ? _SR["Your two-factor authentication provider has been set."]
: message == ManageMessageId.Error ? _SR["An error has occurred."]
: message == ManageMessageId.AddPhoneSuccess ? _SR["Your phone number was added."]
: message == ManageMessageId.RemovePhoneSuccess ? _SR["Your phone number was removed."]
: message == ManageMessageId.ChangeNameSuccess ? _SR["Your name was updated."]
: message == ManageMessageId.SetActivitySuccess ? _SR["Your activity was set."]
: message == ManageMessageId.AvatarUpdateSuccess ? _SR["Your avatar was updated."]
: message == ManageMessageId.IdentityUpdateSuccess ? _SR["Your identity was updated."]
: message == ManageMessageId.SetBankInfoSuccess ? _SR["Vos informations bancaires ont bien été enregistrées."]
: message == ManageMessageId.SetAddressSuccess ? _SR["Votre adresse a bien été enregistrée."]
: message == ManageMessageId.SetMonthlyEmailSuccess ? _SR["Vos préférences concernant la lettre mensuelle ont été sauvegardées."]
: "";
var user = await GetCurrentUserAsync();
long pc = _dbContext.Blogspot.Count(x => x.AuthorId == user.Id);
var model = new IndexViewModel
{
HasPassword = await _userManager.HasPasswordAsync(user),
PhoneNumber = await _userManager.GetPhoneNumberAsync(user),
TwoFactor = await _userManager.GetTwoFactorEnabledAsync(user),
Logins = await _userManager.GetLoginsAsync(user),
BrowserRemembered = await _signInManager.IsTwoFactorClientRememberedAsync(user),
UserName = user.UserName,
PostsCounter = pc,
Balance = user.AccountBalance,
ActiveCommandCount = _dbContext.RdvQueries.Count(x => (x.ClientId == user.Id) && (x.EventDate > DateTime.Now)),
HasDedicatedCalendar = !string.IsNullOrEmpty(user.DedicatedGoogleCalendar),
Roles = await _userManager.GetRolesAsync(user),
PostalAddress = user.PostalAddress?.Address,
FullName = user.FullName,
Avatar = user.Avatar,
BankInfo = user.BankInfo,
DiskUsage = user.DiskUsage,
DiskQuota = user.DiskQuota,
DedicatedCalendarId = user.DedicatedGoogleCalendar,
EMail = user.Email,
EmailConfirmed = await _userManager.IsEmailConfirmedAsync(user),
AllowMonthlyEmail = user.AllowMonthlyEmail
};
model.HaveProfessionalSettings = _dbContext.Performers.Any(x => x.PerformerId == user.Id);
var usrActs = _dbContext.UserActivities.Include(a=>a.Does).Where(a=> a.UserId == user.Id).ToArray();
// TODO remember me who this magical a.Settings is built
var usrActToSet = usrActs.Where( a => ( a.Settings == null && a.Does.SettingsClassName != null )).ToArray();
model.HaveActivityToConfigure = usrActToSet .Count()>0;
model.Activity = _dbContext.UserActivities.Include(a=>a.Does).Where(u=>u.UserId == user.Id).ToList();
return View(model);
}
[HttpGet]
public async Task<IActionResult> ProfileEMailUsage ()
{
var user = await GetCurrentUserAsync();
return View("ProfileEMailUsage", new ProfileEMailUsageViewModel(user));
}
[HttpPost]
public async Task<IActionResult> ProfileEMailUsage (ProfileEMailUsageViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// Generate the token and send it
var user = await GetCurrentUserAsync();
user.AllowMonthlyEmail = model.Allow;
await this._dbContext.SaveChangesAsync(User.GetUserId());
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.SetMonthlyEmailSuccess });
}
//
// POST: /Manage/RemoveLogin
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemoveLogin(RemoveLoginViewModel account)
{
ManageMessageId? message = ManageMessageId.Error;
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.RemoveLoginAsync(user, account.LoginProvider, account.ProviderKey);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
message = ManageMessageId.RemoveLoginSuccess;
}
}
return RedirectToAction(nameof(ManageLogins), new { Message = message });
}
//
// GET: /Manage/AddPhoneNumber
public IActionResult AddPhoneNumber()
{
return View();
}
//
// POST: /Manage/AddPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddPhoneNumber(AddPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// Generate the token and send it
var user = await GetCurrentUserAsync();
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber);
// TODO await _smsSender.SendSmsAsync(_twilioSettings, model.PhoneNumber, "Your security code is: " + code);
return RedirectToAction(nameof(VerifyPhoneNumber), new { PhoneNumber = model.PhoneNumber });
}
//
// POST: /Manage/EnableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EnableTwoFactorAuthentication()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await _userManager.SetTwoFactorEnabledAsync(user, true);
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(1, "User enabled two-factor authentication.");
}
return RedirectToAction(nameof(Index), "Manage");
}
//
// POST: /Manage/DisableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DisableTwoFactorAuthentication()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await _userManager.SetTwoFactorEnabledAsync(user, false);
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(2, "User disabled two-factor authentication.");
}
return RedirectToAction(nameof(Index), "Manage");
}
//
// GET: /Manage/VerifyPhoneNumber
[HttpGet]
public async Task<IActionResult> VerifyPhoneNumber(string phoneNumber)
{
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(await GetCurrentUserAsync(), phoneNumber);
// Send an SMS to verify the phone number
return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber });
}
//
// POST: /Manage/VerifyPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.ChangePhoneNumberAsync(user, model.PhoneNumber, model.Code);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.AddPhoneSuccess });
}
}
// If we got this far, something failed, redisplay the form
ModelState.AddModelError(string.Empty, "Failed to verify phone number");
return View(model);
}
//
// GET: /Manage/RemovePhoneNumber
[HttpGet]
public async Task<IActionResult> RemovePhoneNumber()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.SetPhoneNumberAsync(user, null);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.RemovePhoneSuccess });
}
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//
// GET: /Manage/ChangePassword
[HttpGet]
public IActionResult ChangePassword()
{
return View();
}
[HttpGet]
public IActionResult AddMobileApp(GoogleCloudMobileDeclaration model)
{
return View();
}
[HttpGet]
public async Task<IActionResult> SetGoogleCalendar(string returnUrl, string pageToken)
{
var uid = User.GetUserId();
var calendars = await _calendarManager.GetCalendarsAsync(uid, pageToken);
return View(new SetGoogleCalendarViewModel {
ReturnUrl = returnUrl,
Calendars = calendars
});
}
[HttpPost, ValidateAntiForgeryToken]
public async Task<IActionResult> SetGoogleCalendar(SetGoogleCalendarViewModel model)
{
var user = _dbContext.Users.FirstOrDefault(u => u.Id == User.GetUserId());
user.DedicatedGoogleCalendar = model.GoogleCalendarId;
await _dbContext.SaveChangesAsync(User.GetUserId());
if (string.IsNullOrEmpty(model.ReturnUrl))
return RedirectToAction("Index");
else return Redirect(model.ReturnUrl);
}
[HttpGet]
public async Task<IActionResult> AddBankInfo()
{
var uid = User.GetUserId();
var user = await _dbContext.Users.Include(u=>u.BankInfo).SingleAsync(u=>u.Id==uid);
return View(user.BankInfo);
}
[HttpPost]
public async Task<IActionResult> AddBankInfo (BankIdentity model)
{
if (ModelState.IsValid)
{
// TODO PostBankInfoRequirement & auth
var uid = User.GetUserId();
var user = _dbContext.Users.Include(u=>u.BankInfo)
.Single(u=>u.Id == uid);
if (user.BankInfo != null)
{
model.Id = user.BankInfo.Id;
_dbContext.Entry(user.BankInfo).State = EntityState.Detached;
_dbContext.Update(model);
}
else {
user.BankInfo = model;
_dbContext.Update(user);
}
await _dbContext.SaveChangesAsync();
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.SetBankInfoSuccess });
}
[HttpGet]
public async Task<IActionResult> SetFullName()
{
var user = await _userManager.FindByIdAsync(User.GetUserId());
return View(user);
}
//
// POST: /Manage/ChangePassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(3, "User changed their password successfully.");
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.ChangePasswordSuccess });
}
AddErrors(result);
return View(model);
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
public IActionResult ChangeUserName()
{
return View(new ChangeUserNameViewModel() { NewUserName = User.Identity.Name });
}
[HttpPost]
public async Task<IActionResult> ChangeUserName(ChangeUserNameViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var oldUserName = user.UserName;
var result = await this._userManager.SetUserNameAsync(user, model.NewUserName);
if (result.Succeeded)
{
// Renames the blog files
var userdirinfo = new DirectoryInfo(
Path.Combine(_siteSettings.Blog,
oldUserName));
var newdir = Path.Combine(_siteSettings.Blog,
model.NewUserName);
if (userdirinfo.Exists)
userdirinfo.MoveTo(newdir);
// Renames the Avatars
foreach (string s in new string [] { ".png", ".s.png", ".xs.png" })
{
FileInfo fi = new FileInfo(
Path.Combine(_siteSettings.Avatars,
oldUserName+s));
if (fi.Exists)
fi.MoveTo(Path.Combine(_siteSettings.Avatars,
model.NewUserName+s));
}
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(3, "User changed his user name successfully.");
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.ChangeNameSuccess });
}
AddErrors(result);
return View(model);
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//
// GET: /Manage/SetPassword
[HttpGet]
public IActionResult SetPassword()
{
return View();
}
//
// POST: /Manage/SetPassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SetPassword(SetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.AddPasswordAsync(user, model.NewPassword);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.SetPasswordSuccess });
}
AddErrors(result);
return View(model);
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//GET: /Manage/ManageLogins
[HttpGet]
public async Task<IActionResult> ManageLogins(ManageMessageId? message = null)
{
ViewData["StatusMessage"] =
message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: message == ManageMessageId.AddLoginSuccess ? "The external login was added."
: message == ManageMessageId.Error ? "An error has occurred."
: "";
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var userLogins = await _userManager.GetLoginsAsync(user);
var otherLogins = _signInManager.GetExternalAuthenticationSchemes().Where(auth => userLogins.All(ul => auth.AuthenticationScheme != ul.LoginProvider)).ToList();
ViewData["ShowRemoveButton"] = user.PasswordHash != null || userLogins.Count > 1;
return View(new ManageLoginsViewModel
{
CurrentLogins = userLogins,
OtherLogins = otherLogins
});
}
//
// POST: /Manage/LinkLogin
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult LinkLogin(string provider)
{
// Request a redirect to the external login provider to link a login for the current user
var redirectUrl = Url.Action("LinkLoginCallback", "Manage");
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, User.GetUserId());
return new ChallengeResult(provider, properties);
}
//
// GET: /Manage/LinkLoginCallback
[HttpGet]
public async Task<ActionResult> LinkLoginCallback()
{
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var info = await _signInManager.GetExternalLoginInfoAsync(User.GetUserId());
if (info == null)
{
return RedirectToAction(nameof(ManageLogins), new { Message = ManageMessageId.Error });
}
var result = await _userManager.AddLoginAsync(user, info);
var message = result.Succeeded ? ManageMessageId.AddLoginSuccess : ManageMessageId.Error;
return RedirectToAction(nameof(ManageLogins), new { Message = message });
}
[HttpGet]
public IActionResult SetAvatar()
{
return View();
}
[HttpGet]
public IActionResult SetActivity()
{
var user = GetCurrentUserAsync().Result;
var uid = user.Id;
var existing = _dbContext.Performers
.Include(p=>p.Performer)
.Include(x => x.OrganizationAddress)
.Include(p=>p.Activity)
.FirstOrDefault(x => x.PerformerId == uid);
ViewBag.GoogleSettings = _googleSettings;
if (existing!=null)
{
var currentProfile = _dbContext.Performers.Include(x => x.OrganizationAddress)
.First(x => x.PerformerId == uid);
ViewBag.Activities = _dbContext.ActivityItems(existing.Activity);
return View(currentProfile);
}
ViewBag.Activities = _dbContext.ActivityItems(new List<UserActivity>());
return View(new PerformerProfile
{
PerformerId = user.Id,
Performer = user,
OrganizationAddress = new Location()
});
}
[HttpPost]
public async Task<IActionResult> SetActivity(PerformerProfile model)
{
var user = GetCurrentUserAsync().Result;
var uid = user.Id;
try
{
if (ModelState.IsValid)
{
var exSiren = await _dbContext.ExceptionsSIREN.FirstOrDefaultAsync(
ex => ex.SIREN == model.SIREN
);
if (exSiren != null)
{
_logger.LogInformation("Exception SIREN:" + exSiren);
}
else
{
var taskCheck = await _cchecker.CheckAsync(model.SIREN);
if (!taskCheck.success)
{
ModelState.AddModelError(
"SIREN",
_SR["Invalid company number"] + " (" + taskCheck.errorCode + ")"
);
_logger.LogInformation($"Invalid company number: {model.SIREN}/{taskCheck.errorType}/{taskCheck.errorCode}/{taskCheck.errorMessage}" );
}
}
}
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
ModelState.AddModelError("SIREN", ex.Message);
}
if (ModelState.IsValid)
{
if (uid == model.PerformerId)
{
bool addrexists = _dbContext.Locations.Any(x => model.OrganizationAddress.Id == x.Id);
if (!addrexists)
{
_dbContext.Locations.Add(model.OrganizationAddress);
}
if (_dbContext.Performers.Any(p=>p.PerformerId == uid))
{
_dbContext.Update(model);
}
else _dbContext.Performers.Add(model);
_dbContext.SaveChanges(User.GetUserId());
// Give this user the Performer role
if (!User.IsInRole("Performer"))
await _userManager.AddToRoleAsync(user, "Performer");
var message = ManageMessageId.SetActivitySuccess;
return RedirectToAction(nameof(Index), new { Message = message });
}
else ModelState.AddModelError(string.Empty, $"Access denied ({uid} vs {model.PerformerId})");
}
ViewBag.Activities = _dbContext.ActivityItems(new List<UserActivity>());
ViewBag.GoogleSettings = _googleSettings;
model.Performer = _dbContext.Users.Single(u=>u.Id == model.PerformerId);
return View(model);
}
[HttpPost]
public async Task<IActionResult> UnsetActivity()
{
var user = GetCurrentUserAsync().Result;
var uid = user.Id;
bool existing = _dbContext.Performers.Any(x => x.PerformerId == uid);
if (existing)
{
_dbContext.Performers.Remove(
_dbContext.Performers.First(x => x.PerformerId == uid)
);
_dbContext.SaveChanges(User.GetUserId());
await _userManager.RemoveFromRoleAsync(user, "Performer");
}
var message = ManageMessageId.UnsetActivitySuccess;
return RedirectToAction(nameof(Index), new { Message = message });
}
[HttpGet, Route("/Manage/Credits")]
public IActionResult Credits()
{
return View();
}
public IActionResult Credit(string id)
{
if (id == "Cancel" || id == "Return")
{
return View ("Credit"+id);
}
return View();
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
public enum ManageMessageId
{
AddPhoneSuccess,
AddLoginSuccess,
ChangePasswordSuccess,
ChangeNameSuccess,
SetTwoFactorSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
RemovePhoneSuccess,
SetActivitySuccess,
UnsetActivitySuccess,
AvatarUpdateSuccess,
IdentityUpdateSuccess,
SetBankInfoSuccess,
SetAddressSuccess,
SetMonthlyEmailSuccess,
Error
}
private async Task<ApplicationUser> GetCurrentUserAsync()
{
return await _userManager.FindByIdAsync(HttpContext.User.GetUserId());
}
#endregion
[HttpGet]
public async Task <IActionResult> SetAddress()
{
var uid = User.GetUserId();
var user = await _dbContext.Users.Include(u=>u.PostalAddress).SingleAsync(u=>u.Id==uid);
ViewBag.GoogleSettings = _googleSettings;
return View (new Yavsc.ViewModels.Manage.SetAddressViewModel { Street1 = user.PostalAddress?.Address } );
}
[HttpPost]
public async Task <IActionResult> SetAddress(Location model)
{
if (ModelState.IsValid) {
var uid = User.GetUserId();
var user = _dbContext.Users.Include(u=>u.PostalAddress).Single(u=>u.Id==uid);
var existingLocation = _dbContext.Locations.FirstOrDefault( x=>x.Address == model.Address
&& x.Longitude == model.Longitude && x.Latitude == model.Latitude );
if (existingLocation!=null) {
user.PostalAddressId = existingLocation.Id;
} else _dbContext.Attach<Location>(model);
user.PostalAddress = model;
await _dbContext.SaveChangesAsync();
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.SetAddressSuccess });
}
ViewBag.GoogleSettings = _googleSettings;
return View(new Yavsc.ViewModels.Manage.SetAddressViewModel { Street1 = model.Address});
}
public async Task<IActionResult> PaymentInfo (string id)
{
ViewData["id"] = id;
var info = await PayPalHelpers.GetCheckoutInfo(_dbContext,id);
return View(info);
}
public IActionResult PaymentError (string id, string error)
{
ViewData["error"] = error;
ViewData["id"] = id;
return View();
}
}
}

View file

@ -0,0 +1,153 @@
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.DataProtection.KeyManagement;
using Microsoft.AspNet.Http.Authentication;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.WebUtilities;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.OptionsModel;
using Microsoft.Extensions.Primitives;
using OAuth.AspNet.AuthServer;
using Yavsc.Models;
using Yavsc.Models.Auth;
namespace Yavsc.Controllers
{
[AllowAnonymous]
public class OAuthController : Controller
{
ApplicationDbContext _context;
UserManager<ApplicationUser> _userManager;
SiteSettings _siteSettings;
ILogger _logger;
private readonly SignInManager<ApplicationUser> _signInManager;
public OAuthController(ApplicationDbContext context, SignInManager<ApplicationUser> signInManager, IKeyManager keyManager,
UserManager<ApplicationUser> userManager,
IOptions<SiteSettings> siteSettings,
ILoggerFactory loggerFactory
)
{
_siteSettings = siteSettings.Value;
_context = context;
_signInManager = signInManager;
_userManager = userManager;
_logger = loggerFactory.CreateLogger<OAuthController>();
}
[HttpGet("~/api/getclaims"), Produces("application/json")]
public IActionResult GetClaims()
{
var identity = User.Identity as ClaimsIdentity;
var claims = from c in identity.Claims
select new
{
subject = c.Subject.Name,
type = c.Type,
value = c.Value
};
return Ok(claims);
}
[HttpGet(Constants.AuthorizePath),HttpPost(Constants.AuthorizePath)]
public async Task<ActionResult> Authorize()
{
if (Response.StatusCode != 200)
{
return View("AuthorizeError");
}
AuthenticationManager authentication = Request.HttpContext.Authentication;
var appAuthSheme = Startup.IdentityAppOptions.Cookies.ApplicationCookieAuthenticationScheme;
ClaimsPrincipal principal = await authentication.AuthenticateAsync(appAuthSheme);
if (principal == null)
{
await authentication.ChallengeAsync(appAuthSheme);
if (Response.StatusCode == 200)
return new HttpUnauthorizedResult();
return new HttpStatusCodeResult(Response.StatusCode);
}
string[] scopes = { };
string redirect_uri=null;
IDictionary<string,StringValues> queryStringComponents = null;
if (Request.QueryString.HasValue)
{
queryStringComponents = QueryHelpers.ParseQuery(Request.QueryString.Value);
if (queryStringComponents.ContainsKey("scope"))
scopes = ((string)queryStringComponents["scope"]).Split(' ');
if (queryStringComponents.ContainsKey("redirect_uri"))
redirect_uri = queryStringComponents["redirect_uri"];
}
var username = User.GetUserName();
var model = new AuthorisationView {
Scopes = (Constants.SiteScopes.Where(s=> scopes.Contains(s.Id))).ToArray(),
Message = $"Bienvenue {username}."
} ;
if (Request.Method == "POST")
{
if (!string.IsNullOrEmpty(Request.Form["submit.Grant"]))
{
principal = new ClaimsPrincipal(principal.Identities);
ClaimsIdentity primaryIdentity = (ClaimsIdentity)principal.Identity;
foreach (var scope in scopes)
{
primaryIdentity.AddClaim(new Claim("urn:oauth:scope", scope));
}
await authentication.SignInAsync(OAuthDefaults.AuthenticationType, principal);
}
if (!string.IsNullOrEmpty(Request.Form["submit.Deny"]))
{
await authentication.SignOutAsync(appAuthSheme);
if (redirect_uri!=null)
return Redirect(redirect_uri+"?error=scope-denied");
return Redirect("/");
}
if (!string.IsNullOrEmpty(Request.Form["submit.Login"]))
{
await authentication.SignOutAsync(appAuthSheme);
await authentication.ChallengeAsync(appAuthSheme);
return new HttpUnauthorizedResult();
}
}
if (Request.Headers.Keys.Contains("Accept")) {
var accepted = Request.Headers["Accept"];
if (accepted == "application/json")
{
return Ok(model);
}
}
return View(model);
}
[HttpGet("~/oauth/success")]
public IActionResult NativeAuthSuccess ()
{
return RedirectToAction("Index","Home");
}
}
}

View file

@ -0,0 +1,127 @@
using System.Threading.Tasks;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
using Yavsc.Models;
namespace Yavsc.Controllers
{
[Authorize("AdministratorOnly")]
public class UsersController : Controller
{
private ApplicationDbContext _context;
public UsersController(ApplicationDbContext context)
{
_context = context;
}
// GET: Users
public async Task<IActionResult> Index()
{
var applicationDbContext = _context.ApplicationUser.Include(a => a.PostalAddress);
return View(await applicationDbContext.ToListAsync());
}
// GET: Users/Details/5
public async Task<IActionResult> Details(string id)
{
if (id == null)
{
return HttpNotFound();
}
ApplicationUser applicationUser = await _context.ApplicationUser.SingleAsync(m => m.Id == id);
if (applicationUser == null)
{
return HttpNotFound();
}
return View(applicationUser);
}
// GET: Users/Create
public IActionResult Create()
{
ViewData["PostalAddressId"] = new SelectList(_context.Locations, "Id", "PostalAddress");
return View();
}
// POST: Users/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(ApplicationUser applicationUser)
{
if (ModelState.IsValid)
{
_context.ApplicationUser.Add(applicationUser);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewData["PostalAddressId"] = new SelectList(_context.Locations, "Id", "PostalAddress", applicationUser.PostalAddressId);
return View(applicationUser);
}
// GET: Users/Edit/5
public async Task<IActionResult> Edit(string id)
{
if (id == null)
{
return HttpNotFound();
}
ApplicationUser applicationUser = await _context.ApplicationUser.SingleAsync(m => m.Id == id);
if (applicationUser == null)
{
return HttpNotFound();
}
ViewData["PostalAddressId"] = new SelectList(_context.Locations, "Id", "PostalAddress", applicationUser.PostalAddressId);
return View(applicationUser);
}
// POST: Users/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(ApplicationUser applicationUser)
{
if (ModelState.IsValid)
{
_context.Update(applicationUser);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewData["PostalAddressId"] = new SelectList(_context.Locations, "Id", "PostalAddress", applicationUser.PostalAddressId);
return View(applicationUser);
}
// GET: Users/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(string id)
{
if (id == null)
{
return HttpNotFound();
}
ApplicationUser applicationUser = await _context.ApplicationUser.SingleAsync(m => m.Id == id);
if (applicationUser == null)
{
return HttpNotFound();
}
return View(applicationUser);
}
// POST: Users/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(string id)
{
ApplicationUser applicationUser = await _context.ApplicationUser.SingleAsync(m => m.Id == id);
_context.ApplicationUser.Remove(applicationUser);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
}
}