files tree made better.

This commit is contained in:
2019-01-01 16:28:47 +00:00
parent cb96933a25
commit 5b8e9b3975
1633 changed files with 18220 additions and 41869 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");
}
}
}

View File

@ -0,0 +1,158 @@
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Mvc;
using Microsoft.Data.Entity;
using Yavsc.Abstract.Identity;
using Yavsc.Models;
using Yavsc.ViewModels.Administration;
namespace Yavsc.Controllers
{
[Authorize()]
public class AdministrationController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
private readonly ApplicationDbContext context;
public AdministrationController(UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager,
ApplicationDbContext context)
{
_userManager = userManager;
_roleManager = roleManager;
this.context = context;
}
private async Task<bool> EnsureRoleList () {
// ensure all roles existence
foreach (string roleName in new string[] {
Constants.AdminGroupName,
Constants.StarGroupName,
Constants.PerformerGroupName,
Constants.FrontOfficeGroupName,
Constants.StarHunterGroupName,
Constants.BlogModeratorGroupName
})
if (!await _roleManager.RoleExistsAsync(roleName))
{
var role = new IdentityRole { Name = roleName };
var resultCreate = await _roleManager.CreateAsync(role);
if (!resultCreate.Succeeded)
{
AddErrors(resultCreate);
return false;
}
}
return true;
}
/// <summary>
/// Gives the (new if was not existing) administrator role
/// to current authenticated user, when no existing
/// administrator was found.
/// When nothing is to do, it returns a 404.
/// </summary>
/// <returns></returns>
[Produces("application/json")]
public async Task<IActionResult> Take()
{
// If some amdin already exists, make this method disapear
var admins = await _userManager.GetUsersInRoleAsync(Constants.AdminGroupName);
if (admins != null && admins.Count > 0)
{
// All is ok, nothing to do here.
if (User.IsInRole(Constants.AdminGroupName))
{
return Ok(new { message = "you already got it." });
}
return HttpNotFound();
}
var user = await _userManager.FindByIdAsync(User.GetUserId());
// check all user groups exist
if (!await EnsureRoleList()) {
ModelState.AddModelError(null, "Could not ensure role list existence. aborting.");
return new BadRequestObjectResult(ModelState);
}
IdentityRole adminRole;
adminRole = await _roleManager.FindByNameAsync(Constants.AdminGroupName);
var addToRoleResult = await _userManager.AddToRoleAsync(user, Constants.AdminGroupName);
if (!addToRoleResult.Succeeded)
{
AddErrors(addToRoleResult);
return new BadRequestObjectResult(ModelState);
}
return Ok(new { message = "you owned it." });
}
[Authorize(Roles = Constants.AdminGroupName)]
[Produces("application/json")]
public async Task<IActionResult> Index()
{
var adminCount = await _userManager.GetUsersInRoleAsync(
Constants.AdminGroupName);
var userCount = await context.Users.CountAsync();
var youAreAdmin = await _userManager.IsInRoleAsync(
await _userManager.FindByIdAsync(User.GetUserId()),
Constants.AdminGroupName);
var roles = _roleManager.Roles.Include(
x => x.Users
).Select(x => new RoleInfo {
Id = x.Id,
Name = x.Name,
Users = x.Users.Select(u=>u.UserId).ToArray()
});
var assembly = GetType().Assembly;
ViewBag.ThisAssembly = assembly.FullName;
ViewBag.RunTimeVersion = assembly.ImageRuntimeVersion;
ViewBag.HostContextFullName = Startup.HostingFullName;
return View(new AdminViewModel
{
Roles = roles.ToArray(),
AdminCount = adminCount.Count,
YouAreAdmin = youAreAdmin,
UserCount = userCount
});
}
public IActionResult Role(string id)
{
IdentityRole role = _roleManager.Roles
.Include(r=>r.Users).FirstOrDefault
( r=> r.Id == id );
var ri = GetRoleUserCollection(role);
return View("Role",ri);
}
public RoleUserCollection GetRoleUserCollection(IdentityRole role)
{
var result = new RoleUserCollection {
Id = role.Id,
Name = role.Name,
Users = context.Users.Where(u=>role.Users.Any(ru => u.Id == ru.UserId))
.Select( u => new UserInfo { UserName = u.UserName, Avatar = u.Avatar, UserId = u.Id } )
.ToArray()
};
return result;
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
}
}

View File

@ -0,0 +1,151 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Security.Claims;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
using Yavsc.Models;
using Yavsc.Models.Calendar;
using Yavsc.Server.Models.EMailing;
using Microsoft.AspNet.Authorization;
namespace Yavsc.Controllers
{
[Authorize("AdministratorOnly")]
public class MailingTemplateController : Controller
{
private ApplicationDbContext _context;
public MailingTemplateController(ApplicationDbContext context)
{
_context = context;
}
// GET: MailingTemplate
public async Task<IActionResult> Index()
{
var applicationDbContext = _context.MailingTemplate.Include(m => m.Manager);
return View(await applicationDbContext.ToListAsync());
}
// GET: MailingTemplate/Details/5
public async Task<IActionResult> Details(long? id)
{
if (id == null)
{
return HttpNotFound();
}
MailingTemplate mailingTemplate = await _context.MailingTemplate.SingleAsync(m => m.Id == id);
if (mailingTemplate == null)
{
return HttpNotFound();
}
return View(mailingTemplate);
}
List<SelectListItem> GetSelectFromEnum(Type enumType )
{
var list = new List<SelectListItem>();
foreach (var v in enumType.GetEnumValues())
{
list.Add(new SelectListItem { Value = v.ToString(), Text = enumType.GetEnumName(v) });
}
return list;
}
// GET: MailingTemplate/Create
public IActionResult Create()
{
ViewBag.ManagerId = new SelectList(_context.ApplicationUser, "Id", "UserName");
ViewBag.ToSend = GetSelectFromEnum(typeof(Periodicity));
return View();
}
// POST: MailingTemplate/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(MailingTemplate mailingTemplate)
{
if (ModelState.IsValid)
{
_context.MailingTemplate.Add(mailingTemplate);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
ViewBag.ManagerId = new SelectList(_context.ApplicationUser, "Id", "UserName");
ViewBag.ToSend = GetSelectFromEnum(typeof(Periodicity));
return View(mailingTemplate);
}
// GET: MailingTemplate/Edit/5
public async Task<IActionResult> Edit(long? id)
{
if (id == null)
{
return HttpNotFound();
}
MailingTemplate mailingTemplate = await _context.MailingTemplate.SingleAsync(m => m.Id == id);
if (mailingTemplate == null)
{
return HttpNotFound();
}
ViewBag.ManagerId = new SelectList(_context.ApplicationUser, "Id", "UserName");
ViewBag.ToSend = GetSelectFromEnum(typeof(Periodicity));
return View(mailingTemplate);
}
// POST: MailingTemplate/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(MailingTemplate mailingTemplate)
{
if (ModelState.IsValid)
{
_context.Update(mailingTemplate);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
ViewBag.ManagerId = new SelectList(_context.ApplicationUser, "Id", "UserName");
ViewBag.ToSend = GetSelectFromEnum(typeof(Periodicity));
return View(mailingTemplate);
}
// GET: MailingTemplate/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(long? id)
{
if (id == null)
{
return HttpNotFound();
}
MailingTemplate mailingTemplate = await _context.MailingTemplate.SingleAsync(m => m.Id == id);
if (mailingTemplate == null)
{
return HttpNotFound();
}
return View(mailingTemplate);
}
// POST: MailingTemplate/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(long id)
{
MailingTemplate mailingTemplate = await _context.MailingTemplate.SingleAsync(m => m.Id == id);
_context.MailingTemplate.Remove(mailingTemplate);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
}
}

View File

@ -0,0 +1,167 @@
using System.Threading.Tasks;
using Yavsc.ViewModels.Auth;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Mvc;
using Microsoft.Data.Entity;
using Yavsc.Models;
using Yavsc.Models.Messaging;
using Microsoft.Extensions.Localization;
using System.Collections.Generic;
using Microsoft.AspNet.Mvc.Rendering;
namespace Yavsc.Controllers
{
public class AnnouncesController : Controller
{
private ApplicationDbContext _context;
IStringLocalizer<AnnouncesController> _localizer;
IAuthorizationService _authorizationService;
public AnnouncesController(ApplicationDbContext context,
IAuthorizationService authorizationService,
IStringLocalizer<AnnouncesController> localizer)
{
_context = context;
_authorizationService = authorizationService;
_localizer = localizer;
}
// GET: Announces
public async Task<IActionResult> Index()
{
return View(await _context.Announce.ToListAsync());
}
// GET: Announces/Details/5
public async Task<IActionResult> Details(long? id)
{
if (id == null)
{
return HttpNotFound();
}
Announce announce = await _context.Announce.SingleAsync(m => m.Id == id);
if (announce == null)
{
return HttpNotFound();
}
return View(announce);
}
// GET: Announces/Create
public async Task<IActionResult> Create()
{
var model = new Announce();
await SetupView(model);
return View(model);
}
private async Task SetupView(Announce announce)
{
ViewBag.IsAdmin = User.IsInRole(Constants.AdminGroupName);
ViewBag.IsPerformer = User.IsInRole(Constants.PerformerGroupName);
ViewBag.AllowEdit = (announce!=null && announce.Id>0) ?
await _authorizationService.AuthorizeAsync(User,announce,new EditRequirement()) :
true;
List<SelectListItem> dl = new List<SelectListItem>();
var rnames = System.Enum.GetNames(typeof(Reason));
var rvalues = System.Enum.GetValues(typeof(Reason));
for (int i = 0; i<rnames.Length; i++) {
dl.Add(new SelectListItem { Text =
_localizer[rnames[i]],
Value= rvalues.GetValue(i).ToString() });
}
ViewBag.For = dl.ToArray();
}
// POST: Announces/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Announce announce)
{
await SetupView(announce);
if (ModelState.IsValid)
{
// Only allow admin to create corporate annonces
if (announce.For == Reason.Corporate && ! ViewBag.IsAdmin)
{
ModelState.AddModelError("For", _localizer["YourNotAdmin"]);
return View(announce);
}
// Only allow performers to create ServiceProposal
if (announce.For == Reason.ServiceProposal && ! ViewBag.IsAdmin)
{
ModelState.AddModelError("For", _localizer["YourNotAPerformer"]);
return View(announce);
}
_context.Announce.Add(announce);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(announce);
}
// GET: Announces/Edit/5
public async Task<IActionResult> Edit(long? id)
{
if (id == null)
{
return HttpNotFound();
}
Announce announce = await _context.Announce.SingleAsync(m => m.Id == id);
if (announce == null)
{
return HttpNotFound();
}
return View(announce);
}
// POST: Announces/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(Announce announce)
{
if (ModelState.IsValid)
{
_context.Update(announce);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(announce);
}
// GET: Announces/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(long? id)
{
if (id == null)
{
return HttpNotFound();
}
Announce announce = await _context.Announce.SingleAsync(m => m.Id == id);
if (announce == null)
{
return HttpNotFound();
}
return View(announce);
}
// POST: Announces/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(long id)
{
Announce announce = await _context.Announce.SingleAsync(m => m.Id == id);
_context.Announce.Remove(announce);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
}
}

View File

@ -0,0 +1,225 @@
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.AspNet.Authorization;
using Microsoft.Data.Entity;
using Microsoft.Extensions.OptionsModel;
using Yavsc.Models;
using Yavsc.ViewModels.Auth;
using Microsoft.AspNet.Mvc.Rendering;
using Yavsc.Models.Blog;
using Yavsc.Helpers;
// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace Yavsc.Controllers
{
public class BlogspotController : Controller
{
ILogger _logger;
private ApplicationDbContext _context;
private IAuthorizationService _authorizationService;
public BlogspotController(
ApplicationDbContext context,
UserManager<ApplicationUser> userManager,
ILoggerFactory loggerFactory,
IAuthorizationService authorizationService,
IOptions<SiteSettings> siteSettings)
{
_context = context;
_logger = loggerFactory.CreateLogger<AccountController>();
_authorizationService = authorizationService;
}
// GET: Blog
[AllowAnonymous]
public async Task<IActionResult> Index(string id, int skip=0, int maxLen=25)
{
if (!string.IsNullOrEmpty(id)) {
return await UserPosts(id);
}
return View();
}
[Route("/Title/{id?}")]
[AllowAnonymous]
public IActionResult Title(string id)
{
var uid = User.GetUserId();
ViewData["Title"] = id;
return View("Title", _context.Blogspot.Include(
b => b.Author
).Where(x => x.Title == id && (x.Visible || x.AuthorId == uid )).OrderByDescending(
x => x.DateCreated
).ToList());
}
[Route("/Blog/{userName}/{pageLen?}/{pageNum?}")]
[AllowAnonymous]
public async Task<IActionResult> UserPosts(string userName, int pageLen=10, int pageNum=0)
{
string posterId = (await _context.Users.SingleOrDefaultAsync(u=>u.UserName == userName))?.Id ?? null ;
var result = _context.UserPosts(posterId, User.Identity.Name);
return View("Index", result.OrderByDescending(p => p.DateCreated).ToList().Skip(pageLen*pageNum).Take(pageLen).GroupBy(p=> p.Title ));
}
// GET: Blog/Details/5
[AllowAnonymous]
public async Task<IActionResult> Details(long? id)
{
if (id == null)
{
return HttpNotFound();
}
BlogPost blog = _context.Blogspot
.Include(p => p.Author)
.Include(p => p.Tags)
.Include(p => p.Comments)
.Include(p => p.ACL)
.Single(m => m.Id == id);
if (blog == null)
{
return HttpNotFound();
}
if (!await _authorizationService.AuthorizeAsync(User, blog, new ViewRequirement()))
{
return new ChallengeResult();
}
foreach (var c in blog.Comments) {
c.Author = _context.Users.First(u=>u.Id==c.AuthorId);
}
ViewData["apicmtctlr"] = "/api/blogcomments";
ViewData["moderatoFlag"] = User.IsInRole(Constants.BlogModeratorGroupName);
return View(blog);
}
// GET: Blog/Create
[Authorize()]
public IActionResult Create(string title)
{
var result = new BlogPost{Title=title};
ViewData["PostTarget"]="Create";
return View("Edit",result);
}
// POST: Blog/Create
[HttpPost, Authorize, ValidateAntiForgeryToken]
public IActionResult Create(Models.Blog.BlogPost blog)
{
blog.Rate = 0;
blog.AuthorId = User.GetUserId();
blog.Id=0;
if (ModelState.IsValid)
{
_context.Blogspot.Add(blog);
_context.SaveChanges(User.GetUserId());
return RedirectToAction("Index");
}
ModelState.AddModelError("Unknown","Invalid Blog posted ...");
ViewData["PostTarget"]="Create";
return View("Edit",blog);
}
[Authorize()]
// GET: Blog/Edit/5
public async Task<IActionResult> Edit(long? id)
{
if (id == null)
{
return HttpNotFound();
}
ViewData["PostTarget"]="Edit";
BlogPost blog = _context.Blogspot.Include(x => x.Author).Include(x => x.ACL).Single(m => m.Id == id);
if (blog == null)
{
return HttpNotFound();
}
if (await _authorizationService.AuthorizeAsync(User, blog, new EditRequirement()))
{
ViewBag.ACL = _context.Circle.Where(
c=>c.OwnerId == blog.AuthorId)
.Select(
c => new SelectListItem
{
Text = c.Name,
Value = c.Id.ToString(),
Selected = blog.AuthorizeCircle(c.Id)
} 
);
return View(blog);
}
else
{
return new ChallengeResult();
}
}
// POST: Blog/Edit/5
[HttpPost]
[ValidateAntiForgeryToken,Authorize()]
public IActionResult Edit(BlogPost blog)
{
if (ModelState.IsValid)
{
var auth = _authorizationService.AuthorizeAsync(User, blog, new EditRequirement());
if (auth.Result)
{
// saves the change
_context.Update(blog);
_context.SaveChanges(User.GetUserId());
ViewData["StatusMessage"] = "Post modified";
return RedirectToAction("Index");
}
else
{
ViewData["StatusMessage"] = "Accès restreint";
return new ChallengeResult();
}
}
ViewData["PostTarget"]="Edit";
return View(blog);
}
// GET: Blog/Delete/5
[ActionName("Delete"),Authorize()]
public IActionResult Delete(long? id)
{
if (id == null)
{
return HttpNotFound();
}
BlogPost blog = _context.Blogspot.Include(
b => b.Author
).Single(m => m.Id == id);
if (blog == null)
{
return HttpNotFound();
}
return View(blog);
}
// POST: Blog/Delete/5
[HttpPost, ActionName("Delete"), Authorize()]
[ValidateAntiForgeryToken]
public IActionResult DeleteConfirmed(long id)
{
BlogPost blog = _context.Blogspot.Single(m => m.Id == id);
var auth = _authorizationService.AuthorizeAsync(User, blog, new EditRequirement());
if (auth.Result)
{
_context.Blogspot.Remove(blog);
_context.SaveChanges(User.GetUserId());
}
return RedirectToAction("Index");
}
}
}

View File

@ -0,0 +1,122 @@
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.Data.Entity;
using Yavsc.Models;
using Yavsc.Models.Relationship;
namespace Yavsc.Controllers
{
public class CircleController : Controller
{
private ApplicationDbContext _context;
public CircleController(ApplicationDbContext context)
{
_context = context;
}
// GET: Circle
public async Task<IActionResult> Index()
{
return View(await _context.Circle.ToListAsync());
}
// GET: Circle/Details/5
public async Task<IActionResult> Details(long? id)
{
if (id == null)
{
return HttpNotFound();
}
Circle circle = await _context.Circle.SingleAsync(m => m.Id == id);
if (circle == null)
{
return HttpNotFound();
}
return View(circle);
}
// GET: Circle/Create
public IActionResult Create()
{
return View();
}
// POST: Circle/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Circle circle)
{
if (ModelState.IsValid)
{
_context.Circle.Add(circle);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
return View(circle);
}
// GET: Circle/Edit/5
public async Task<IActionResult> Edit(long? id)
{
if (id == null)
{
return HttpNotFound();
}
Circle circle = await _context.Circle.SingleAsync(m => m.Id == id);
if (circle == null)
{
return HttpNotFound();
}
return View(circle);
}
// POST: Circle/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(Circle circle)
{
if (ModelState.IsValid)
{
_context.Update(circle);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
return View(circle);
}
// GET: Circle/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(long? id)
{
if (id == null)
{
return HttpNotFound();
}
Circle circle = await _context.Circle.SingleAsync(m => m.Id == id);
if (circle == null)
{
return HttpNotFound();
}
return View(circle);
}
// POST: Circle/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(long id)
{
Circle circle = await _context.Circle.SingleAsync(m => m.Id == id);
_context.Circle.Remove(circle);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
}
}

View File

@ -0,0 +1,135 @@
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
using Yavsc.Models;
using Yavsc.Models.Relationship;
namespace Yavsc.Controllers
{
public class CircleMembersController : Controller
{
private ApplicationDbContext _context;
public CircleMembersController(ApplicationDbContext context)
{
_context = context;
}
// GET: CircleMembers
public async Task<IActionResult> Index()
{
var uid = User.GetUserId();
var applicationDbContext = _context.CircleMembers.Include(c => c.Circle).Include(c => c.Member)
.Where(c=>c.Circle.OwnerId == uid);
return View(await applicationDbContext.ToListAsync());
}
// GET: CircleMembers/Details/5
public async Task<IActionResult> Details(long id)
{
var uid = User.GetUserId();
CircleMember circleMember = await _context.CircleMembers
.Include(m=>m.Circle)
.FirstOrDefaultAsync(c=>c.CircleId == id);
if (circleMember == null)
{
return HttpNotFound();
}
return View(circleMember);
}
// GET: CircleMembers/Create
public IActionResult Create()
{
var uid = User.GetUserId();
ViewBag.CircleId = new SelectList(_context.Circle.Where(c=>c.OwnerId == uid), "Id", "Name");
ViewBag.MemberId = new SelectList(_context.Users, "Id", "UserName");
return View();
}
// POST: CircleMembers/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(CircleMember circleMember)
{
var uid = User.GetUserId();
var circle = _context.Circle.SingleOrDefault(c=>c.OwnerId == uid && c.Id == circleMember.CircleId);
if (circle==null)
return new BadRequestResult();
if (ModelState.IsValid)
{
_context.CircleMembers.Add(circleMember);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
ViewData["CircleId"] = new SelectList(_context.Circle, "Id", "Name", circleMember.CircleId);
ViewData["MemberId"] = new SelectList(_context.Users, "Id", "UserName", circleMember.MemberId);
return View(circleMember);
}
// GET: CircleMembers/Edit/5
public async Task<IActionResult> Edit(long id)
{
var uid = User.GetUserId();
CircleMember circleMember = await _context.CircleMembers
.Include(m=>m.Member)
.SingleOrDefaultAsync(m => m.CircleId == id && m.MemberId == uid);
if (circleMember == null)
{
return HttpNotFound();
}
return View(circleMember);
}
// POST: CircleMembers/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(CircleMember circleMember)
{
if (ModelState.IsValid)
{
_context.Update(circleMember);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
ViewData["CircleId"] = new SelectList(_context.Circle, "Id", "Circle", circleMember.CircleId);
ViewData["MemberId"] = new SelectList(_context.Users, "Id", "Member", circleMember.MemberId);
return View(circleMember);
}
// GET: CircleMembers/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(long id)
{
var uid = User.GetUserId();
CircleMember circleMember = await _context.CircleMembers
.Include(m=>m.Circle)
.Include(m=>m.Member)
.SingleOrDefaultAsync(m => m.CircleId == id && m.MemberId == uid);
if (circleMember == null)
{
return HttpNotFound();
}
return View(circleMember);
}
// POST: CircleMembers/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(long id)
{
CircleMember circleMember = await _context.CircleMembers.SingleAsync(m => m.CircleId == id);
_context.CircleMembers.Remove(circleMember);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
}
}

View File

@ -0,0 +1,129 @@
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
using Yavsc.Models;
using Yavsc.Models.Blog;
namespace Yavsc.Controllers
{
public class CommentsController : Controller
{
private ApplicationDbContext _context;
public CommentsController(ApplicationDbContext context)
{
_context = context;
}
// GET: Comments
public async Task<IActionResult> Index()
{
var applicationDbContext = _context.Comment.Include(c => c.Post);
return View(await applicationDbContext.ToListAsync());
}
// GET: Comments/Details/5
public async Task<IActionResult> Details(long? id)
{
if (id == null)
{
return HttpNotFound();
}
Comment comment = await _context.Comment.SingleAsync(m => m.Id == id);
if (comment == null)
{
return HttpNotFound();
}
return View(comment);
}
// GET: Comments/Create
public IActionResult Create()
{
ViewData["PostId"] = new SelectList(_context.Blogspot, "Id", "Post");
return View();
}
// POST: Comments/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Comment comment)
{
comment.UserCreated = User.GetUserId();
if (ModelState.IsValid)
{
_context.Comment.Add(comment);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewData["PostId"] = new SelectList(_context.Blogspot, "Id", "Post", comment.PostId);
return View(comment);
}
// GET: Comments/Edit/5
public async Task<IActionResult> Edit(long? id)
{
if (id == null)
{
return HttpNotFound();
}
Comment comment = await _context.Comment.SingleAsync(m => m.Id == id);
if (comment == null)
{
return HttpNotFound();
}
ViewData["PostId"] = new SelectList(_context.Blogspot, "Id", "Post", comment.PostId);
return View(comment);
}
// POST: Comments/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(Comment comment)
{
if (ModelState.IsValid)
{
_context.Update(comment);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewData["PostId"] = new SelectList(_context.Blogspot, "Id", "Post", comment.PostId);
return View(comment);
}
// GET: Comments/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(long? id)
{
if (id == null)
{
return HttpNotFound();
}
Comment comment = await _context.Comment.SingleAsync(m => m.Id == id);
if (comment == null)
{
return HttpNotFound();
}
return View(comment);
}
// POST: Comments/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(long id)
{
Comment comment = await _context.Comment.SingleAsync(m => m.Id == id);
_context.Comment.Remove(comment);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
}
}

View File

@ -0,0 +1,78 @@
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.Data.Entity;
namespace Yavsc.Controllers
{
using Models;
using Models.Identity;
public class GCMDevicesController : Controller
{
private ApplicationDbContext _context;
public GCMDevicesController(ApplicationDbContext context)
{
_context = context;
}
// GET: GCMDevices
public async Task<IActionResult> Index()
{
var uid = User.GetUserId();
var applicationDbContext = _context.GCMDevices.Include(g => g.DeviceOwner).Where(d=>d.DeviceOwnerId == uid);
return View(await applicationDbContext.ToListAsync());
}
// GET: GCMDevices/Details/5
public async Task<IActionResult> Details(string id)
{
if (id == null)
{
return HttpNotFound();
}
GoogleCloudMobileDeclaration googleCloudMobileDeclaration = await _context.GCMDevices.SingleAsync(m => m.DeviceId == id);
if (googleCloudMobileDeclaration == null)
{
return HttpNotFound();
}
return View(googleCloudMobileDeclaration);
}
// GET: GCMDevices/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(string id)
{
if (id == null)
{
return HttpNotFound();
}
GoogleCloudMobileDeclaration googleCloudMobileDeclaration = await _context.GCMDevices.SingleAsync(m => m.DeviceId == id);
if (googleCloudMobileDeclaration == null)
{
return HttpNotFound();
}
return View(googleCloudMobileDeclaration);
}
// POST: GCMDevices/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(string id)
{
GoogleCloudMobileDeclaration googleCloudMobileDeclaration = await _context.GCMDevices.SingleAsync(m => m.DeviceId == id);
_context.GCMDevices.Remove(googleCloudMobileDeclaration);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
}
}

View File

@ -0,0 +1,83 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net.WebSockets;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.Extensions.Logging;
using Yavsc.ViewModels.Streaming;
namespace Yavsc.Controllers.Communicating
{
public class LiveController : Controller
{
ILogger _logger;
public static ConcurrentDictionary<string, LiveCastMeta> Casters = new ConcurrentDictionary<string, LiveCastMeta>();
public LiveController(LoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<LiveController>();
}
public async Task<IActionResult> Cast()
{
var uname = User.GetUserName();
// ensure this request is for a websocket
if (!HttpContext.WebSockets.IsWebSocketRequest) return new BadRequestResult();
// ensure uniqueness of casting stream from this user
var existent = Casters[uname];
if (existent != null) return new BadRequestObjectResult("not supported, you already casting, there's support for one live streaming only");
var meta = new LiveCastMeta { Socket = await HttpContext.WebSockets.AcceptWebSocketAsync() };
using (meta.Socket)
{
if (meta.Socket != null && meta.Socket.State == WebSocketState.Open)
{
Casters[uname] = meta;
// TODO: Handle the socket here.
// Find receivers: others in the chat room
// send them the flow
byte[] buffer = new byte[1024];
WebSocketReceiveResult received = await meta.Socket.ReceiveAsync
(new ArraySegment<byte>(buffer), CancellationToken.None);
// FIXME do we really need to close those one in invalid state ?
Stack<string> ToClose = new Stack<string>();
while (received.MessageType != WebSocketMessageType.Close)
{
_logger.LogInformation($"Echoing {received.Count} bytes received in a {received.MessageType} message; Fin={received.EndOfMessage}");
// Echo anything we receive
// and send to all listner found
foreach (var cliItem in meta.Listeners)
{
var listenningSocket = cliItem.Value;
if (listenningSocket.State == WebSocketState.Open)
await listenningSocket.SendAsync(new ArraySegment<byte>
(buffer, 0, received.Count), received.MessageType, received.EndOfMessage, CancellationToken.None);
else ToClose.Push(cliItem.Key);
}
received = await meta.Socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
string no;
do
{
no = ToClose.Pop();
WebSocket listenningSocket;
if (meta.Listeners.TryRemove(no, out listenningSocket))
await listenningSocket.CloseAsync(WebSocketCloseStatus.EndpointUnavailable, "State != WebSocketState.Open", CancellationToken.None);
} while (no != null);
}
await meta.Socket.CloseAsync(received.CloseStatus.Value, received.CloseStatusDescription, CancellationToken.None);
Casters[uname] = null;
}
else _logger.LogInformation($"failed (meta.Socket != null && meta.Socket.State == WebSocketState.Open)");
}
return Ok();
}
}
}

View File

@ -0,0 +1,121 @@
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.Data.Entity;
using Yavsc.Models;
using Yavsc.Models.Messaging;
namespace Yavsc.Controllers
{
public class NotificationsController : Controller
{
private ApplicationDbContext _context;
public NotificationsController(ApplicationDbContext context)
{
_context = context;
}
// GET: Notifications
public async Task<IActionResult> Index()
{
return View(await _context.Notification.ToListAsync());
}
// GET: Notifications/Details/5
public async Task<IActionResult> Details(long? id)
{
if (id == null)
{
return HttpNotFound();
}
Notification notification = await _context.Notification.SingleAsync(m => m.Id == id);
if (notification == null)
{
return HttpNotFound();
}
return View(notification);
}
// GET: Notifications/Create
public IActionResult Create()
{
return View();
}
// POST: Notifications/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Notification notification)
{
if (ModelState.IsValid)
{
_context.Notification.Add(notification);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
return View(notification);
}
// GET: Notifications/Edit/5
public async Task<IActionResult> Edit(long? id)
{
if (id == null)
{
return HttpNotFound();
}
Notification notification = await _context.Notification.SingleAsync(m => m.Id == id);
if (notification == null)
{
return HttpNotFound();
}
return View(notification);
}
// POST: Notifications/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(Notification notification)
{
if (ModelState.IsValid)
{
_context.Update(notification);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
return View(notification);
}
// GET: Notifications/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(long? id)
{
if (id == null)
{
return HttpNotFound();
}
Notification notification = await _context.Notification.SingleAsync(m => m.Id == id);
if (notification == null)
{
return HttpNotFound();
}
return View(notification);
}
// POST: Notifications/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(long id)
{
Notification notification = await _context.Notification.SingleAsync(m => m.Id == id);
_context.Notification.Remove(notification);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
}
}

View File

@ -0,0 +1,213 @@
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
namespace Yavsc.Controllers
{
using System.Security.Claims;
using Models;
using Models.Workflow;
[Authorize("AdministratorOnly")]
public class ActivityController : Controller
{
private ApplicationDbContext _context;
IStringLocalizer<Yavsc.Resources.YavscLocalisation> SR;
ILogger logger;
public ActivityController(ApplicationDbContext context,
IStringLocalizer<Yavsc.Resources.YavscLocalisation> SR,
ILoggerFactory loggerFactory)
{
_context = context;
this.SR = SR;
logger=loggerFactory.CreateLogger<ActivityController>();
}
// GET: Activity
public IActionResult Index()
{
SetSettingClasseInfo();
return View(_context.Activities.Include(a=>a.Parent).ToList());
}
private void SetSettingClasseInfo(string currentCode = null)
{
var items = Startup.ProfileTypes.Select(
pt => new SelectListItem
{
Text = SR[pt.FullName],
Value = pt.FullName,
Selected = currentCode == pt.FullName
}).ToList();
items.Add(new SelectListItem { Text = SR[Constants.NoneCode], Value = Constants.NoneCode, Selected = currentCode == null});
ViewBag.SettingsClassName = items;
}
private List<SelectListItem> GetEligibleParent(string code)
{
// eligibles are those
// who are not in descendants
//
var acts = _context.Activities.Where(
a => a.Code != code
).Select(a => new SelectListItem
{
Text = a.Name,
Value = a.Code
}).ToList();
var nullItem = new SelectListItem { Text = SR[Constants.NoneCode], Value = Constants.NoneCode };
acts.Add(nullItem);
if (code == null) return acts;
var existing = _context.Activities.Include(a => a.Children).FirstOrDefault(a => a.Code == code);
if (existing == null) return acts;
var pi = acts.FirstOrDefault(i => i.Value == existing.ParentCode);
if (pi!=null) pi.Selected = true;
else nullItem.Selected = true;
RecFilterChild(acts, existing);
return acts;
}
/// <summary>
/// Filters a activity selection list
/// in order to exculde any descendant
/// from the eligible list at the <c>Parent</c> property.
/// WARN! results in a infinite loop when
/// data is corrupted and there is a circularity
/// in the activity hierarchy graph (Parent/Children)
/// </summary>
/// <param name="list"></param>
/// <param name="activity"></param>
private static void RecFilterChild(List<SelectListItem> list, Activity activity)
{
if (activity == null) return;
if (activity.Children == null) return;
if (list.Count == 0) return;
foreach (var child in activity.Children)
{
RecFilterChild(list, child);
var rem = list.FirstOrDefault(i => i.Value == child.Code);
if (rem != null) list.Remove(rem);
}
}
// GET: Activity/Details/5
public IActionResult Details(string id)
{
if (id == null)
{
return HttpNotFound();
}
Activity activity = _context.Activities.Single(m => m.Code == id);
if (activity == null)
{
return HttpNotFound();
}
return View(activity);
}
// GET: Activity/Create
public IActionResult Create()
{
SetSettingClasseInfo();
ViewBag.ParentCode = GetEligibleParent(null);
return View();
}
// POST: Activity/Create
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Activity activity)
{
if (activity.ParentCode==Constants.NoneCode)
activity.ParentCode=null;
if (activity.SettingsClassName==Constants.NoneCode)
activity.SettingsClassName=null;
if (ModelState.IsValid)
{
_context.Activities.Add(activity);
_context.SaveChanges(User.GetUserId());
return RedirectToAction("Index");
}
SetSettingClasseInfo();
return View(activity);
}
// GET: Activity/Edit/5
public IActionResult Edit(string id)
{
if (id == null)
{
return HttpNotFound();
}
Activity activity = _context.Activities.Single(m => m.Code == id);
if (activity == null)
{
return HttpNotFound();
}
ViewBag.ParentCode = GetEligibleParent(id);
SetSettingClasseInfo();
return View(activity);
}
// POST: Activity/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Edit(Activity activity)
{
if (activity.ParentCode==Constants.NoneCode)
activity.ParentCode=null;
if (activity.SettingsClassName==Constants.NoneCode)
activity.SettingsClassName=null;
if (ModelState.IsValid)
{
_context.Update(activity);
_context.SaveChanges(User.GetUserId());
return RedirectToAction("Index");
}
return View(activity);
}
// GET: Activity/Delete/5
[ActionName("Delete")]
public IActionResult Delete(string id)
{
if (id == null)
{
return HttpNotFound();
}
Activity activity = _context.Activities.Single(m => m.Code == id);
if (activity == null)
{
return HttpNotFound();
}
return View(activity);
}
// POST: Activity/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public IActionResult DeleteConfirmed(string id)
{
Activity activity = _context.Activities.Single(m => m.Code == id);
_context.Activities.Remove(activity);
_context.SaveChanges(User.GetUserId());
return RedirectToAction("Index");
}
}
}

View File

@ -0,0 +1,139 @@
using System;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
using System.Collections.Generic;
using Yavsc.Models;
using Yavsc.Models.Auth;
using System.Security.Claims;
namespace Yavsc.Controllers
{
public class ClientController : Controller
{
private ApplicationDbContext _context;
public ClientController(ApplicationDbContext context)
{
_context = context;
}
// GET: Client
public async Task<IActionResult> Index()
{
return View(await _context.Applications.ToListAsync());
}
// GET: Client/Details/5
public async Task<IActionResult> Details(string id)
{
if (id == null)
{
return HttpNotFound();
}
Client client = await _context.Applications.SingleAsync(m => m.Id == id);
if (client == null)
{
return HttpNotFound();
}
return View(client);
}
// GET: Client/Create
public IActionResult Create()
{
SetAppTypesInputValues();
return View();
}
// POST: Client/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Client client)
{
if (ModelState.IsValid)
{
client.Id = Guid.NewGuid().ToString();
_context.Applications.Add(client);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
SetAppTypesInputValues();
return View(client);
}
private void SetAppTypesInputValues()
{
IEnumerable<SelectListItem> types = new SelectListItem[] {
new SelectListItem {
Text = ApplicationTypes.JavaScript.ToString(),
Value = ((int) ApplicationTypes.JavaScript).ToString() },
new SelectListItem {
Text = ApplicationTypes.NativeConfidential.ToString(),
Value = ((int) ApplicationTypes.NativeConfidential).ToString()
}
};
ViewData["Type"] = types;
}
// GET: Client/Edit/5
public async Task<IActionResult> Edit(string id)
{
if (id == null)
{
return HttpNotFound();
}
Client client = await _context.Applications.SingleAsync(m => m.Id == id);
if (client == null)
{
return HttpNotFound();
}
SetAppTypesInputValues();
return View(client);
}
// POST: Client/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(Client client)
{
if (ModelState.IsValid)
{
_context.Update(client);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
return View(client);
}
// GET: Client/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(string id)
{
if (id == null)
{
return HttpNotFound();
}
Client client = await _context.Applications.SingleAsync(m => m.Id == id);
if (client == null)
{
return HttpNotFound();
}
return View(client);
}
// POST: Client/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(string id)
{
Client client = await _context.Applications.SingleAsync(m => m.Id == id);
_context.Applications.Remove(client);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
}
}

View File

@ -0,0 +1,132 @@
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
using Yavsc.Models;
using Yavsc.Models.Workflow;
namespace Yavsc.Controllers
{
public class CoWorkingController : Controller
{
private ApplicationDbContext _context;
public CoWorkingController(ApplicationDbContext context)
{
_context = context;
}
// GET: CoWorking
public async Task<IActionResult> Index()
{
var applicationDbContext = _context.WorkflowProviders.Include(c => c.Performer).Include(c => c.WorkingFor);
return View(await applicationDbContext.ToListAsync());
}
// GET: CoWorking/Details/5
public async Task<IActionResult> Details(long? id)
{
if (id == null)
{
return HttpNotFound();
}
CoWorking coWorking = await _context.WorkflowProviders.SingleAsync(m => m.Id == id);
if (coWorking == null)
{
return HttpNotFound();
}
return View(coWorking);
}
// GET: CoWorking/Create
public IActionResult Create()
{
ViewBag.PerformerId = _context.Performers.Select( p=> new SelectListItem { Value = p.PerformerId, Text = p.Performer.UserName});
ViewBag.WorkingForId = new SelectList(_context.Users, "Id", "UserName");
return View();
}
// POST: CoWorking/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(CoWorking coWorking)
{
if (ModelState.IsValid)
{
_context.WorkflowProviders.Add(coWorking);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
ViewData["PerformerId"] = new SelectList(_context.Performers, "PerformerId", "Performer", coWorking.PerformerId);
ViewData["WorkingForId"] = new SelectList(_context.Users, "Id", "WorkingFor", coWorking.WorkingForId);
return View(coWorking);
}
// GET: CoWorking/Edit/5
public async Task<IActionResult> Edit(long? id)
{
if (id == null)
{
return HttpNotFound();
}
CoWorking coWorking = await _context.WorkflowProviders.SingleAsync(m => m.Id == id);
if (coWorking == null)
{
return HttpNotFound();
}
ViewData["PerformerId"] = new SelectList(_context.Performers, "PerformerId", "Performer", coWorking.PerformerId);
ViewData["WorkingForId"] = new SelectList(_context.Users, "Id", "WorkingFor", coWorking.WorkingForId);
return View(coWorking);
}
// POST: CoWorking/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(CoWorking coWorking)
{
if (ModelState.IsValid)
{
_context.Update(coWorking);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
ViewData["PerformerId"] = new SelectList(_context.Performers, "PerformerId", "Performer", coWorking.PerformerId);
ViewData["WorkingForId"] = new SelectList(_context.Users, "Id", "WorkingFor", coWorking.WorkingForId);
return View(coWorking);
}
// GET: CoWorking/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(long? id)
{
if (id == null)
{
return HttpNotFound();
}
CoWorking coWorking = await _context.WorkflowProviders.SingleAsync(m => m.Id == id);
if (coWorking == null)
{
return HttpNotFound();
}
return View(coWorking);
}
// POST: CoWorking/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(long id)
{
CoWorking coWorking = await _context.WorkflowProviders.SingleAsync(m => m.Id == id);
_context.WorkflowProviders.Remove(coWorking);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
}
}

View File

@ -0,0 +1,277 @@
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.Data.Entity;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.OptionsModel;
namespace Yavsc.Controllers
{
using Helpers;
using Models;
using Models.Google.Messaging;
using Models.Relationship;
using Models.Workflow;
using Services;
public class CommandController : Controller
{
protected UserManager<ApplicationUser> _userManager;
protected ApplicationDbContext _context;
protected GoogleAuthSettings _googleSettings;
protected IGoogleCloudMessageSender _GCMSender;
protected IEmailSender _emailSender;
protected IStringLocalizer _localizer;
protected SiteSettings _siteSettings;
protected SmtpSettings _smtpSettings;
protected ICalendarManager _calendarManager;
protected readonly ILogger _logger;
public CommandController(ApplicationDbContext context, IOptions<GoogleAuthSettings> googleSettings,
IGoogleCloudMessageSender GCMSender,
UserManager<ApplicationUser> userManager,
ICalendarManager calendarManager,
IStringLocalizer<Yavsc.Resources.YavscLocalisation> localizer,
IEmailSender emailSender,
IOptions<SmtpSettings> smtpSettings,
IOptions<SiteSettings> siteSettings,
ILoggerFactory loggerFactory)
{
_context = context;
_GCMSender = GCMSender;
_emailSender = emailSender;
_googleSettings = googleSettings.Value;
_userManager = userManager;
_smtpSettings = smtpSettings.Value;
_siteSettings = siteSettings.Value;
_calendarManager = calendarManager;
_localizer = localizer;
_logger = loggerFactory.CreateLogger<CommandController>();
}
// GET: Command
[Authorize]
public virtual async Task<IActionResult> Index()
{
var uid = User.GetUserId();
return View(await _context.RdvQueries
.Include(x => x.Client)
.Include(x => x.PerformerProfile)
.Include(x => x.PerformerProfile.Performer)
.Include(x => x.Location)
.Where(x=> x.ClientId == uid || x.PerformerId == uid)
.ToListAsync());
}
// GET: Command/Details/5
public virtual async Task<IActionResult> Details(long id)
{
RdvQuery command = await _context.RdvQueries
.Include(x => x.Location)
.Include(x => x.PerformerProfile)
.SingleAsync(m => m.Id == id);
if (command == null)
{
return HttpNotFound();
}
return View(command);
}
/// <summary>
/// Gives a view on
/// Creating a command for a specified performer
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet]
public IActionResult Create(string proId, string activityCode, string billingCode)
{
if (string.IsNullOrWhiteSpace(proId))
throw new InvalidOperationException(
"This method needs a performer id (from parameter proId)"
);
if (string.IsNullOrWhiteSpace(activityCode))
throw new InvalidOperationException(
"This method needs an activity code"
);
var pro = _context.Performers.Include(
x => x.Performer).FirstOrDefault(
x => x.PerformerId == proId
);
if (pro == null)
return HttpNotFound();
ViewBag.Activity = _context.Activities.FirstOrDefault(a=>a.Code == activityCode);
ViewBag.GoogleSettings = _googleSettings;
var userid = User.GetUserId();
var user = _userManager.FindByIdAsync(userid).Result;
return View("Create",new RdvQuery(activityCode,new Location(),DateTime.Now.AddHours(4))
{
PerformerProfile = pro,
PerformerId = pro.PerformerId,
ClientId = userid,
Client = user,
ActivityCode = activityCode
});
}
// POST: Command/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(RdvQuery command)
{
// TODO validate BillingCode value
var uid = User.GetUserId();
var prid = command.PerformerId;
if (string.IsNullOrWhiteSpace(uid)
|| string.IsNullOrWhiteSpace(prid))
throw new InvalidOperationException(
"This method needs a PerformerId"
);
var pro = _context.Performers.Include(
u => u.Performer
).Include(u => u.Performer.Devices)
.FirstOrDefault(
x => x.PerformerId == command.PerformerId
);
var user = await _userManager.FindByIdAsync(uid);
command.Client = user;
command.ClientId = uid;
command.PerformerProfile = pro;
// FIXME Why!!
// ModelState.ClearValidationState("PerformerProfile.Avatar");
// ModelState.ClearValidationState("Client.Avatar");
// ModelState.ClearValidationState("ClientId");
ModelState.MarkFieldSkipped("ClientId");
if (ModelState.IsValid)
{
var existingLocation = _context.Locations.FirstOrDefault( x=>x.Address == command.Location.Address
&& x.Longitude == command.Location.Longitude && x.Latitude == command.Location.Latitude );
if (existingLocation!=null) {
command.Location=existingLocation;
}
else _context.Attach<Location>(command.Location);
_context.RdvQueries.Add(command, GraphBehavior.IncludeDependents);
_context.SaveChanges(User.GetUserId());
var yaev = command.CreateEvent(_localizer, "NewCommand");
MessageWithPayloadResponse grep = null;
if (pro.AcceptNotifications
&& pro.AcceptPublicContact)
{
try {
if (pro.Performer.Devices.Count > 0) {
var regids = command.PerformerProfile.Performer
.Devices.Select(d => d.GCMRegistrationId);
grep = await _GCMSender.NotifyBookQueryAsync(regids,yaev);
}
_logger.LogError("sending GCM");
// TODO setup a profile choice to allow notifications
// both on mailbox and mobile
// if (grep==null || grep.success<=0 || grep.failure>0)
ViewBag.GooglePayload=grep;
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
}
try {
ViewBag.EmailSent = await _emailSender.SendEmailAsync(
command.PerformerProfile.Performer.UserName,
command.PerformerProfile.Performer.Email,
$"{command.Client.UserName} (un client) vous demande un rendez-vous",
$"{yaev.CreateBody()}\r\n-- \r\n{yaev.Previsional}\r\n{yaev.EventDate}\r\n"
);
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
}
}
ViewBag.Activity = _context.Activities.FirstOrDefault(a=>a.Code == command.ActivityCode);
ViewBag.GoogleSettings = _googleSettings;
return View("CommandConfirmation",command);
}
ViewBag.Activity = _context.Activities.FirstOrDefault(a=>a.Code == command.ActivityCode);
ViewBag.GoogleSettings = _googleSettings;
return View(command);
}
// GET: Command/Edit/5
public IActionResult Edit(long? id)
{
if (id == null)
{
return HttpNotFound();
}
RdvQuery command = _context.RdvQueries.Single(m => m.Id == id);
if (command == null)
{
return HttpNotFound();
}
return View(command);
}
// POST: Command/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Edit(RdvQuery command)
{
if (ModelState.IsValid)
{
_context.Update(command);
_context.SaveChanges(User.GetUserId());
return RedirectToAction("Index");
}
return View(command);
}
// GET: Command/Delete/5
[ActionName("Delete")]
public IActionResult Delete(long? id)
{
if (id == null)
{
return HttpNotFound();
}
RdvQuery command = _context.RdvQueries.Single(m => m.Id == id);
if (command == null)
{
return HttpNotFound();
}
return View(command);
}
// POST: Command/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public IActionResult DeleteConfirmed(long id)
{
RdvQuery command = _context.RdvQueries.Single(m => m.Id == id);
_context.RdvQueries.Remove(command);
_context.SaveChanges(User.GetUserId());
return RedirectToAction("Index");
}
public IActionResult CGV()
{
return View();
}
}
}

View File

@ -0,0 +1,131 @@
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
using Yavsc.Models;
using Yavsc.Models.Workflow;
namespace Yavsc.Controllers
{
public class CommandFormsController : Controller
{
private ApplicationDbContext _context;
public CommandFormsController(ApplicationDbContext context)
{
_context = context;
}
// GET: CommandForms
public async Task<IActionResult> Index()
{
var applicationDbContext = _context.CommandForm.Include(c => c.Context);
return View(await applicationDbContext.ToListAsync());
}
// GET: CommandForms/Details/5
public async Task<IActionResult> Details(long? id)
{
if (id == null)
{
return HttpNotFound();
}
CommandForm commandForm = await _context.CommandForm.SingleAsync(m => m.Id == id);
if (commandForm == null)
{
return HttpNotFound();
}
return View(commandForm);
}
// GET: CommandForms/Create
public IActionResult Create()
{
SetViewBag();
return View();
}
private void SetViewBag(CommandForm commandForm=null) {
ViewBag.ActivityCode = new SelectList(_context.Activities, "Code", "Name", commandForm?.ActivityCode);
ViewBag.ActionName = Startup.Forms.Select( c => new SelectListItem { Value = c, Text = c, Selected = (commandForm?.ActionName == c) } );
}
// POST: CommandForms/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(CommandForm commandForm)
{
if (ModelState.IsValid)
{
_context.CommandForm.Add(commandForm);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
SetViewBag(commandForm);
return View(commandForm);
}
// GET: CommandForms/Edit/5
public async Task<IActionResult> Edit(long? id)
{
if (id == null)
{
return HttpNotFound();
}
CommandForm commandForm = await _context.CommandForm.SingleAsync(m => m.Id == id);
if (commandForm == null)
{
return HttpNotFound();
}
SetViewBag(commandForm);
return View(commandForm);
}
// POST: CommandForms/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(CommandForm commandForm)
{
if (ModelState.IsValid)
{
_context.Update(commandForm);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
SetViewBag(commandForm);
return View(commandForm);
}
// GET: CommandForms/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(long? id)
{
if (id == null)
{
return HttpNotFound();
}
CommandForm commandForm = await _context.CommandForm.SingleAsync(m => m.Id == id);
if (commandForm == null)
{
return HttpNotFound();
}
return View(commandForm);
}
// POST: CommandForms/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(long id)
{
CommandForm commandForm = await _context.CommandForm.SingleAsync(m => m.Id == id);
_context.CommandForm.Remove(commandForm);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
}
}

View File

@ -0,0 +1,120 @@
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.Data.Entity;
using Yavsc.Models;
using Yavsc.Models.Musical.Profiles;
namespace Yavsc.Controllers
{
public class DjSettingsController : Controller
{
private ApplicationDbContext _context;
public DjSettingsController(ApplicationDbContext context)
{
_context = context;
}
// GET: DjSettings
public async Task<IActionResult> Index()
{
return View(await _context.DjSettings.ToListAsync());
}
// GET: DjSettings/Details/5
public async Task<IActionResult> Details(string id)
{
if (id == null)
{
return HttpNotFound();
}
DjSettings djSettings = await _context.DjSettings.SingleAsync(m => m.UserId == id);
if (djSettings == null)
{
return HttpNotFound();
}
return View(djSettings);
}
// GET: DjSettings/Create
public IActionResult Create()
{
return View();
}
// POST: DjSettings/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(DjSettings djSettings)
{
if (ModelState.IsValid)
{
_context.DjSettings.Add(djSettings);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(djSettings);
}
// GET: DjSettings/Edit/5
public async Task<IActionResult> Edit(string id)
{
if (id == null)
{
return HttpNotFound();
}
DjSettings djSettings = await _context.DjSettings.SingleAsync(m => m.UserId == id);
if (djSettings == null)
{
return HttpNotFound();
}
return View(djSettings);
}
// POST: DjSettings/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(DjSettings djSettings)
{
if (ModelState.IsValid)
{
_context.Update(djSettings);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(djSettings);
}
// GET: DjSettings/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(string id)
{
if (id == null)
{
return HttpNotFound();
}
DjSettings djSettings = await _context.DjSettings.SingleAsync(m => m.UserId == id);
if (djSettings == null)
{
return HttpNotFound();
}
return View(djSettings);
}
// POST: DjSettings/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(string id)
{
DjSettings djSettings = await _context.DjSettings.SingleAsync(m => m.UserId == id);
_context.DjSettings.Remove(djSettings);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
}
}

View File

@ -0,0 +1,187 @@
using System.Linq;
using System.Security.Claims;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
namespace Yavsc.Controllers
{
using Microsoft.Extensions.Logging;
using Models;
using Models.Workflow;
using Yavsc.ViewModels.Workflow;
using Yavsc.Services;
using System.Threading.Tasks;
[Authorize]
public class DoController : Controller
{
private ApplicationDbContext dbContext;
ILogger logger;
IBillingService billing;
public DoController(
ApplicationDbContext context,
IBillingService billing,
ILogger<DoController> logger)
{
dbContext = context;
this.billing = billing;
this.logger = logger;
}
// GET: /Do/Index
[HttpGet]
public IActionResult Index(string id)
{
if (id == null)
id = User.GetUserId();
var userActivities = dbContext.UserActivities.Include(u => u.Does)
.Include(u => u.User).Where(u=> u.UserId == id)
.OrderByDescending(u => u.Weight);
return View(userActivities.ToList());
}
// GET: Do/Details/5
public async Task<IActionResult> Details(string id, string activityCode)
{
if (id == null || activityCode == null)
{
return HttpNotFound();
}
UserActivity userActivity = dbContext.UserActivities.Include(m=>m.Does)
.Include(m=>m.User).Single(m => m.DoesCode == activityCode && m.UserId == id);
if (userActivity == null)
{
return HttpNotFound();
}
bool hasConfigurableSettings = (userActivity.Does.SettingsClassName != null);
var settings = await billing.GetPerformerSettingsAsync(activityCode,id);
ViewBag.ProfileType = Startup.ProfileTypes.Single(t=>t.FullName==userActivity.Does.SettingsClassName);
var gift = new UserActivityViewModel {
Declaration = userActivity,
Settings = settings,
NeedsSettings = hasConfigurableSettings
};
return View (gift);
}
// GET: Do/Create
[ActionName("Create"),Authorize]
public IActionResult Create(string userId)
{
if (userId==null)
userId = User.GetUserId();
var model = new UserActivity { UserId = userId };
ViewBag.DoesCode = new SelectList(dbContext.Activities, "Code", "Name");
//ViewData["UserId"] = userId;
ViewBag.UserId = new SelectList(dbContext.Performers.Include(p=>p.Performer), "PerformerId", "Performer", userId);
return View(model);
}
// POST: Do/Create
[HttpPost(),ActionName("Create"),Authorize]
[ValidateAntiForgeryToken]
public IActionResult Create(UserActivity userActivity)
{
var uid = User.GetUserId();
if (!User.IsInRole("Administrator"))
if (uid != userActivity.UserId)
ModelState.AddModelError("User","You're not admin.");
if (userActivity.UserId == null) userActivity.UserId = uid;
if (ModelState.IsValid)
{
dbContext.UserActivities.Add(userActivity);
dbContext.SaveChanges(User.GetUserId());
return RedirectToAction("Index");
}
ViewBag.DoesCode = new SelectList(dbContext.Activities, "Code", "Name", userActivity.DoesCode);
ViewBag.UserId = new SelectList(dbContext.Performers.Include(p=>p.Performer), "PerformerId", "User", userActivity.UserId);
return View(userActivity);
}
// GET: Do/Edit/5
[Authorize]
public IActionResult Edit(string id, string activityCode)
{
if (id == null)
{
return HttpNotFound();
}
UserActivity userActivity = dbContext.UserActivities.Include(
u=>u.Does
).Include(
u=>u.User
).Single(m => m.DoesCode == activityCode && m.UserId == id);
if (userActivity == null)
{
return HttpNotFound();
}
ViewData["DoesCode"] = new SelectList(dbContext.Activities, "Code", "Does", userActivity.DoesCode);
ViewData["UserId"] = new SelectList(dbContext.Performers, "PerformerId", "User", userActivity.UserId);
return View(userActivity);
}
// POST: Do/Edit/5
[HttpPost,Authorize]
[ValidateAntiForgeryToken]
public IActionResult Edit(UserActivity userActivity)
{
if (!User.IsInRole("Administrator"))
if (User.GetUserId() != userActivity.UserId)
ModelState.AddModelError("User","You're not admin.");
if (ModelState.IsValid)
{
dbContext.Update(userActivity);
dbContext.SaveChanges(User.GetUserId());
return RedirectToAction("Index");
}
ViewData["DoesCode"] = new SelectList(dbContext.Activities, "Code", "Does", userActivity.DoesCode);
ViewData["UserId"] = new SelectList(dbContext.Performers, "PerformerId", "User", userActivity.UserId);
return View(userActivity);
}
// GET: Do/Delete/5
[ActionName("Delete"),Authorize]
public IActionResult Delete(string id, string activityCode)
{
if (id == null)
{
return HttpNotFound();
}
UserActivity userActivity = dbContext.UserActivities.Single(m => m.UserId == id && m.DoesCode == activityCode);
if (userActivity == null)
{
return HttpNotFound();
}
if (!User.IsInRole("Administrator"))
if (User.GetUserId() != userActivity.UserId)
ModelState.AddModelError("User","You're not admin.");
return View(userActivity);
}
// POST: Do/Delete/5
[HttpPost, ActionName("Delete"),Authorize]
[ValidateAntiForgeryToken]
public IActionResult DeleteConfirmed(UserActivity userActivity)
{
if (!ModelState.IsValid)
return new BadRequestObjectResult(ModelState);
if (!User.IsInRole("Administrator"))
if (User.GetUserId() != userActivity.UserId) {
ModelState.AddModelError("User","You're not admin.");
return RedirectToAction("Index");
}
dbContext.UserActivities.Remove(userActivity);
dbContext.SaveChanges(User.GetUserId());
return RedirectToAction("Index");
}
}
}

View File

@ -0,0 +1,219 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mime;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc;
using Microsoft.Data.Entity;
using Microsoft.Extensions.OptionsModel;
namespace Yavsc.Controllers
{
using Models;
using Models.Billing;
using Models.Workflow;
using ViewModels.Auth;
using Yavsc.Abstract.FileSystem;
[Authorize]
public class EstimateController : Controller
{
private ApplicationDbContext _context;
private SiteSettings _site;
IAuthorizationService authorizationService;
public EstimateController(ApplicationDbContext context, IAuthorizationService authorizationService, IOptions<SiteSettings> siteSettings)
{
_context = context;
_site = siteSettings.Value;
this.authorizationService = authorizationService;
}
// GET: Estimate
public IActionResult Index()
{
var uid = User.GetUserId();
return View(_context.Estimates.Include(e=>e.Query)
.Include(e=>e.Query.PerformerProfile)
.Include(e=>e.Query.PerformerProfile.Performer)
.Where(
e=>e.OwnerId == uid || e.ClientId == uid
).OrderByDescending(e=>e.ProviderValidationDate)
.ToList());
}
// GET: Estimate/Details/5
public async Task<IActionResult> Details(long? id)
{
var uid = User.GetUserId();
if (id == null)
{
return HttpNotFound();
}
Estimate estimate = _context.Estimates
.Include(e => e.Query)
.Include(e => e.Query.PerformerProfile)
.Include(e => e.Query.PerformerProfile.Performer)
.Include(e=> e.Bill)
.Where(
e=>e.OwnerId == uid || e.ClientId == uid
)
.Single(m => m.Id == id);
if (estimate == null)
{
return HttpNotFound();
}
if (!await authorizationService.AuthorizeAsync(User, estimate, new ViewRequirement()))
{
return new ChallengeResult();
}
return View(estimate);
}
// GET: Estimate/Create
[Authorize]
public IActionResult Create()
{
var uid = User.GetUserId();
IQueryable<RdvQuery> queries = _context.RdvQueries.Include(q=>q.Location).Where(bq=>bq.PerformerId == uid);
//.Select(bq=>new SelectListItem{ Text = bq.Client.UserName, Value = bq.Client.Id });
ViewBag.Clients = queries.Select(q=>q.Client).Distinct();
ViewBag.Queries = queries;
return View();
}
// POST: Estimate/Create
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Estimate estimate,
ICollection<IFormFile> newGraphics,
ICollection<IFormFile> newFiles
)
{
estimate.OwnerId = User.GetUserId();
if (ModelState.IsValid)
{
_context.Estimates
.Add(estimate);
_context.SaveChanges(User.GetUserId());
var query = _context.RdvQueries.FirstOrDefault(
q=>q.Id == estimate.CommandId
);
var perfomerProfile = _context.Performers
.Include(
perpr => perpr.Performer).FirstOrDefault(
x=>x.PerformerId == query.PerformerId
);
var command = _context.RdvQueries.FirstOrDefault(
cmd => cmd.Id == estimate.CommandId
);
var billsdir = Path.Combine(
_site.Bills,
perfomerProfile.Performer.UserName
);
foreach (var gr in newGraphics)
{
ContentDisposition contentDisposition = new ContentDisposition(gr.ContentDisposition);
gr.SaveAs(
Path.Combine(
Path.Combine(billsdir, estimate.Id.ToString()),
contentDisposition.FileName));
}
foreach (var formFile in newFiles)
{
ContentDisposition contentDisposition = new ContentDisposition(formFile.ContentDisposition);
formFile.SaveAs(
Path.Combine(
Path.Combine(billsdir, estimate.Id.ToString()),
contentDisposition.FileName));
}
return RedirectToAction("Index");
}
return View(estimate);
}
private void Save(ICollection<IFormFile> newGraphics,
ICollection<IFormFile> newFiles) {
}
// GET: Estimate/Edit/5
public IActionResult Edit(long? id)
{
if (id == null)
{
return HttpNotFound();
}
var uid = User.GetUserId();
Estimate estimate = _context.Estimates
.Where(e=>e.OwnerId==uid||e.ClientId==uid).Single(m => m.Id == id);
if (estimate == null)
{
return HttpNotFound();
}
ViewBag.Files = User.GetUserFiles(null);
return View(estimate);
}
// POST: Estimate/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Edit(Estimate estimate)
{
var uid = User.GetUserId();
if (estimate.OwnerId!=uid&&estimate.ClientId!=uid
) return new HttpNotFoundResult();
if (ModelState.IsValid)
{
_context.Update(estimate);
_context.SaveChanges(User.GetUserId());
return RedirectToAction("Index");
}
return View(estimate);
}
// GET: Estimate/Delete/5
[ActionName("Delete")]
public IActionResult Delete(long? id)
{
if (id == null)
{
return HttpNotFound();
}
var uid = User.GetUserId();
Estimate estimate = _context.Estimates
.Where(e=>e.OwnerId==uid||e.ClientId==uid) .Single(m => m.Id == id);
if (estimate == null)
{
return HttpNotFound();
}
return View(estimate);
}
// POST: Estimate/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public IActionResult DeleteConfirmed(long id)
{
Estimate estimate = _context.Estimates.Single(m => m.Id == id);
_context.Estimates.Remove(estimate);
_context.SaveChanges(User.GetUserId());
return RedirectToAction("Index");
}
}
}

View File

@ -0,0 +1,15 @@
using Yavsc.Controllers.Generic;
using Yavsc.Models;
using Yavsc.Models.Workflow.Profiles;
namespace Yavsc.Controllers
{
public class FormationSettingsController : SettingsController<FormationSettings>
{
public FormationSettingsController(ApplicationDbContext context) : base(context)
{
}
}
}

View File

@ -0,0 +1,121 @@
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.Data.Entity;
using Yavsc.Models;
using Yavsc.Models.Forms;
namespace Yavsc.Controllers
{
public class FormsController : Controller
{
private ApplicationDbContext _context;
public FormsController(ApplicationDbContext context)
{
_context = context;
}
// GET: Forms
public async Task<IActionResult> Index()
{
return View(await _context.Form.ToListAsync());
}
// GET: Forms/Details/5
public async Task<IActionResult> Details(string id)
{
if (id == null)
{
return HttpNotFound();
}
Form form = await _context.Form.SingleAsync(m => m.Id == id);
if (form == null)
{
return HttpNotFound();
}
return View(form);
}
// GET: Forms/Create
public IActionResult Create()
{
return View();
}
// POST: Forms/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Form form)
{
if (ModelState.IsValid)
{
_context.Form.Add(form);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
return View(form);
}
// GET: Forms/Edit/5
public async Task<IActionResult> Edit(string id)
{
if (id == null)
{
return HttpNotFound();
}
Form form = await _context.Form.SingleAsync(m => m.Id == id);
if (form == null)
{
return HttpNotFound();
}
return View(form);
}
// POST: Forms/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(Form form)
{
if (ModelState.IsValid)
{
_context.Update(form);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
return View(form);
}
// GET: Forms/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(string id)
{
if (id == null)
{
return HttpNotFound();
}
Form form = await _context.Form.SingleAsync(m => m.Id == id);
if (form == null)
{
return HttpNotFound();
}
return View(form);
}
// POST: Forms/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(string id)
{
Form form = await _context.Form.SingleAsync(m => m.Id == id);
_context.Form.Remove(form);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
}
}

View File

@ -0,0 +1,139 @@
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Identity;
using Microsoft.Data.Entity;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Security.Claims;
namespace Yavsc.Controllers
{
using Helpers;
using Microsoft.Extensions.Localization;
using Models;
using ViewModels.FrontOffice;
using Yavsc.Abstract.FileSystem;
using Yavsc.Services;
public class FrontOfficeController : Controller
{
ApplicationDbContext _context;
UserManager<ApplicationUser> _userManager;
ILogger _logger;
IStringLocalizer _SR;
private IBillingService _billing;
public FrontOfficeController(ApplicationDbContext context,
UserManager<ApplicationUser> userManager,
IBillingService billing,
ILoggerFactory loggerFactory,
IStringLocalizer<Yavsc.Resources.YavscLocalisation> SR)
{
_context = context;
_userManager = userManager;
_logger = loggerFactory.CreateLogger<FrontOfficeController>();
_SR = SR;
_billing = billing;
}
public ActionResult Index()
{
var uid = User.GetUserId();
var now = DateTime.Now;
var model = new FrontOfficeIndexViewModel
{
EstimateToProduceCount = _context.RdvQueries.Where(c => c.PerformerId == uid && c.EventDate > now
&& c.ValidationDate == null && !_context.Estimates.Any(e => (e.CommandId == c.Id && e.ProviderValidationDate != null))).Count(),
EstimateToSignAsProCount = _context.RdvQueries.Where(c => (c.PerformerId == uid && c.EventDate > now
&& c.ValidationDate == null && _context.Estimates.Any(e => (e.CommandId == c.Id && e.ProviderValidationDate != null)))).Count(),
EstimateToSignAsCliCount = _context.Estimates.Where(e => e.ClientId == uid && e.ClientValidationDate == null).Count(),
BillToSignAsProCount = 0,
BillToSignAsCliCount = 0,
NewPayementsCount = 0
};
return View(model);
}
[AllowAnonymous]
public ActionResult Profiles(string id)
{
if (id == null)
{
throw new NotImplementedException("No Activity code");
}
ViewBag.Activity = _context.Activities.FirstOrDefault(a => a.Code == id);
var result = _context.ListPerformers(_billing, id);
return View(result);
}
[AllowAnonymous]
public ActionResult HairCut(string id)
{
if (id == null)
{
throw new NotImplementedException("No Activity code");
}
ViewBag.Activity = _context.Activities.FirstOrDefault(a => a.Code == id);
var result = _context.ListPerformers(_billing, id);
return View(result);
}
[Produces("text/x-tex"), Authorize, Route("estimate-{id}.tex")]
public ViewResult EstimateTex(long id)
{
var estimate = _context.Estimates.Include(x => x.Query)
.Include(x => x.Query.Client)
.Include(x => x.Query.PerformerProfile)
.Include(x => x.Query.PerformerProfile.OrganizationAddress)
.Include(x => x.Query.PerformerProfile.Performer)
.Include(e => e.Bill).FirstOrDefault(x => x.Id == id);
Response.ContentType = "text/x-tex";
return View("Estimate.tex", estimate);
}
[Authorize, Route("Estimate-{id}.pdf")]
public IActionResult EstimatePdf(long id)
{
ViewBag.TempDir = Startup.SiteSetup.TempDir;
ViewBag.BillsDir = AbstractFileSystemHelpers.UserBillsDirName;
var estimate = _context.Estimates.Include(x => x.Query)
.Include(x => x.Query.Client)
.Include(x => x.Query.PerformerProfile)
.Include(x => x.Query.PerformerProfile.OrganizationAddress)
.Include(x => x.Query.PerformerProfile.Performer)
.Include(e => e.Bill).FirstOrDefault(x => x.Id == id);
if (estimate == null)
throw new Exception("No data");
return View("Estimate.pdf", estimate);
}
[Authorize]
public IActionResult EstimateProValidation()
{
throw new NotImplementedException();
}
[Authorize]
public IActionResult EstimateClientValidation()
{
throw new NotImplementedException();
}
[Authorize]
public IActionResult BillValidation()
{
throw new NotImplementedException();
}
[Authorize]
public IActionResult BillAcquitment()
{
throw new NotImplementedException();
}
}
}

View File

@ -0,0 +1,120 @@
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.Data.Entity;
using Yavsc.Models;
using Yavsc.Models.Musical.Profiles;
namespace Yavsc.Controllers
{
public class GeneralSettingsController : Controller
{
private ApplicationDbContext _context;
public GeneralSettingsController(ApplicationDbContext context)
{
_context = context;
}
// GET: GeneralSettings
public async Task<IActionResult> Index()
{
return View(await _context.GeneralSettings.ToListAsync());
}
// GET: GeneralSettings/Details/5
public async Task<IActionResult> Details(string id)
{
if (id == null)
{
return HttpNotFound();
}
GeneralSettings generalSettings = await _context.GeneralSettings.SingleAsync(m => m.UserId == id);
if (generalSettings == null)
{
return HttpNotFound();
}
return View(generalSettings);
}
// GET: GeneralSettings/Create
public IActionResult Create()
{
return View();
}
// POST: GeneralSettings/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(GeneralSettings generalSettings)
{
if (ModelState.IsValid)
{
_context.GeneralSettings.Add(generalSettings);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(generalSettings);
}
// GET: GeneralSettings/Edit/5
public async Task<IActionResult> Edit(string id)
{
if (id == null)
{
return HttpNotFound();
}
GeneralSettings generalSettings = await _context.GeneralSettings.SingleAsync(m => m.UserId == id);
if (generalSettings == null)
{
return HttpNotFound();
}
return View(generalSettings);
}
// POST: GeneralSettings/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(GeneralSettings generalSettings)
{
if (ModelState.IsValid)
{
_context.Update(generalSettings);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(generalSettings);
}
// GET: GeneralSettings/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(string id)
{
if (id == null)
{
return HttpNotFound();
}
GeneralSettings generalSettings = await _context.GeneralSettings.SingleAsync(m => m.UserId == id);
if (generalSettings == null)
{
return HttpNotFound();
}
return View(generalSettings);
}
// POST: GeneralSettings/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(string id)
{
GeneralSettings generalSettings = await _context.GeneralSettings.SingleAsync(m => m.UserId == id);
_context.GeneralSettings.Remove(generalSettings);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
}
}

View File

@ -0,0 +1,149 @@
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
using Yavsc.Models;
using Yavsc.Models.Musical.Profiles;
namespace Yavsc.Controllers
{
[Authorize]
public class InstrumentationController : Controller
{
private ApplicationDbContext _context;
public InstrumentationController(ApplicationDbContext context)
{
_context = context;
}
// GET: Instrumentation
public async Task<IActionResult> Index()
{
return View(await _context.Instrumentation.ToListAsync());
}
// GET: Instrumentation/Details/5
public async Task<IActionResult> Details(string id)
{
if (id == null)
{
return HttpNotFound();
}
Instrumentation musicianSettings = await _context.Instrumentation.SingleAsync(m => m.UserId == id);
if (musicianSettings == null)
{
return HttpNotFound();
}
return View(musicianSettings);
}
// GET: Instrumentation/Create
public IActionResult Create()
{
var uid = User.GetUserId();
var owned = _context.Instrumentation.Include(i=>i.Tool).Where(i=>i.UserId==uid).Select(i=>i.InstrumentId);
var ownedArray = owned.ToArray();
ViewBag.YetAvailableInstruments = _context.Instrument.Select(k=>new SelectListItem
{ Text = k.Name, Value = k.Id.ToString(), Disabled = ownedArray.Contains(k.Id) });
return View(new Instrumentation { UserId = uid });
}
// POST: Instrumentation/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Instrumentation model)
{
var uid = User.GetUserId();
if (ModelState.IsValid)
{
if (model.UserId != uid) if (!User.IsInRole(Constants.AdminGroupName))
return new ChallengeResult();
_context.Instrumentation.Add(model);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
return View(model);
}
// GET: Instrumentation/Edit/5
public async Task<IActionResult> Edit(string id)
{
var uid = User.GetUserId();
if (id == null)
{
return HttpNotFound();
}
if (id != uid) if (!User.IsInRole(Constants.AdminGroupName))
return new ChallengeResult();
Instrumentation musicianSettings = await _context.Instrumentation.SingleAsync(m => m.UserId == id);
if (musicianSettings == null)
{
return HttpNotFound();
}
return View(musicianSettings);
}
// POST: Instrumentation/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(Instrumentation musicianSettings)
{
var uid = User.GetUserId();
if (musicianSettings.UserId != uid) if (!User.IsInRole(Constants.AdminGroupName))
return new ChallengeResult();
if (ModelState.IsValid)
{
_context.Update(musicianSettings);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
return View(musicianSettings);
}
// GET: Instrumentation/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(string id)
{
if (id == null)
{
return HttpNotFound();
}
Instrumentation musicianSettings = await _context.Instrumentation.SingleAsync(m => m.UserId == id);
if (musicianSettings == null)
{
return HttpNotFound();
}
var uid = User.GetUserId();
if (musicianSettings.UserId != uid) if (!User.IsInRole(Constants.AdminGroupName))
return new ChallengeResult();
return View(musicianSettings);
}
// POST: Instrumentation/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(string id)
{
Instrumentation musicianSettings = await _context.Instrumentation.SingleAsync(m => m.UserId == id);
var uid = User.GetUserId();
if (musicianSettings.UserId != uid) if (!User.IsInRole(Constants.AdminGroupName))
return new ChallengeResult();
_context.Instrumentation.Remove(musicianSettings);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
}
}

View File

@ -0,0 +1,120 @@
using System.Linq;
using Microsoft.AspNet.Mvc;
namespace Yavsc.Controllers
{
using System.Security.Claims;
using Models;
using Models.Musical;
public class InstrumentsController : Controller
{
private ApplicationDbContext _context;
public InstrumentsController(ApplicationDbContext context)
{
_context = context;
}
// GET: Instruments
public IActionResult Index()
{
return View(_context.Instrument.ToList());
}
// GET: Instruments/Details/5
public IActionResult Details(long? id)
{
if (id == null)
{
return HttpNotFound();
}
Instrument instrument = _context.Instrument.Single(m => m.Id == id);
if (instrument == null)
{
return HttpNotFound();
}
return View(instrument);
}
// GET: Instruments/Create
public IActionResult Create()
{
return View();
}
// POST: Instruments/Create
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Instrument instrument)
{
if (ModelState.IsValid)
{
_context.Instrument.Add(instrument);
_context.SaveChanges(User.GetUserId());
return RedirectToAction("Index");
}
return View(instrument);
}
// GET: Instruments/Edit/5
public IActionResult Edit(long? id)
{
if (id == null)
{
return HttpNotFound();
}
Instrument instrument = _context.Instrument.Single(m => m.Id == id);
if (instrument == null)
{
return HttpNotFound();
}
return View(instrument);
}
// POST: Instruments/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Edit(Instrument instrument)
{
if (ModelState.IsValid)
{
_context.Update(instrument);
_context.SaveChanges(User.GetUserId());
return RedirectToAction("Index");
}
return View(instrument);
}
// GET: Instruments/Delete/5
[ActionName("Delete")]
public IActionResult Delete(long? id)
{
if (id == null)
{
return HttpNotFound();
}
Instrument instrument = _context.Instrument.Single(m => m.Id == id);
if (instrument == null)
{
return HttpNotFound();
}
return View(instrument);
}
// POST: Instruments/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public IActionResult DeleteConfirmed(long id)
{
Instrument instrument = _context.Instrument.Single(m => m.Id == id);
_context.Instrument.Remove(instrument);
_context.SaveChanges(User.GetUserId());
return RedirectToAction("Index");
}
}
}

View File

@ -0,0 +1,120 @@
using System.Linq;
using Microsoft.AspNet.Mvc;
namespace Yavsc.Controllers
{
using System.Security.Claims;
using Models;
using Models.Musical;
public class MusicalTendenciesController : Controller
{
private ApplicationDbContext _context;
public MusicalTendenciesController(ApplicationDbContext context)
{
_context = context;
}
// GET: MusicalTendencies
public IActionResult Index()
{
return View(_context.MusicalTendency.ToList());
}
// GET: MusicalTendencies/Details/5
public IActionResult Details(long? id)
{
if (id == null)
{
return HttpNotFound();
}
MusicalTendency musicalTendency = _context.MusicalTendency.Single(m => m.Id == id);
if (musicalTendency == null)
{
return HttpNotFound();
}
return View(musicalTendency);
}
// GET: MusicalTendencies/Create
public IActionResult Create()
{
return View();
}
// POST: MusicalTendencies/Create
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(MusicalTendency musicalTendency)
{
if (ModelState.IsValid)
{
_context.MusicalTendency.Add(musicalTendency);
_context.SaveChanges(User.GetUserId());
return RedirectToAction("Index");
}
return View(musicalTendency);
}
// GET: MusicalTendencies/Edit/5
public IActionResult Edit(long? id)
{
if (id == null)
{
return HttpNotFound();
}
MusicalTendency musicalTendency = _context.MusicalTendency.Single(m => m.Id == id);
if (musicalTendency == null)
{
return HttpNotFound();
}
return View(musicalTendency);
}
// POST: MusicalTendencies/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Edit(MusicalTendency musicalTendency)
{
if (ModelState.IsValid)
{
_context.Update(musicalTendency);
_context.SaveChanges(User.GetUserId());
return RedirectToAction("Index");
}
return View(musicalTendency);
}
// GET: MusicalTendencies/Delete/5
[ActionName("Delete")]
public IActionResult Delete(long? id)
{
if (id == null)
{
return HttpNotFound();
}
MusicalTendency musicalTendency = _context.MusicalTendency.Single(m => m.Id == id);
if (musicalTendency == null)
{
return HttpNotFound();
}
return View(musicalTendency);
}
// POST: MusicalTendencies/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public IActionResult DeleteConfirmed(long id)
{
MusicalTendency musicalTendency = _context.MusicalTendency.Single(m => m.Id == id);
_context.MusicalTendency.Remove(musicalTendency);
_context.SaveChanges(User.GetUserId());
return RedirectToAction("Index");
}
}
}

View File

@ -0,0 +1,122 @@
using System.Linq;
using System.Security.Claims;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Mvc;
using Yavsc.Models;
using Yavsc.Models.Billing;
namespace Yavsc.Controllers
{
[Authorize(Roles="Administrator")]
public class SIRENExceptionsController : Controller
{
private ApplicationDbContext _context;
public SIRENExceptionsController(ApplicationDbContext context)
{
_context = context;
}
// GET: SIRENExceptions
public IActionResult Index()
{
return View(_context.ExceptionsSIREN.ToList());
}
// GET: SIRENExceptions/Details/5
public IActionResult Details(string id)
{
if (id == null)
{
return HttpNotFound();
}
ExceptionSIREN exceptionSIREN = _context.ExceptionsSIREN.Single(m => m.SIREN == id);
if (exceptionSIREN == null)
{
return HttpNotFound();
}
return View(exceptionSIREN);
}
// GET: SIRENExceptions/Create
public IActionResult Create()
{
return View();
}
// POST: SIRENExceptions/Create
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(ExceptionSIREN exceptionSIREN)
{
if (ModelState.IsValid)
{
_context.ExceptionsSIREN.Add(exceptionSIREN);
_context.SaveChanges(User.GetUserId());
return RedirectToAction("Index");
}
return View(exceptionSIREN);
}
// GET: SIRENExceptions/Edit/5
public IActionResult Edit(string id)
{
if (id == null)
{
return HttpNotFound();
}
ExceptionSIREN exceptionSIREN = _context.ExceptionsSIREN.Single(m => m.SIREN == id);
if (exceptionSIREN == null)
{
return HttpNotFound();
}
return View(exceptionSIREN);
}
// POST: SIRENExceptions/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Edit(ExceptionSIREN exceptionSIREN)
{
if (ModelState.IsValid)
{
_context.Update(exceptionSIREN);
_context.SaveChanges(User.GetUserId());
return RedirectToAction("Index");
}
return View(exceptionSIREN);
}
// GET: SIRENExceptions/Delete/5
[ActionName("Delete")]
public IActionResult Delete(string id)
{
if (id == null)
{
return HttpNotFound();
}
ExceptionSIREN exceptionSIREN = _context.ExceptionsSIREN.Single(m => m.SIREN == id);
if (exceptionSIREN == null)
{
return HttpNotFound();
}
return View(exceptionSIREN);
}
// POST: SIRENExceptions/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public IActionResult DeleteConfirmed(string id)
{
ExceptionSIREN exceptionSIREN = _context.ExceptionsSIREN.Single(m => m.SIREN == id);
_context.ExceptionsSIREN.Remove(exceptionSIREN);
_context.SaveChanges(User.GetUserId());
return RedirectToAction("Index");
}
}
}

View File

@ -0,0 +1,146 @@
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Mvc;
using Microsoft.Data.Entity;
namespace Yavsc.Controllers.Generic
{
using System.Linq;
using Models;
using Yavsc.Services;
[Authorize]
public abstract class SettingsController<TSettings> : Controller where TSettings : class, ISpecializationSettings, new()
{
protected ApplicationDbContext _context;
DbSet<TSettings> dbSet=null;
protected string activityCode=null;
protected DbSet<TSettings> Settings { get {
if (dbSet == null) {
dbSet = (DbSet<TSettings>) BillingService.UserSettings.Single(s=>s.Name == typeof(TSettings).Name).GetValue(_context);
}
return dbSet;
} }
public SettingsController(ApplicationDbContext context)
{
_context = context;
}
public async Task<IActionResult> Index()
{
var existing = await this.Settings.SingleOrDefaultAsync(p=>p.UserId == User.GetUserId());
return View(existing);
}
// GET: BrusherProfile/Details/5
public async Task<IActionResult> Details(string id)
{
if (id == null)
{
id = User.GetUserId();
}
var profile = await Settings.SingleAsync(m => m.UserId == id);
if (profile == null)
{
return HttpNotFound();
}
return View(profile);
}
// GET: BrusherProfile/Create
public IActionResult Create()
{
return View("Edit", new TSettings());
}
// GET: BrusherProfile/Edit/5
public async Task<IActionResult> Edit(string id)
{
if (id == null)
{
id = User.GetUserId();
}
TSettings setting = await Settings.SingleOrDefaultAsync(m => m.UserId == id);
if (setting == null)
{
setting = new TSettings { };
}
return View(setting);
}
// GET: BrusherProfile/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(string id)
{
if (id == null)
{
return HttpNotFound();
}
var brusherProfile = await Settings.SingleAsync(m => m.UserId == id);
if (brusherProfile == null)
{
return HttpNotFound();
}
return View(brusherProfile);
}
// POST: FormationSettings/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(TSettings settings)
{
if (settings.UserId == null) settings.UserId = User.GetUserId();
if (ModelState.IsValid)
{
Settings.Add(settings);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View("Edit",settings);
}
// POST: FormationSettings/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(TSettings settings)
{
if (settings.UserId == null) {
settings.UserId = User.GetUserId();
Settings.Add(settings);
} else
_context.Update(settings);
if (ModelState.IsValid)
{
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(settings);
}
// POST: FormationSettings/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(string id)
{
TSettings formationSettings = await Settings.SingleAsync(m => m.UserId == id);
Settings.Remove(formationSettings);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
}
}

View File

@ -0,0 +1,17 @@
using Yavsc.Models;
using Yavsc.Models.Haircut;
using Microsoft.AspNet.Authorization;
using Yavsc.Controllers.Generic;
namespace Yavsc.Controllers
{
[Authorize(Roles="Performer")]
public class BrusherProfileController : SettingsController<BrusherProfile>
{
public BrusherProfileController(ApplicationDbContext context) : base(context)
{
}
}
}

View File

@ -0,0 +1,121 @@
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.Data.Entity;
using Yavsc.Models;
using Yavsc.Models.Drawing;
namespace Yavsc.Controllers
{
public class ColorsController : Controller
{
private ApplicationDbContext _context;
public ColorsController(ApplicationDbContext context)
{
_context = context;
}
// GET: Colors
public async Task<IActionResult> Index()
{
return View(await _context.Color.ToListAsync());
}
// GET: Colors/Details/5
public async Task<IActionResult> Details(long? id)
{
if (id == null)
{
return HttpNotFound();
}
Color color = await _context.Color.SingleAsync(m => m.Id == id);
if (color == null)
{
return HttpNotFound();
}
return View(color);
}
// GET: Colors/Create
public IActionResult Create()
{
return View(new Color());
}
// POST: Colors/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Color color)
{
if (ModelState.IsValid)
{
_context.Color.Add(color);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
return View(color);
}
// GET: Colors/Edit/5
public async Task<IActionResult> Edit(long? id)
{
if (id == null)
{
return HttpNotFound();
}
Color color = await _context.Color.SingleAsync(m => m.Id == id);
if (color == null)
{
return HttpNotFound();
}
return View(color);
}
// POST: Colors/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(Color color)
{
if (ModelState.IsValid)
{
_context.Update(color);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
return View(color);
}
// GET: Colors/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(long? id)
{
if (id == null)
{
return HttpNotFound();
}
Color color = await _context.Color.SingleAsync(m => m.Id == id);
if (color == null)
{
return HttpNotFound();
}
return View(color);
}
// POST: Colors/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(long id)
{
Color color = await _context.Color.SingleAsync(m => m.Id == id);
_context.Color.Remove(color);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
}
}

View File

@ -0,0 +1,472 @@
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.Data.Entity;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.OptionsModel;
namespace Yavsc.Controllers
{
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Google.Messaging;
using Yavsc.Models.Relationship;
using Yavsc.Services;
using Newtonsoft.Json;
using Microsoft.AspNet.Http;
using Yavsc.Extensions;
using Yavsc.Models.Haircut;
using System.Globalization;
using Microsoft.AspNet.Mvc.Rendering;
using System.Collections.Generic;
using Yavsc.Models.Messaging;
using PayPal.PayPalAPIInterfaceService.Model;
public class HairCutCommandController : CommandController
{
public HairCutCommandController(ApplicationDbContext context,
IOptions<PayPalSettings> payPalSettings,
IOptions<GoogleAuthSettings> googleSettings,
IGoogleCloudMessageSender GCMSender,
UserManager<ApplicationUser> userManager,
IStringLocalizer<Yavsc.Resources.YavscLocalisation> localizer,
IEmailSender emailSender,
IOptions<SmtpSettings> smtpSettings,
IOptions<SiteSettings> siteSettings,
ICalendarManager calManager,
ILoggerFactory loggerFactory) : base(context, googleSettings, GCMSender, userManager,
calManager, localizer, emailSender, smtpSettings, siteSettings, loggerFactory)
{
this.payPalSettings = payPalSettings.Value;
}
PayPalSettings payPalSettings;
private async Task<HairCutQuery> GetQuery(long id)
{
var query = await _context.HairCutQueries
.Include(x => x.Location)
.Include(x => x.PerformerProfile)
.Include(x => x.Prestation)
.Include(x => x.PerformerProfile.Performer)
.Include(x => x.PerformerProfile.Performer.Devices)
.Include(x => x.Regularisation)
.SingleAsync(m => m.Id == id);
query.SelectedProfile = await _context.BrusherProfile.SingleAsync(b => b.UserId == query.PerformerId);
return query;
}
public async Task<IActionResult> ClientCancel(long id)
{
HairCutQuery command = await GetQuery(id);
if (command == null)
{
return HttpNotFound();
}
SetViewBagPaymentUrls(id);
return View(command);
}
public async Task<IActionResult> PaymentConfirmation([FromRoute] long id, string token, string PayerID)
{
HairCutQuery command = await GetQuery(id);
if (command == null)
{
return HttpNotFound();
}
var paymentInfo = await _context.ConfirmPayment(User.GetUserId(), PayerID, token);
ViewData["paymentinfo"] = paymentInfo;
command.Regularisation = paymentInfo.DbContent;
command.PaymentId = token;
bool paymentOk = false;
if (paymentInfo.DetailsFromPayPal != null)
if (paymentInfo.DetailsFromPayPal.Ack == AckCodeType.SUCCESS)
{
// FIXME Assert (command.ValidationDate == null)
if (command.ValidationDate == null) {
paymentOk = true;
command.ValidationDate = DateTime.Now;
}
else _logger.LogError
("This Command were yet validated, and is now paied one more ...");
}
await _context.SaveChangesAsync(User.GetUserId());
SetViewBagPaymentUrls(id);
if (paymentOk)
{
MessageWithPayloadResponse grep = null;
var yaev = command.CreatePaymentEvent(paymentInfo, _localizer);
if (command.PerformerProfile.AcceptNotifications)
{
if (command.PerformerProfile.Performer.Devices.Count > 0)
{
var regids = command.PerformerProfile.Performer
.Devices.Select(d => d.GCMRegistrationId);
grep = await _GCMSender.NotifyAsync(regids, yaev);
}
// TODO setup a profile choice to allow notifications
// both on mailbox and mobile
// if (grep==null || grep.success<=0 || grep.failure>0)
ViewBag.GooglePayload = grep;
}
ViewBag.EmailSent = await _emailSender.SendEmailAsync(
command.PerformerProfile.Performer.UserName,
command.PerformerProfile.Performer.Email,
yaev.Topic,
yaev.CreateBody()
);
}
ViewData["Notify"] = new List<Notification> {
new Notification {
title= "Paiment PayPal",
body = "Votre paiment a été accépté."
}
};
return View("Details", command);
}
private void SetViewBagPaymentUrls(long id)
{
ViewBag.CreatePaymentUrl = Request.ToAbsolute("api/haircut/createpayment/" + id);
ViewBag.ExecutePaymentUrl = Request.ToAbsolute("api/payment/execute");
ViewBag.Urls = Request.GetPaymentUrls("HairCutCommand", id.ToString());
}
public async Task<IActionResult> ClientCancelConfirm(long id)
{
var query = await GetQuery(id); if (query == null)
{
return HttpNotFound();
}
var uid = User.GetUserId();
if (query.ClientId != uid)
return new ChallengeResult();
_context.HairCutQueries.Remove(query);
await _context.SaveChangesAsync();
return await Index();
}
/// <summary>
/// List client's queries (and only client's ones)
/// </summary>
/// <returns></returns>
public override async Task<IActionResult> Index()
{
var uid = User.GetUserId();
return View("Index", await _context.HairCutQueries
.Include(x => x.Client)
.Include(x => x.PerformerProfile)
.Include(x => x.PerformerProfile.Performer)
.Include(x => x.Location)
.Where(x => x.ClientId == uid)
.ToListAsync());
}
public override async Task<IActionResult> Details(long id)
{
HairCutQuery command = await _context.HairCutQueries
.Include(x => x.Location)
.Include(x => x.PerformerProfile)
.Include(x => x.Prestation)
.Include(x => x.PerformerProfile.Performer)
.Include(x => x.Regularisation)
.SingleOrDefaultAsync(m => m.Id == id);
if (command == null)
{
return HttpNotFound();
}
SetViewBagPaymentUrls(id);
return View(command);
}
/// <summary>
/// Crée une requête en coiffure à domicile
///
/// </summary>
/// <param name="model"></param>
/// <param name="taintIds"></param>
/// <returns></returns>
[HttpPost, Authorize]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateHairCutQuery(HairCutQuery model, string taintIds)
{
// TODO utiliser Markdown-av+tags
var uid = User.GetUserId();
model.ClientId = uid;
var prid = model.PerformerId;
var brusherProfile = await _context.BrusherProfile.SingleAsync(p => p.UserId == prid);
long[] longtaintIds = null;
List<HairTaint> colors = null;
if (string.IsNullOrWhiteSpace(uid)
|| string.IsNullOrWhiteSpace(prid))
throw new InvalidOperationException(
"This method needs a PerformerId"
);
if (!model.Consent)
ModelState.AddModelError("Consent", "Vous devez accepter les conditions générales de vente de ce service");
if (ModelState.IsValid)
{
_logger.LogInformation("le Model _est_ valide.");
var pro = _context.Performers.Include(
u => u.Performer
).Include(u => u.Performer.Devices)
.FirstOrDefault(
x => x.PerformerId == model.PerformerId
);
if (taintIds != null)
{
longtaintIds = taintIds.Split(',').Select(s => long.Parse(s)).ToArray();
colors = _context.HairTaint.Where(t => longtaintIds.Contains(t.Id)).ToList();
// a Prestation is required
model.Prestation.Taints = colors.Select(c =>
new HairTaintInstance { Taint = c }).ToList();
}
// Une prestation pour enfant ou homme inclut toujours la coupe.
if (model.Prestation.Gender != HairCutGenders.Women)
model.Prestation.Cut = true;
if (model.Location != null)
{
var existingLocation = await _context.Locations.FirstOrDefaultAsync(x => x.Address == model.Location.Address
&& x.Longitude == model.Location.Longitude && x.Latitude == model.Location.Latitude);
if (existingLocation != null)
{
model.Location = existingLocation;
}
else _context.Attach<Location>(model.Location);
}
var existingPrestation = await _context.HairPrestation.FirstOrDefaultAsync(x => model.PrestationId == x.Id);
if (existingPrestation != null)
{
model.Prestation = existingPrestation;
}
else _context.Attach<HairPrestation>(model.Prestation);
_context.HairCutQueries.Add(model);
await _context.SaveChangesAsync(uid);
_logger.LogInformation("la donnée _est_ sauvée:");
MessageWithPayloadResponse grep = null;
model.SelectedProfile = brusherProfile;
model.Client = await _userManager.FindByIdAsync(uid);
_logger.LogInformation(JsonConvert.SerializeObject(model));
var yaev = model.CreateNewHairCutQueryEvent(_localizer);
if (pro.AcceptPublicContact)
{
if (pro.AcceptNotifications)
{
if (pro.Performer.Devices.Count > 0)
{
var regids = pro.Performer.Devices.Select(d => d.GCMRegistrationId);
grep = await _GCMSender.NotifyHairCutQueryAsync(regids, yaev);
}
// TODO setup a profile choice to allow notifications
// both on mailbox and mobile
// if (grep==null || grep.success<=0 || grep.failure>0)
ViewBag.GooglePayload = grep;
if (grep != null)
_logger.LogWarning($"Performer: {pro.Performer.UserName} success: {grep.success} failure: {grep.failure}");
}
// TODO if pro.AllowCalendarEventInsert
if (pro.Performer.DedicatedGoogleCalendar != null && yaev.EventDate != null)
{
_logger.LogInformation("Inserting an event in the calendar");
DateTime evdate = yaev.EventDate ?? new DateTime();
var result = await _calendarManager.CreateEventAsync(pro.Performer.Id,
pro.Performer.DedicatedGoogleCalendar,
evdate, 3600, yaev.Topic, yaev.Client.UserName + " : " + yaev.Reason,
yaev.Location?.Address, false
);
if (result.Id == null)
_logger.LogWarning("Something went wrong, calendar event not created");
}
else _logger.LogWarning($"Calendar: {pro.Performer.DedicatedGoogleCalendar != null}\nEventDate: {yaev.EventDate != null}");
await _emailSender.SendEmailAsync(
pro.Performer.UserName,
pro.Performer.Email,
$"{yaev.Client.UserName}: {yaev.Reason}",
$"{yaev.Reason}\r\n-- \r\n{yaev.Previsional}\r\n{yaev.EventDate}\r\n"
);
}
else
{
// TODO if (AcceptProContact) try & find a bookmaker to send him this query
}
ViewBag.Activity = _context.Activities.FirstOrDefault(a => a.Code == model.ActivityCode);
ViewBag.GoogleSettings = _googleSettings;
var items = model.GetBillItems();
var addition = items.Addition();
ViewBag.Addition = addition.ToString("C", CultureInfo.CurrentUICulture);
return View("CommandConfirmation", model);
}
ViewBag.Activity = _context.Activities.FirstOrDefault(a => a.Code == model.ActivityCode);
ViewBag.GoogleSettings = _googleSettings;
model.SelectedProfile = brusherProfile;
SetViewData(model.ActivityCode, model.PerformerId, model.Prestation);
return View("HairCut", model);
}
public async Task<ActionResult> HairCut(string performerId, string activityCode)
{
HairPrestation pPrestation = null;
var prestaJson = HttpContext.Session.GetString("HairCutPresta");
if (prestaJson != null)
{
pPrestation = JsonConvert.DeserializeObject<HairPrestation>(prestaJson);
}
else
{
pPrestation = new HairPrestation { };
}
var uid = User.GetUserId();
var user = await _userManager.FindByIdAsync(uid);
SetViewData(activityCode, performerId, pPrestation);
var perfer = _context.Performers.Include(
p => p.Performer
).Single(p => p.PerformerId == performerId);
var result = new HairCutQuery
{
PerformerProfile = perfer,
PerformerId = perfer.PerformerId,
ClientId = uid,
Prestation = pPrestation,
Client = user,
Location = new Location { Address = "" },
EventDate = new DateTime()
};
return View(result);
}
private void SetViewData(string activityCode, string performerId, HairPrestation pPrestation)
{
ViewBag.HairTaints = _context.HairTaint.Include(t => t.Color);
ViewBag.HairTaintsItems = _context.HairTaint.Include(t => t.Color).Select(
c =>
new SelectListItem
{
Text = c.Color.Name + " " + c.Brand,
Value = c.Id.ToString()
}
);
ViewBag.HairTechnos = EnumExtensions.GetSelectList(typeof(HairTechnos), _localizer);
ViewBag.HairLength = EnumExtensions.GetSelectList(typeof(HairLength), _localizer);
ViewBag.Activity = _context.Activities.First(a => a.Code == activityCode);
ViewBag.Gender = EnumExtensions.GetSelectList(typeof(HairCutGenders), _localizer, HairCutGenders.Women);
ViewBag.HairDressings = EnumExtensions.GetSelectList(typeof(HairDressings), _localizer);
ViewBag.ColorsClass = (pPrestation.Tech == HairTechnos.Color
|| pPrestation.Tech == HairTechnos.Mech) ? "" : "hidden";
ViewBag.TechClass = (pPrestation.Gender == HairCutGenders.Women) ? "" : "hidden";
ViewData["PerfPrefs"] = _context.BrusherProfile.Single(p => p.UserId == performerId);
}
[HttpPost, Authorize]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateHairMultiCutQuery(HairMultiCutQuery command)
{
var uid = User.GetUserId();
var prid = command.PerformerId;
if (string.IsNullOrWhiteSpace(uid)
|| string.IsNullOrWhiteSpace(prid))
throw new InvalidOperationException(
"This method needs a PerformerId"
);
var pro = _context.Performers.Include(
u => u.Performer
).Include(u => u.Performer.Devices)
.FirstOrDefault(
x => x.PerformerId == command.PerformerId
);
var user = await _userManager.FindByIdAsync(uid);
command.Client = user;
command.ClientId = uid;
command.PerformerProfile = pro;
// FIXME Why!!
// ModelState.ClearValidationState("PerformerProfile.Avatar");
// ModelState.ClearValidationState("Client.Avatar");
// ModelState.ClearValidationState("ClientId");
ModelState.MarkFieldSkipped("ClientId");
if (ModelState.IsValid)
{
var existingLocation = _context.Locations.FirstOrDefault(x => x.Address == command.Location.Address
&& x.Longitude == command.Location.Longitude && x.Latitude == command.Location.Latitude);
if (existingLocation != null)
{
command.Location = existingLocation;
}
else _context.Attach<Location>(command.Location);
_context.HairMultiCutQueries.Add(command, GraphBehavior.IncludeDependents);
_context.SaveChanges(User.GetUserId());
var brSettings = await _context.BrusherProfile.SingleAsync(
bp => bp.UserId == command.PerformerId
);
var yaev = command.CreateEvent(_localizer, brSettings);
string msg = yaev.CreateBoby();
MessageWithPayloadResponse grep = null;
if (pro.AcceptNotifications
&& pro.AcceptPublicContact)
{
if (pro.Performer.Devices?.Count > 0)
{
var regids = command.PerformerProfile.Performer
.Devices.Select(d => d.GCMRegistrationId);
grep = await _GCMSender.NotifyHairCutQueryAsync(regids, yaev);
}
// TODO setup a profile choice to allow notifications
// both on mailbox and mobile, and to allow calendar event insertion.
// if (grep==null || grep.success<=0 || grep.failure>0)
ViewBag.GooglePayload = grep;
if (grep != null)
_logger.LogWarning($"Performer: {command.PerformerProfile.Performer.UserName} success: {grep.success} failure: {grep.failure}");
if (pro.Performer.DedicatedGoogleCalendar != null && yaev.EventDate != null)
{
DateTime evdate = yaev.EventDate ?? new DateTime();
await _calendarManager.CreateEventAsync(
pro.Performer.Id,
pro.Performer.DedicatedGoogleCalendar,
evdate, 3600, yaev.Topic, msg,
yaev.Location?.ToString(), false
);
}
await _emailSender.SendEmailAsync(
command.PerformerProfile.Performer.UserName,
command.PerformerProfile.Performer.Email,
yaev.Topic + " " + yaev.Sender,
$"{msg}\r\n-- \r\n{yaev.Previsional}\r\n{yaev.EventDate}\r\n"
);
}
ViewBag.Activity = _context.Activities.FirstOrDefault(a => a.Code == command.ActivityCode);
ViewBag.GoogleSettings = _googleSettings;
return View("CommandConfirmation", command);
}
ViewBag.Activity = _context.Activities.FirstOrDefault(a => a.Code == command.ActivityCode);
ViewBag.GoogleSettings = _googleSettings;
return View("HairCut", command);
}
}
}

View File

@ -0,0 +1,120 @@
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.Data.Entity;
using Yavsc.Models;
using Yavsc.Models.Haircut;
namespace Yavsc.Controllers
{
public class HairPrestationsController : Controller
{
private ApplicationDbContext _context;
public HairPrestationsController(ApplicationDbContext context)
{
_context = context;
}
// GET: HairPrestations
public async Task<IActionResult> Index()
{
return View(await _context.HairPrestation.ToListAsync());
}
// GET: HairPrestations/Details/5
public async Task<IActionResult> Details(long? id)
{
if (id == null)
{
return HttpNotFound();
}
HairPrestation hairPrestation = await _context.HairPrestation.SingleAsync(m => m.Id == id);
if (hairPrestation == null)
{
return HttpNotFound();
}
return View(hairPrestation);
}
// GET: HairPrestations/Create
public IActionResult Create()
{
return View();
}
// POST: HairPrestations/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(HairPrestation hairPrestation)
{
if (ModelState.IsValid)
{
_context.HairPrestation.Add(hairPrestation);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(hairPrestation);
}
// GET: HairPrestations/Edit/5
public async Task<IActionResult> Edit(long? id)
{
if (id == null)
{
return HttpNotFound();
}
HairPrestation hairPrestation = await _context.HairPrestation.SingleAsync(m => m.Id == id);
if (hairPrestation == null)
{
return HttpNotFound();
}
return View(hairPrestation);
}
// POST: HairPrestations/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(HairPrestation hairPrestation)
{
if (ModelState.IsValid)
{
_context.Update(hairPrestation);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(hairPrestation);
}
// GET: HairPrestations/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(long? id)
{
if (id == null)
{
return HttpNotFound();
}
HairPrestation hairPrestation = await _context.HairPrestation.SingleAsync(m => m.Id == id);
if (hairPrestation == null)
{
return HttpNotFound();
}
return View(hairPrestation);
}
// POST: HairPrestations/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(long id)
{
HairPrestation hairPrestation = await _context.HairPrestation.SingleAsync(m => m.Id == id);
_context.HairPrestation.Remove(hairPrestation);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
}
}

View File

@ -0,0 +1,129 @@
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
using Yavsc.Models;
using Yavsc.Models.Haircut;
namespace Yavsc.Controllers
{
[Authorize("AdministratorOnly")]
public class HairTaintsController : Controller
{
private ApplicationDbContext _context;
public HairTaintsController(ApplicationDbContext context)
{
_context = context;
}
// GET: HairTaints
public async Task<IActionResult> Index()
{
var applicationDbContext = _context.HairTaint.Include(h => h.Color);
return View(await applicationDbContext.ToListAsync());
}
// GET: HairTaints/Details/5
public async Task<IActionResult> Details(long? id)
{
if (id == null)
{
return HttpNotFound();
}
HairTaint hairTaint = await _context.HairTaint.SingleAsync(m => m.Id == id);
if (hairTaint == null)
{
return HttpNotFound();
}
return View(hairTaint);
}
// GET: HairTaints/Create
public IActionResult Create()
{
ViewBag.ColorId = new SelectList(_context.Color, "Id", "Name");
return View();
}
// POST: HairTaints/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(HairTaint hairTaint)
{
if (ModelState.IsValid)
{
_context.HairTaint.Add(hairTaint);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
ViewBag.ColorId = new SelectList(_context.Color, "Id", "Name", hairTaint.ColorId);
return View(hairTaint);
}
// GET: HairTaints/Edit/5
public async Task<IActionResult> Edit(long? id)
{
if (id == null)
{
return HttpNotFound();
}
HairTaint hairTaint = await _context.HairTaint.SingleAsync(m => m.Id == id);
if (hairTaint == null)
{
return HttpNotFound();
}
ViewBag.ColorId = new SelectList(_context.Color, "Id", "Name",hairTaint.ColorId);
return View(hairTaint);
}
// POST: HairTaints/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(HairTaint hairTaint)
{
if (ModelState.IsValid)
{
_context.Update(hairTaint);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
ViewBag.ColorId = new SelectList(_context.Color, "Id", "Name", hairTaint.ColorId);
return View(hairTaint);
}
// GET: HairTaints/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(long? id)
{
if (id == null)
{
return HttpNotFound();
}
HairTaint hairTaint = await _context.HairTaint.SingleAsync(m => m.Id == id);
if (hairTaint == null)
{
return HttpNotFound();
}
return View(hairTaint);
}
// POST: HairTaints/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(long id)
{
HairTaint hairTaint = await _context.HairTaint.SingleAsync(m => m.Id == id);
_context.HairTaint.Remove(hairTaint);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
}
}

View File

@ -0,0 +1,148 @@
using Microsoft.AspNet.Mvc.Localization;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Http.Features;
using Microsoft.AspNet.Diagnostics;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Identity;
using System.Linq;
using System.Security.Claims;
using Microsoft.Data.Entity;
using Microsoft.AspNet.Http;
using System.Threading.Tasks;
namespace Yavsc.Controllers
{
using System.IO;
using Models;
using Yavsc;
using Yavsc.Helpers;
[AllowAnonymous]
public class HomeController : Controller
{
public IHostingEnvironment Hosting { get; set; }
private ApplicationDbContext DbContext;
private readonly IHtmlLocalizer _localizer;
public HomeController(IHtmlLocalizer<Startup> localizer, IHostingEnvironment hosting,
ApplicationDbContext context, UserManager<ApplicationUser> userManager)
{
_localizer = localizer;
Hosting = hosting;
DbContext = context;
}
public async Task<IActionResult> Index(string id)
{
/*
*/ ViewBag.IsFromSecureProx = (Request.Headers.ContainsKey(Constants.SshHeaderKey))? Request.Headers[Constants.SshHeaderKey]=="on" : false ;
ViewBag.SecureHomeUrl = "https://"+Request.Headers["X-Forwarded-Host"];
ViewBag.SshHeaderKey = Request.Headers[Constants.SshHeaderKey];
var uid = User.GetUserId();
long [] clicked=null;
if (uid==null) {
await HttpContext.Session.LoadAsync();
var strclicked = HttpContext.Session.GetString("clicked");
if (strclicked!=null) clicked = strclicked.Split(':').Select(c=>long.Parse(c)).ToArray();
if (clicked==null) clicked = new long [0];
}
else clicked = DbContext.DimissClicked.Where(d=>d.UserId == uid).Select(d=>d.NotificationId).ToArray();
var notes = DbContext.Notification.Where(
n=> !clicked.Contains(n.Id)
);
this.Notify(notes);
ViewData["HaircutCommandCount"] = DbContext.HairCutQueries.Where(
q=>q.ClientId == uid && q.Status < QueryStatus.Failed
).Count();
var toShow = DbContext.Activities
.Include(a=>a.Forms)
.Include(a=>a.Parent)
.Include(a=>a.Children)
.Where(a=>!a.Hidden)
.Where(a=>a.ParentCode==id)
.OrderByDescending(a=>a.Rate).ToList();
foreach (var a in toShow) {
a.Children=a.Children.Where(c => !c.Hidden).ToList();
}
return View(toShow);
//if (id==null) {
// Workaround
// NotImplementedException: Remotion.Linq.Clauses.ResultOperators.ConcatResultOperator
//
// Use Concat()| whatever to do left outer join on ToArray() or ToList(), not on IQueryable
// var legacy = DbContext.Activities.Include(a=>a.Forms).Include(a=>a.Children).Where(a=> !a.Hidden).Where(a=> a.ParentCode==null).ToArray();
// OMG
// var hiddenchildren = DbContext.Activities
// .Include(a=>a.Forms).Include(a=>a.Children)
// .Where(a=> a.Parent.Hidden && !a.Hidden).ToArray();
// return View(legacy.Concat(hiddenchildren).OrderByDescending(a=>a.Rate));
// }
}
public async Task<IActionResult> About()
{
FileInfo fi = new FileInfo("wwwroot/version");
return View("About",fi.Exists ? _localizer["Version logicielle: "] + await fi.OpenText().ReadToEndAsync() : _localizer["Aucune information sur la version logicielle n'est publiée."]);
}
public IActionResult Privacy()
{
return View();
}
public IActionResult AboutMarkdown()
{
return View();
}
public IActionResult Contact()
{
return View();
}
public ActionResult Chat()
{
if (User.Identity.IsAuthenticated) {
ViewBag.IsAuthenticated=true;
string uid = User.GetUserId();
ViewBag.Contacts = DbContext.Contacts.Where(c=>c.OwnerId == uid)
;
} else ViewBag.IsAuthenticated=false;
return View();
}
public IActionResult Error()
{
var feature = this.HttpContext.Features.Get<IExceptionHandlerFeature>();
return View("~/Views/Shared/Error.cshtml", feature?.Error);
}
public IActionResult Status(int id)
{
ViewBag.StatusCode = id;
return View("~/Views/Shared/Status.cshtml");
}
public IActionResult Todo()
{
User.GetUserId();
return View();
}
public IActionResult VideoChat()
{
return View();
}
public IActionResult Audio()
{
return View();
}
}
}

View File

@ -0,0 +1,120 @@
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.Data.Entity;
using Yavsc.Models;
using Yavsc.Models.Relationship;
namespace Yavsc.Controllers
{
public class HyperLinkController : Controller
{
private ApplicationDbContext _context;
public HyperLinkController(ApplicationDbContext context)
{
_context = context;
}
// GET: HyperLink
public async Task<IActionResult> Index()
{
return View(await _context.Links.ToListAsync());
}
// GET: HyperLink/Details/5
public async Task<IActionResult> Details(string id)
{
if (id == null)
{
return HttpNotFound();
}
HyperLink hyperLink = await _context.Links.SingleAsync(m => m.HRef == id);
if (hyperLink == null)
{
return HttpNotFound();
}
return View(hyperLink);
}
// GET: HyperLink/Create
public IActionResult Create()
{
return View();
}
// POST: HyperLink/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(HyperLink hyperLink)
{
if (ModelState.IsValid)
{
_context.Links.Add(hyperLink);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(hyperLink);
}
// GET: HyperLink/Edit/5
public async Task<IActionResult> Edit(string id)
{
if (id == null)
{
return HttpNotFound();
}
HyperLink hyperLink = await _context.Links.SingleAsync(m => m.HRef == id);
if (hyperLink == null)
{
return HttpNotFound();
}
return View(hyperLink);
}
// POST: HyperLink/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(HyperLink hyperLink)
{
if (ModelState.IsValid)
{
_context.Update(hyperLink);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(hyperLink);
}
// GET: HyperLink/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(string id)
{
if (id == null)
{
return HttpNotFound();
}
HyperLink hyperLink = await _context.Links.SingleAsync(m => m.HRef == id);
if (hyperLink == null)
{
return HttpNotFound();
}
return View(hyperLink);
}
// POST: HyperLink/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(string id)
{
HyperLink hyperLink = await _context.Links.SingleAsync(m => m.HRef == id);
_context.Links.Remove(hyperLink);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
}
}

View File

@ -0,0 +1,157 @@
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
using Yavsc.Models;
using Yavsc.Server.Models.IT.SourceCode;
using Yavsc.Helpers;
namespace Yavsc.Controllers
{
[Authorize("AdministratorOnly")]
public class GitController : Controller
{
private ApplicationDbContext _context;
public GitController(ApplicationDbContext context)
{
_context = context;
}
[Route("~/Git/sources/{*path}")]
public IActionResult Sources (string path)
{
if (path == null)
{
return HttpNotFound();
}
/*
GitRepositoryReference gitRepositoryReference = await _context.GitRepositoryReference.SingleAsync(m => m.Path == path);
if (gitRepositoryReference == null)
{
return HttpNotFound();
}
*/
var info = Startup.GitOptions.FileProvider.GetFileInfo(path);
if (!info.Exists)
return HttpNotFound();
var stream = info.CreateReadStream();
if (path.EndsWith(".ansi.log"))
{
var accept = Request.Headers["Accept"];
if (accept.Any(v => v.Split(',').Contains("text/html")))
{
return File(AnsiToHtmlEncoder.GetStream(stream),"text/html");
}
return File(stream,"text/text");
}
if (path.EndsWith(".html")) return File(stream,"text/html");
if (path.EndsWith(".cshtml")) return File(stream,"text/razor-html-csharp");
if (path.EndsWith(".cs")) return File(stream,"text/csharp");
return File(stream,"application/octet-stream");
}
// GET: Git
public async Task<IActionResult> Index()
{
var applicationDbContext = _context.GitRepositoryReference.Include(g => g.Owner);
return View(await applicationDbContext.ToListAsync());
}
// GET: Git/Details/5
public async Task<IActionResult> Details(long id)
{
GitRepositoryReference gitRepositoryReference = await _context.GitRepositoryReference.SingleAsync(m => m.Id == id);
if (gitRepositoryReference == null)
{
return HttpNotFound();
}
return View(gitRepositoryReference);
}
// GET: Git/Create
public IActionResult Create()
{
return View();
}
// POST: Git/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(GitRepositoryReference gitRepositoryReference)
{
gitRepositoryReference.OwnerId = User.GetUserId();
if (ModelState.IsValid)
{
_context.GitRepositoryReference.Add(gitRepositoryReference);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewData["OwnerId"] = new SelectList(_context.ApplicationUser, "Id", "Owner", gitRepositoryReference.OwnerId);
return View(gitRepositoryReference);
}
// GET: Git/Edit/5
public async Task<IActionResult> Edit(long id)
{
GitRepositoryReference gitRepositoryReference = await _context.GitRepositoryReference.SingleAsync(m => m.Id == id);
if (gitRepositoryReference == null)
{
return HttpNotFound();
}
ViewBag.OwnerId = new SelectList(_context.ApplicationUser, "Id", "Owner", gitRepositoryReference.OwnerId);
return View(gitRepositoryReference);
}
// POST: Git/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(GitRepositoryReference gitRepositoryReference)
{
if (ModelState.IsValid)
{
_context.Update(gitRepositoryReference);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewData["OwnerId"] = new SelectList(_context.ApplicationUser, "Id", "Owner", gitRepositoryReference.OwnerId);
return View(gitRepositoryReference);
}
// GET: Git/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(string id)
{
if (id == null)
{
return HttpNotFound();
}
GitRepositoryReference gitRepositoryReference = await _context.GitRepositoryReference.SingleAsync(m => m.Path == id);
if (gitRepositoryReference == null)
{
return HttpNotFound();
}
return View(gitRepositoryReference);
}
// POST: Git/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(string id)
{
GitRepositoryReference gitRepositoryReference = await _context.GitRepositoryReference.SingleAsync(m => m.Path == id);
_context.GitRepositoryReference.Remove(gitRepositoryReference);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
}
}

View File

@ -0,0 +1,169 @@
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
using Microsoft.Extensions.Logging;
using Yavsc.Models;
using Yavsc.Server.Models.IT;
using Microsoft.AspNet.Authorization;
using Yavsc.Server.Helpers;
using Yavsc.Models.Workflow;
using Yavsc.Models.Payment;
using Yavsc.Server.Models.IT.SourceCode;
using Microsoft.Extensions.Localization;
namespace Yavsc.Controllers
{
[Authorize("AdministratorOnly")]
public class ProjectController : Controller
{
private ApplicationDbContext _context;
ILogger _logger;
IStringLocalizer<Yavsc.Resources.YavscLocalisation> _localizer;
public ProjectController(ApplicationDbContext context,
ILoggerFactory loggerFactory,
IStringLocalizer<Yavsc.Resources.YavscLocalisation> localizer
)
{
_context = context;
_localizer = localizer;
_logger = loggerFactory.CreateLogger<ProjectController>();
}
// GET: Project
public async Task<IActionResult> Index()
{
var applicationDbContext = _context.Projects.Include(p => p.Client).Include(p => p.Context).Include(p => p.PerformerProfile).Include(p => p.Regularisation).Include(p => p.Repository);
return View(await applicationDbContext.ToListAsync());
}
// GET: Project/Details/5
public async Task<IActionResult> Details(long? id)
{
if (id == null)
{
return HttpNotFound();
}
Project project = await _context.Projects.SingleAsync(m => m.Id == id);
if (project == null)
{
return HttpNotFound();
}
return View(project);
}
// GET: Project/Create
public IActionResult Create()
{
ViewBag.ClientIdItems = _context.ApplicationUser.CreateSelectListItems<ApplicationUser>(
u => u.Id, u => u.UserName);
ViewBag.OwnerIdItems = _context.ApplicationUser.CreateSelectListItems<ApplicationUser>(
u => u.Id, u => u.UserName);
ViewBag.ActivityCodeItems = _context.Activities.CreateSelectListItems<Activity>(
a => a.Code, a => a.Name);
ViewBag.PerformerIdItems = _context.Performers.Include(p=>p.Performer).CreateSelectListItems<PerformerProfile>(p => p.PerformerId, p => p.Performer.UserName);
ViewBag.PaymentIdItems = _context.PayPalPayments.CreateSelectListItems<PayPalPayment>
(p => p.OrderReference, p => $"{p.Executor.UserName} {p.PaypalPayerId} {p.OrderReference}");
ViewBag.Status = typeof(Yavsc.QueryStatus).CreateSelectListItems(null);
ViewBag.RepositoryItems = _context.GitRepositoryReference.CreateSelectListItems<GitRepositoryReference>(
u => u.Id.ToString(), u => u.ToString());
return View();
}
// POST: Project/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Project project)
{
if (ModelState.IsValid)
{
_context.Projects.Add(project);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.ClientIdItems = _context.ApplicationUser.CreateSelectListItems<ApplicationUser>(
u => u.Id, u => u.UserName, project.ClientId);
ViewBag.OwnerIdItems = _context.ApplicationUser.CreateSelectListItems<ApplicationUser>(
u => u.Id, u => u.UserName, project.OwnerId);
ViewBag.ActivityCodeItems = _context.Activities.CreateSelectListItems<Activity>(
a => a.Code, a => a.Name, project.ActivityCode);
ViewBag.PerformerIdItems = _context.Performers.Include(p=>p.Performer).CreateSelectListItems<PerformerProfile>(p => p.PerformerId, p => p.Performer.UserName, project.PerformerId);
ViewBag.PaymentIdItems = _context.PayPalPayments.CreateSelectListItems<PayPalPayment>
(p => p.OrderReference, p => $"{p.Executor.UserName} {p.PaypalPayerId} {p.OrderReference}", project.PaymentId);
return View(project);
}
// GET: Project/Edit/5
public async Task<IActionResult> Edit(long? id)
{
if (id == null)
{
return HttpNotFound();
}
Project project = await _context.Projects.SingleAsync(m => m.Id == id);
if (project == null)
{
return HttpNotFound();
}
/* ViewBag.ClientId = new SelectList(_context.ApplicationUser, "Id", "Client", project.ClientId);
ViewBag.ActivityCodeItems = new SelectList(_context.Activities, "Code", "Context", project.ActivityCode);
ViewBag.PerformerId = new SelectList(_context.Performers, "PerformerId", "PerformerProfile", project.PerformerId);
ViewBag.PaymentId = new SelectList(_context.PayPalPayments, "CreationToken", "Regularisation", project.PaymentId);
ViewBag.Name = new SelectList(_context.GitRepositoryReference, "Path", "Repository", project.Name);
*/
ViewBag.Status = Yavsc.Extensions.EnumExtensions.GetSelectList(typeof(QueryStatus), _localizer, project.Status);
ViewBag.Repository = new SelectList(_context.GitRepositoryReference, "Path", "Repository", project.Repository);
return View(project);
}
// POST: Project/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(Project project)
{
if (ModelState.IsValid)
{
_context.Update(project);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(project);
}
// GET: Project/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(long? id)
{
if (id == null)
{
return HttpNotFound();
}
Project project = await _context.Projects.SingleAsync(m => m.Id == id);
if (project == null)
{
return HttpNotFound();
}
return View(project);
}
// POST: Project/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(long id)
{
Project project = await _context.Projects.SingleAsync(m => m.Id == id);
_context.Projects.Remove(project);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
}
}

View File

@ -0,0 +1,140 @@
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.Data.Entity;
using Yavsc.Models;
using Yavsc.Models.IT.Fixing;
using Yavsc.Models.IT.Evolution;
using System.Linq;
using Yavsc.Server.Helpers;
using System.Collections.Generic;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Extensions.Localization;
namespace Yavsc.Controllers
{
public class BugController : Controller
{
ApplicationDbContext _context;
IStringLocalizer<BugController> _localizer;
public BugController(ApplicationDbContext context, IStringLocalizer<BugController> localizer )
{
_context = context;
_localizer = localizer;
}
// GET: Bug
public async Task<IActionResult> Index()
{
return View(await _context.Bug.ToListAsync());
}
// GET: Bug/Details/5
public async Task<IActionResult> Details(long? id)
{
if (id == null)
{
return HttpNotFound();
}
Bug bug = await _context.Bug.SingleAsync(m => m.Id == id);
if (bug == null)
{
return HttpNotFound();
}
return View(bug);
}
// GET: Bug/Create
public IActionResult Create()
{
ViewBag.Features = Features(_context);
ViewBag.Statuses = Statuses(default(BugStatus));
return View();
}
IEnumerable<SelectListItem> Statuses(BugStatus ?status) =>
typeof(Yavsc.Models.IT.Fixing.BugStatus).CreateSelectListItems(status);
IEnumerable<SelectListItem> Features(ApplicationDbContext context) =>
context.Feature.CreateSelectListItems<Feature>(f => f.Id.ToString(), f => f.ShortName, null)
.AddNull(_localizer["noAttachedFID"]);
// POST: Bug/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Bug bug)
{
if (ModelState.IsValid)
{
_context.Bug.Add(bug);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(bug);
}
// GET: Bug/Edit/5
public async Task<IActionResult> Edit(long? id)
{
if (id == null)
{
return HttpNotFound();
}
Bug bug = await _context.Bug.SingleAsync(m => m.Id == id);
if (bug == null)
{
return HttpNotFound();
}
ViewBag.Features = Features(_context);
ViewBag.Statuses = Statuses(bug.Status);
return View(bug);
}
// POST: Bug/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(Bug bug)
{
if (ModelState.IsValid)
{
_context.Update(bug);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(bug);
}
// GET: Bug/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(long? id)
{
if (id == null)
{
return HttpNotFound();
}
Bug bug = await _context.Bug.SingleAsync(m => m.Id == id);
if (bug == null)
{
return HttpNotFound();
}
return View(bug);
}
// POST: Bug/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(long id)
{
Bug bug = await _context.Bug.SingleAsync(m => m.Id == id);
_context.Bug.Remove(bug);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
}
}

View File

@ -0,0 +1,130 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
namespace Yavsc.Controllers
{
using Models;
using Models.IT.Evolution;
public class FeatureController : Controller
{
private ApplicationDbContext _context;
public FeatureController(ApplicationDbContext context)
{
_context = context;
}
// GET: Feature
public async Task<IActionResult> Index()
{
return View(await _context.Feature.ToListAsync());
}
// GET: Feature/Details/5
public async Task<IActionResult> Details(long? id)
{
if (id == null)
{
return HttpNotFound();
}
Feature feature = await _context.Feature.SingleAsync(m => m.Id == id);
if (feature == null)
{
return HttpNotFound();
}
return View(feature);
}
// GET: Feature/Create
public IActionResult Create()
{
return View();
}
// POST: Feature/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Feature feature)
{
if (ModelState.IsValid)
{
_context.Feature.Add(feature);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(feature);
}
// GET: Feature/Edit/5
public async Task<IActionResult> Edit(long? id)
{
if (id == null)
{
return HttpNotFound();
}
Feature feature = await _context.Feature.SingleAsync(m => m.Id == id);
if (feature == null)
{
return HttpNotFound();
}
var featureStatusEnumType = typeof(FeatureStatus);
var fsstatuses = new List<SelectListItem>();
foreach (var v in featureStatusEnumType.GetEnumValues())
{
fsstatuses.Add(new SelectListItem { Value = v.ToString(), Text = featureStatusEnumType.GetEnumName(v) });
}
ViewBag.Statuses = fsstatuses;
return View(feature);
}
// POST: Feature/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(Feature feature)
{
if (ModelState.IsValid)
{
_context.Update(feature);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(feature);
}
// GET: Feature/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(long? id)
{
if (id == null)
{
return HttpNotFound();
}
Feature feature = await _context.Feature.SingleAsync(m => m.Id == id);
if (feature == null)
{
return HttpNotFound();
}
return View(feature);
}
// POST: Feature/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(long id)
{
Feature feature = await _context.Feature.SingleAsync(m => m.Id == id);
_context.Feature.Remove(feature);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
}
}

View File

@ -0,0 +1,12 @@
using Microsoft.AspNet.Mvc;
namespace Yavsc.Controllers
{
public class TestController: Controller
{
public IActionResult Index()
{
return View();
}
}
}