This commit is contained in:
Paul Schneider 2026-02-14 16:54:27 +00:00
commit 45514010f2
3505 changed files with 154 additions and 523 deletions

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,228 @@
/*
Copyright (c) 2024 HigginsSoft, Alexander Higgins - https://github.com/alexhiggins732/
Copyright (c) 2018, Brock Allen & Dominick Baier. All rights reserved.
Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
Source code and license this software can be found
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
*/
using System.Security.Claims;
using IdentityModel;
using IdentityServer8;
using IdentityServer8.Events;
using IdentityServer8.Services;
using IdentityServer8.Stores;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc;
using Yavsc.Extensions;
using Yavsc.Interfaces;
using Yavsc.Models;
namespace IdentityServerHost.Quickstart.UI;
[SecurityHeaders]
[AllowAnonymous]
public class ExternalController : Controller
{
private readonly IIdentityServerInteractionService _interaction;
private readonly IClientStore _clientStore;
private readonly ILogger<ExternalController> _logger;
private readonly IEventService _events;
private IExternalIdentityManager _users;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly RoleManager<IdentityRole> _roleManager;
private readonly ApplicationDbContext _dbContext;
public ExternalController(
IIdentityServerInteractionService interaction,
IClientStore clientStore,
IEventService events,
ILogger<ExternalController> logger,
IExternalIdentityManager externalIdentityProviderManager,
SignInManager<ApplicationUser> signInManager,
ApplicationDbContext dbContext,
RoleManager<IdentityRole> roleManager
)
{
// if the TestUserStore is not in DI, then we'll just use the global users collection
// this is where you would plug in your own custom identity management library (e.g. ASP.NET Identity)
_users = externalIdentityProviderManager;
_interaction = interaction;
_clientStore = clientStore;
_logger = logger;
_events = events;
_signInManager = signInManager;
_roleManager = roleManager;
_dbContext = dbContext;
}
/// <summary>
/// initiate roundtrip to external authentication provider
/// </summary>
[HttpGet]
public IActionResult Challenge(string scheme, string returnUrl)
{
if (string.IsNullOrEmpty(returnUrl)) returnUrl = "~/";
// validate returnUrl - either it is a valid OIDC URL or back to a local page
if (Url.IsLocalUrl(returnUrl) == false && _interaction.IsValidReturnUrl(returnUrl) == false)
{
// user might have clicked on a malicious link - should be logged
throw new Exception("invalid return URL");
}
// start challenge and roundtrip the return URL and scheme
var props = new AuthenticationProperties
{
RedirectUri = Url.Action(nameof(Callback)),
Items =
{
{ "returnUrl", returnUrl },
{ "scheme", scheme },
}
};
return Challenge(props, scheme);
}
/// <summary>
/// Post processing of external authentication
/// </summary>
[HttpGet]
public async Task<IActionResult> Callback()
{
// read external identity from the temporary cookie
var result = await HttpContext.AuthenticateAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme);
if (result?.Succeeded != true)
{
throw new Exception("External authentication error");
}
if (_logger.IsEnabled(LogLevel.Debug))
{
var externalClaims = result.Principal.Claims.Select(c => $"{c.Type}: {c.Value}");
_logger.LogDebug("External claims: {@claims}", externalClaims);
}
// lookup our user and external provider info
var (user, provider, providerUserId, claims) = await FindUserFromExternalProvider(result);
if (user == null)
{
// this might be where you might initiate a custom workflow for user registration
// in this sample we don't show how that would be done, as our sample implementation
// simply auto-provisions new external user
user = AutoProvisionUser(provider, providerUserId, claims);
}
// this allows us to collect any additional claims or properties
// for the specific protocols used and store them in the local auth cookie.
// this is typically used to store data needed for signout from those protocols.
var additionalLocalClaims = new List<Claim>();
var localSignInProps = new AuthenticationProperties();
ProcessLoginCallback(result, additionalLocalClaims, localSignInProps);
// issue authentication cookie for user
var isuser = new IdentityServerUser(user.Id)
{
DisplayName = user.UserName,
IdentityProvider = provider,
AdditionalClaims = additionalLocalClaims
};
await HttpContext.SignInAsync(isuser, localSignInProps);
//await HttpContext.SignInAsync(user, _roleManager, false, _dbContext);
// delete temporary cookie used during external authentication
await HttpContext.SignOutAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme);
// retrieve return URL
var returnUrl = result.Properties.Items["returnUrl"] ?? "~/";
// check if external login is in the context of an OIDC request
var context = await _interaction.GetAuthorizationContextAsync(returnUrl);
await _events.RaiseAsync(new UserLoginSuccessEvent(provider, providerUserId, user.Id, user.UserName, true, context?.Client.ClientId));
if (context != null)
{
if (context.IsNativeClient())
{
// The client is native, so this change in how to
// return the response is for better UX for the end user.
return this.LoadingPage("Redirect", returnUrl);
}
}
return Redirect(returnUrl);
}
private async Task<(ApplicationUser user,
string provider,
string providerUserId,
IEnumerable<Claim> claims)>
FindUserFromExternalProvider(AuthenticateResult result)
{
var externalUser = result.Principal;
// try to determine the unique id of the external user (issued by the provider)
// the most common claim type for that are the sub claim and the NameIdentifier
// depending on the external provider, some other claim type might be used
var userIdClaim = externalUser.FindFirst(JwtClaimTypes.Subject) ??
externalUser.FindFirst(ClaimTypes.NameIdentifier) ??
throw new Exception("Unknown userid");
// remove the user id claim so we don't include it as an extra claim if/when we provision the user
var claims = externalUser.Claims.ToList();
claims.Remove(userIdClaim);
var provider = result.Properties.Items["scheme"];
var providerUserId = userIdClaim.Value;
// find external user
ApplicationUser? user = await _users.FindByExternaleProviderAsync (provider, providerUserId);
return (user, provider, providerUserId, claims);
}
/// <summary>
/// Register a new user by external id
/// </summary>
/// <param name="provider"></param>
/// <param name="providerUserId"></param>
/// <param name="claims"></param>
/// <returns></returns>
private ApplicationUser AutoProvisionUser(string provider, string providerUserId, IEnumerable<Claim> claims)
{
var user = _users.AutoProvisionUser(provider, providerUserId, claims.ToList());
return user;
}
// if the external login is OIDC-based, there are certain things we need to preserve to make logout work
// this will be different for WS-Fed, SAML2p or other protocols
private void ProcessLoginCallback(AuthenticateResult externalResult, List<Claim> localClaims, AuthenticationProperties localSignInProps)
{
// if the external system sent a session id claim, copy it over
// so we can use it for single sign-out
var sid = externalResult.Principal.Claims.FirstOrDefault(x => x.Type == JwtClaimTypes.SessionId);
if (sid != null)
{
localClaims.Add(new Claim(JwtClaimTypes.SessionId, sid.Value));
}
// if the external provider issued an id_token, we'll keep it for signout
var idToken = externalResult.Properties.GetTokenValue("id_token");
if (idToken != null)
{
localSignInProps.StoreTokens(new[] { new AuthenticationToken { Name = "id_token", Value = idToken } });
}
}
}

View file

@ -0,0 +1,22 @@
/*
Copyright (c) 2024 HigginsSoft, Alexander Higgins - https://github.com/alexhiggins732/
Copyright (c) 2018, Brock Allen & Dominick Baier. All rights reserved.
Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
Source code and license this software can be found
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
*/
using System.Security.Claims;
using Yavsc.Models;
namespace Yavsc.Interfaces;
public interface IExternalIdentityManager
{
ApplicationUser AutoProvisionUser(string provider, string providerUserId, List<Claim> claims);
Task<ApplicationUser?> FindByExternaleProviderAsync(string provider, string providerUserId);
}

View file

@ -0,0 +1,763 @@
using System.Security.Claims;
using System.IO;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Yavsc.Models.Workflow;
using Yavsc.Helpers;
using Yavsc.Models.Relationship;
using Yavsc.Models.Bank;
using Yavsc.ViewModels.Calendar;
using Yavsc.Models;
using Yavsc.Services;
using Yavsc.ViewModels.Manage;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Authorization;
using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
[Authorize]
public class ManageController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ILogger _logger;
private readonly SiteSettings _siteSettings;
private readonly ApplicationDbContext _dbContext;
private readonly GoogleAuthSettings _googleSettings;
private readonly PayPalSettings _payPalSettings;
private readonly IYavscMessageSender _GCMSender;
private readonly SIRENChecker _cchecker;
private readonly IStringLocalizer _SR;
private readonly CompanyInfoSettings _cinfoSettings;
readonly ICalendarManager _calendarManager;
public ManageController(
ApplicationDbContext context,
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender,
IYavscMessageSender GCMSender,
IOptions<SiteSettings> siteSettings,
IOptions<GoogleAuthSettings> googleSettings,
IOptions<PayPalSettings> paypalSettings,
IOptions<CompanyInfoSettings> cinfoSettings,
IStringLocalizer<ManageController> 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."]
: message == ManageMessageId.SetFullNameSuccess ? _SR["Votre nom complet a été renseigné."]
: "";
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,
Address = user.PostalAddress?.Address
};
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 { 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), new { Message = ManageMessageId.UnsetTwoFactorSuccess });
}
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 async Task<IActionResult> SetGoogleCalendar(string returnUrl, string pageToken)
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
var calendars = await _calendarManager.GetCalendarsAsync(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.FindFirstValue(ClaimTypes.NameIdentifier);
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.FindFirstValue(ClaimTypes.NameIdentifier);
var user = _dbContext.Users.Include(u=>u.BankInfo)
.Single(u=>u.Id == uid);
if (user.BankInfo.Any(
bi => bi.Equals(model)
)) return BadRequest(new { message = "data already present" });
user.BankInfo.Add(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(new SetFullNameViewModel { FullName = user.FullName });
}
[HttpPost]
public async Task<IActionResult> SetFullName(SetFullNameViewModel model)
{
if (ModelState.IsValid)
{
var user = await _userManager.FindByIdAsync(User.GetUserId());
user.FullName = model.FullName;
await _userManager.UpdateAsync(user);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.SetFullNameSuccess });
}
return View(model);
}
//
// 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 SetUserName()
{
return View(new SetUserNameViewModel() { UserName = User.Identity.Name });
}
[HttpPost]
public async Task<IActionResult> SetUserName(SetUserNameViewModel 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.UserName);
if (result.Succeeded)
{
// Renames the blog files
var userdirinfo = new DirectoryInfo(
Path.Combine(_siteSettings.Blog,
oldUserName));
var newdir = Path.Combine(_siteSettings.Blog,
model.UserName);
if (userdirinfo.Exists)
userdirinfo.MoveTo(newdir);
// Renames the Avatars files
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.UserName+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);
ViewData["ShowRemoveButton"] = user.PasswordHash != null || userLogins.Count > 1;
return View(new ManageLoginsViewModel
{
CurrentLogins = userLogins
});
}
//
// 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.IsInMsRole("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,
UnsetTwoFactorSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
RemovePhoneSuccess,
SetActivitySuccess,
UnsetActivitySuccess,
AvatarUpdateSuccess,
IdentityUpdateSuccess,
SetBankInfoSuccess,
SetAddressSuccess,
SetMonthlyEmailSuccess,
SetFullNameSuccess,
Error
}
private async Task<ApplicationUser> GetCurrentUserAsync()
{
return await _dbContext.Users.Include(u => u.PostalAddress)
.FirstOrDefaultAsync(u => u.Id == User.GetUserId());
}
#endregion
[HttpGet]
public async Task <IActionResult> SetAddress()
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
var user = await _dbContext.Users.Include(u=>u.PostalAddress).SingleAsync(u=>u.Id==uid);
ViewBag.GoogleSettings = _googleSettings;
return View (user.PostalAddress ?? new Location());
}
[HttpPost]
public async Task <IActionResult> SetAddress(Location model)
{
if (ModelState.IsValid) {
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
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(model);
}
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,127 @@
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Yavsc.Models;
namespace Yavsc.Controllers
{
[Authorize("AdministratorOnly")]
public class UsersController : Controller
{
private readonly 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 NotFound();
}
ApplicationUser applicationUser = await _context.ApplicationUser.SingleAsync(m => m.Id == id);
if (applicationUser == null)
{
return NotFound();
}
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 NotFound();
}
ApplicationUser applicationUser = await _context.ApplicationUser.SingleAsync(m => m.Id == id);
if (applicationUser == null)
{
return NotFound();
}
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 NotFound();
}
ApplicationUser applicationUser = await _context.ApplicationUser.SingleAsync(m => m.Id == id);
if (applicationUser == null)
{
return NotFound();
}
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,209 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Yavsc.Abstract.Identity;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Server.Helpers;
using Yavsc.ViewModels;
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 _dbContext;
public AdministrationController(UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager,
ApplicationDbContext context)
{
_userManager = userManager;
_roleManager = roleManager;
this._dbContext = context;
}
public async Task<IActionResult> Role(string id)
{
var role = await _roleManager.FindByIdAsync(id);
if (role == null) return NotFound();
RoleUserCollection roleUserCollection = new RoleUserCollection
{
Id = id,
Name = role.Name,
Users = (await this._userManager.GetUsersInRoleAsync(role.Name))
.Select(u => new UserInfo (id, u.UserName, u.Email, u.Avatar)).ToArray()
};
return View(roleUserCollection);
}
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.IsInMsRole(Constants.AdminGroupName))
{
return Ok(new { message = "you already got it." });
}
return NotFound();
}
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);
}
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("AdministratorOnly")]
[Produces("application/json")]
public async Task<IActionResult> Index()
{
var adminCount = await _userManager.GetUsersInRoleAsync(
Constants.AdminGroupName);
var userCount = await _dbContext.Users.CountAsync();
var youAreAdmin = await _userManager.IsInRoleAsync(
await _userManager.FindByIdAsync(User.GetUserId()),
Constants.AdminGroupName);
var roles = await _roleManager.Roles.Select(x => new RoleInfo
{
Id = x.Id,
Name = x.Name
}).ToArrayAsync();
foreach (var role in roles)
{
var uinrole = await _userManager.GetUsersInRoleAsync(role.Name);
role.UserCount = uinrole.Count();
}
var assembly = GetType().Assembly;
ViewBag.ThisAssembly = assembly.FullName;
ViewBag.RunTimeVersion = assembly.ImageRuntimeVersion;
var rolesArray = roles.ToArray();
return View(new AdminViewModel
{
Roles = rolesArray,
AdminCount = adminCount.Count,
YouAreAdmin = youAreAdmin,
UserCount = userCount
});
}
[Authorize("AdministratorOnly")]
public IActionResult Enroll(string roleName)
{
ViewBag.UserId = new SelectList(_dbContext.Users, "Id", "UserName");
return View(new EnrolerViewModel { RoleName = roleName });
}
[Authorize("AdministratorOnly")]
[HttpPost()]
public async Task<IActionResult> Enroll(EnrolerViewModel model)
{
if (ModelState.IsValid)
{
var newAdmin = await _dbContext.Users.FirstOrDefaultAsync(u => u.Id == model.EnroledUserId);
if (newAdmin == null) return NotFound();
var addToRoleResult = await _userManager.AddToRoleAsync(newAdmin, model.RoleName);
if (addToRoleResult.Succeeded)
{
return RedirectToAction("Index");
}
AddErrors(addToRoleResult);
}
ViewBag.UserId = new SelectList(_dbContext.Users, "Id", "UserName");
return View(model);
}
[Authorize("AdministratorOnly")]
public async Task<IActionResult> Fire(string roleName, string userId)
{
var user = await _dbContext.Users.FirstOrDefaultAsync(u => u.Id == userId);
if (user == null) return NotFound();
return View(new FireViewModel { RoleName = roleName, EnroledUserId = userId, EnroledUserName = user.UserName });
}
[Authorize("AdministratorOnly")]
[HttpPost()]
public async Task<IActionResult> Fire(FireViewModel model)
{
if (ModelState.IsValid)
{
var oldEnroled = await _dbContext.Users.FirstOrDefaultAsync(u => u.Id == model.EnroledUserId);
if (oldEnroled == null) return NotFound();
var removeFromRole = await _userManager.RemoveFromRoleAsync(oldEnroled, model.RoleName);
if (removeFromRole.Succeeded)
{
return RedirectToAction("Index");
}
AddErrors(removeFromRole);
}
ViewBag.UserId = new SelectList(_dbContext.Users, "Id", "UserName");
return View(model);
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
}
}

View file

@ -0,0 +1,147 @@
using IdentityServer8.EntityFramework.DbContexts;
using IdentityServer8.EntityFramework.Entities;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Auth;
using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
[Authorize("AdministratorOnly")]
public class ClientController : Controller
{
private readonly ConfigurationDbContext _context;
public ClientController(ConfigurationDbContext context)
{
_context = context;
}
// GET: Client
public async Task<IActionResult> Index()
{
return View(await _context.Clients.Include(c=>c.AllowedGrantTypes)
.Include(c=>c.RedirectUris).ToListAsync());
}
// GET: Client/Details/5
public async Task<IActionResult> Details(string id)
{
if (id == null)
{
return NotFound();
}
Client client = await _context.Clients.Include(
c => c.ClientSecrets
).Include(c=>c.AllowedGrantTypes)
.Include(c=>c.RedirectUris)
.SingleAsync(m => m.ClientId == id);
if (client == null)
{
return NotFound();
}
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)
{
if (string.IsNullOrWhiteSpace(client.ClientId))
client.ClientId = Guid.NewGuid().ToString();
_context.Clients.Add(client);
await _context.SaveChangesAsync();
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["AccessTokenType"] = types;
}
// GET: Client/Edit/5
public async Task<IActionResult> Edit(string id)
{
if (id == null)
{
return NotFound();
}
Client client = await _context.Clients.SingleAsync(m => m.ClientId == id);
if (client == null)
{
return NotFound();
}
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();
return RedirectToAction("Index");
}
return View(client);
}
// GET: Client/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(string id)
{
if (id == null)
{
return NotFound();
}
Client client = await _context.Clients.SingleAsync(m => m.ClientId == id);
if (client == null)
{
return NotFound();
}
return View(client);
}
// POST: Client/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(string id)
{
Client client = await _context.Clients.SingleAsync(m => m.ClientId == id);
_context.Clients.Remove(client);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
}
}

View file

@ -0,0 +1,72 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Yavsc.Models;
namespace Yavsc.Controllers
{
[Authorize()]
public class DatabaseController : Controller
{
private readonly ILogger<DatabaseController> logger;
private readonly ApplicationDbContext applicationDbContext;
public DatabaseController(ApplicationDbContext applicationDbContext,
ILoggerFactory loggerFactory)
{
logger = loggerFactory.CreateLogger<DatabaseController>();
this.applicationDbContext = applicationDbContext;
}
public IActionResult GetBlog()
{
return ReturnDbSet(applicationDbContext.BlogSpot);
}
public IActionResult GetUsers()
{
return ReturnDbSet(applicationDbContext.Users);
}
public IActionResult GeActivities()
{
return ReturnDbSet(applicationDbContext.Activities);
}
public IActionResult ImportUsers(String usersJson)
{
return DBSetImportFromJson(applicationDbContext.Users, usersJson);
}
public IActionResult ImportBlog(String blogJson)
{
return DBSetImportFromJson(applicationDbContext.BlogSpot, blogJson);
}
IActionResult ReturnDbSet<T>(DbSet<T> dbSet) where T : class
{
var data = dbSet.ToArray();
return Ok(data);
}
private IActionResult DBSetImportFromJson<T>(DbSet<T> dbSet, string usersJson) where T : class
{
int failures = 0;
var input = JsonConvert.DeserializeObject<T[]>(usersJson);
foreach (var user in input)
{
try
{
dbSet.Add(user);
}
catch (Exception ex)
{
failures++;
}
}
return Ok(failures);
}
}
}

View file

@ -0,0 +1,158 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Yavsc.Models;
using Yavsc.Models.Calendar;
using Yavsc.Server.Models.EMailing;
using Microsoft.AspNetCore.Authorization;
using Yavsc.Server.Settings;
using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Server.Models.Calendar;
using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
[Authorize("AdministratorOnly")]
public class MailingTemplateController : Controller
{
private readonly ApplicationDbContext _context;
private readonly ILogger logger;
public MailingTemplateController(ApplicationDbContext context,
ILoggerFactory loggerFactory)
{
_context = context;
logger = loggerFactory.CreateLogger<MailingTemplateController>();
}
// GET: MailingTemplate
public async Task<IActionResult> Index()
{
var applicationDbContext = _context.MailingTemplate;
return View(await applicationDbContext.ToListAsync());
}
// GET: MailingTemplate/Details/5
public async Task<IActionResult> Details(string id)
{
if (id == null)
{
return NotFound();
}
MailingTemplate mailingTemplate = await _context.MailingTemplate.SingleAsync(m => m.Id == id);
if (mailingTemplate == null)
{
return NotFound();
}
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;
}
private void SetupViewBag()
{
ViewBag.ManagerId = new SelectList(_context.ApplicationUser, "Id", "UserName");
ViewBag.ToSend = GetSelectFromEnum(typeof(Periodicity));
ViewBag.Id = UserPolicies.Criterias.Select(
c => new SelectListItem{ Text = c.Key, Value = c.Key }).ToList();
}
// GET: MailingTemplate/Create
public IActionResult Create()
{
SetupViewBag();
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");
}
SetupViewBag();
return View(mailingTemplate);
}
// GET: MailingTemplate/Edit/5
public async Task<IActionResult> Edit(string id)
{
if (id == null)
{
return NotFound();
}
MailingTemplate mailingTemplate = await _context.MailingTemplate.SingleAsync(m => m.Id == id);
if (mailingTemplate == null)
{
return NotFound();
}
SetupViewBag();
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");
}
SetupViewBag();
return View(mailingTemplate);
}
// GET: MailingTemplate/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(string id)
{
if (id == null)
{
return NotFound();
}
MailingTemplate mailingTemplate = await _context.MailingTemplate.SingleAsync(m => m.Id == id);
if (mailingTemplate == null)
{
return NotFound();
}
return View(mailingTemplate);
}
// POST: MailingTemplate/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(string 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,165 @@
using System.Threading.Tasks;
using Yavsc.ViewModels.Auth;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Yavsc.Models;
using Yavsc.Models.Messaging;
using Microsoft.Extensions.Localization;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
public class AnnouncesController : Controller
{
private readonly ApplicationDbContext _context;
readonly IStringLocalizer<AnnouncesController> _localizer;
readonly 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 NotFound();
}
Announce announce = await _context.Announce.SingleAsync(m => m.Id == id);
if (announce == null)
{
return NotFound();
}
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.IsInMsRole(Constants.AdminGroupName);
ViewBag.IsPerformer = User.IsInMsRole(Constants.PerformerGroupName);
ViewBag.AllowEdit = announce==null || announce.Id<=0 || !_authorizationService.AuthorizeAsync(User,announce,new EditPermission()).IsFaulted;
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)
{
if (ModelState.IsValid)
{
// Only allow admin to create corporate annonces
if (announce.For == Reason.Corporate && ! User.IsInMsRole(Constants.AdminGroupName))
{
ModelState.AddModelError("For", _localizer["YourNotAdmin"]);
return View(announce);
}
// Only allow performers to create ServiceProposal
if (announce.For == Reason.ServiceProposal && ! User.IsInMsRole(Constants.PerformerGroupName))
{
ModelState.AddModelError("For", _localizer["YourNotAPerformer"]);
return View(announce);
}
_context.Announce.Add(announce);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
await SetupView(announce);
return View(announce);
}
// GET: Announces/Edit/5
public async Task<IActionResult> Edit(long? id)
{
if (id == null)
{
return NotFound();
}
Announce announce = await _context.Announce.SingleAsync(m => m.Id == id);
if (announce == null)
{
return NotFound();
}
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 NotFound();
}
Announce announce = await _context.Announce.SingleAsync(m => m.Id == id);
if (announce == null)
{
return NotFound();
}
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,186 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Yavsc.Models;
using Yavsc.ViewModels.Auth;
using Microsoft.AspNetCore.Mvc.Rendering;
using Yavsc.Models.Blog;
using Yavsc.Helpers;
using Microsoft.Extensions.Options;
using Microsoft.EntityFrameworkCore;
using Yavsc.ViewModels.Blog;
using Yavsc.Server.Exceptions;
using Yavsc.Server.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
{
readonly ILogger _logger;
private readonly ApplicationDbContext _context;
private readonly IAuthorizationService _authorizationService;
readonly RequestLocalizationOptions _localisationOptions;
readonly BlogSpotService blogSpotService;
public BlogspotController(
ApplicationDbContext context,
ILoggerFactory loggerFactory,
IAuthorizationService authorizationService,
IOptions<RequestLocalizationOptions> localisationOptions,
BlogSpotService blogSpotService)
{
_context = context;
_logger = loggerFactory.CreateLogger<AccountController>();
_authorizationService = authorizationService;
_localisationOptions = localisationOptions.Value;
this.blogSpotService = blogSpotService;
}
// GET: Blog
[AllowAnonymous]
public async Task<IActionResult> Index(string id, int skip = 0, int take = 25)
{
if (!string.IsNullOrEmpty(id))
{
return View("UserPosts",
await blogSpotService.UserPosts(id, User.GetUserId(),
skip, take));
}
IEnumerable<IBlogPost> index = await this.blogSpotService.Index(User, id, skip, take);
return View(index);
}
[Route("~/Title/{id?}")]
[AllowAnonymous]
[HttpGet]
public IActionResult Title(string id)
{
ViewData["Title"] = id;
return View("Title", blogSpotService.GetTitle(id));
}
private async Task<IEnumerable<BlogPost>> UserPosts(string userName, int pageLen = 10, int pageNum = 0)
{
return await blogSpotService.UserPosts(userName, User.GetUserId(), pageLen, pageNum);
}
// GET: Blog/Details/5
[AllowAnonymous]
public async Task<IActionResult> Details(long? id)
{
if (id == null) return this.NotFound();
try
{
var blog = await blogSpotService.Details(User, id.Value);
ViewData["apicmtctlr"] = "/api/blogcomments";
ViewData["moderatoFlag"] = User.IsInMsRole(Constants.BlogModeratorGroupName);
return View(blog);
}
catch (AuthorizationFailureException ex)
{
return Challenge();
}
}
void SetLangItems()
{
ViewBag.LangItems = _localisationOptions.SupportedUICultures?.Select
(
sc => new SelectListItem { Value = sc.IetfLanguageTag, Text = sc.NativeName, Selected = System.Globalization.CultureInfo.CurrentUICulture == sc }
);
}
// GET: Blog/Create
[Authorize()]
public IActionResult Create(string title)
{
var result = new BlogPostCreateViewModel
{
Title = title
};
SetLangItems();
return View(result);
}
// POST: Blog/Create
[HttpPost, Authorize, ValidateAntiForgeryToken]
public IActionResult Create(BlogPostEditViewModel blogInput)
{
if (ModelState.IsValid)
{
BlogPost post = blogSpotService.Create(User.GetUserId(),
BlogPostEditViewModel.FromViewModel(blogInput));
return RedirectToAction("Index");
}
return View("Edit", blogInput);
}
[Authorize()]
// GET: Blog/Edit/5
public async Task<IActionResult> Edit(long? id)
{
if (id == null)
{
return NotFound();
}
try
{
var blog = await blogSpotService.GetPostForEdition(User, id.Value);
if (blog == null)
{
return NotFound();
}
SetLangItems();
return View(blog);
}
catch (AuthorizationFailureException)
{
return new ChallengeResult();
}
}
// POST: Blog/Edit/5
[HttpPost]
[ValidateAntiForgeryToken, Authorize()]
public async Task<IActionResult> Edit(BlogPostEditViewModel blogEdit)
{
if (ModelState.IsValid)
{
await blogSpotService.Modify(User, blogEdit);
ViewData["StatusMessage"] = "Post modified";
return RedirectToAction("Index");
}
return View(blogEdit);
}
// GET: Blog/Delete/5
[ActionName("Delete"), Authorize()]
public async Task<IActionResult> Delete(long? id)
{
if (id == null)
{
return NotFound();
}
var blog = await blogSpotService.GetBlogPostAsync(id.Value);
if (blog == null)
{
return NotFound();
}
return View(blog);
}
// POST: Blog/Delete/5
[HttpPost, ActionName("Delete"), Authorize("TheAuthor")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(long id)
{
await blogSpotService.Delete(User, id);
return RedirectToAction("Index");
}
}
}

View file

@ -0,0 +1,139 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Relationship;
using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
public class CircleController : Controller
{
private readonly ApplicationDbContext _context;
public CircleController(ApplicationDbContext context)
{
_context = context;
}
// GET: Circle
public async Task<IActionResult> Index()
{
return View(await _context.Circle.Where(c=>c.OwnerId==User.GetUserId()).ToListAsync());
}
// GET: Circle/Details/5
public async Task<IActionResult> Details(long? id)
{
if (id == null)
{
return NotFound();
}
Circle circle = await _context.Circle.SingleAsync(m => m.Id == id);
if (circle == null)
{
return NotFound();
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (uid != circle.OwnerId) return this.Unauthorized();
return View(circle);
}
// GET: Circle/Create
public IActionResult Create()
{
return View(new Circle { OwnerId = User.GetUserId() } );
}
// POST: Circle/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Circle circle)
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (ModelState.IsValid)
{
if (uid != circle.OwnerId)
return this.Unauthorized();
_context.Circle.Add(circle);
await _context.SaveChangesAsync(uid);
return RedirectToAction("Index");
}
return View(circle);
}
// GET: Circle/Edit/5
public async Task<IActionResult> Edit(long? id)
{
if (id == null)
{
return NotFound();
}
Circle circle = await _context.Circle.SingleAsync(m => m.Id == id);
if (circle == null)
{
return NotFound();
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (uid != circle.OwnerId)
return Unauthorized();
return View(circle);
}
// POST: Circle/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(Circle circle)
{
if (ModelState.IsValid)
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (uid != circle.OwnerId) return Unauthorized();
_context.Update(circle);
await _context.SaveChangesAsync(uid);
return RedirectToAction("Index");
}
return View(circle);
}
// GET: Circle/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(long? id)
{
if (id == null)
{
return NotFound();
}
Circle circle = await _context.Circle.SingleAsync(m => m.Id == id);
if (circle == null)
{
return NotFound();
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (uid != circle.OwnerId) return Unauthorized();
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);
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (uid != circle.OwnerId) return Unauthorized();
_context.Circle.Remove(circle);
await _context.SaveChangesAsync(uid);
return RedirectToAction("Index");
}
}
}

View file

@ -0,0 +1,136 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Relationship;
using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
public class CircleMembersController : Controller
{
private readonly ApplicationDbContext _context;
public CircleMembersController(ApplicationDbContext context)
{
_context = context;
}
// GET: CircleMembers
public async Task<IActionResult> Index()
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
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.FindFirstValue(ClaimTypes.NameIdentifier);
CircleMember circleMember = await _context.CircleMembers
.Include(m=>m.Circle)
.FirstOrDefaultAsync(c=>c.CircleId == id);
if (circleMember == null)
{
return NotFound();
}
return View(circleMember);
}
// GET: CircleMembers/Create
public IActionResult Create()
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
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.FindFirstValue(ClaimTypes.NameIdentifier);
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.FindFirstValue(ClaimTypes.NameIdentifier);
CircleMember circleMember = await _context.CircleMembers
.Include(m=>m.Member)
.SingleOrDefaultAsync(m => m.CircleId == id && m.MemberId == uid);
if (circleMember == null)
{
return NotFound();
}
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.FindFirstValue(ClaimTypes.NameIdentifier);
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 NotFound();
}
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,133 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Blog;
using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
/// <summary>
/// Comment some post.
/// </summary>
public class CommentsController : Controller
{
private readonly 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 NotFound();
}
Comment comment = await _context.Comment.SingleAsync(m => m.Id == id);
if (comment == null)
{
return NotFound();
}
return View(comment);
}
// GET: Comments/Create
public IActionResult Create()
{
ViewData["ReceiverId"] = 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["ReceiverId"] = new SelectList(_context.BlogSpot, "Id", "Post", comment.ReceiverId);
return View(comment);
}
// GET: Comments/Edit/5
public async Task<IActionResult> Edit(long? id)
{
if (id == null)
{
return NotFound();
}
Comment comment = await _context.Comment.SingleAsync(m => m.Id == id);
if (comment == null)
{
return NotFound();
}
ViewData["ReceiverId"] = new SelectList(_context.BlogSpot, "Id", "Post", comment.ReceiverId);
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["ReceiverId"] = new SelectList(_context.BlogSpot, "Id", "Post", comment.ReceiverId);
return View(comment);
}
// GET: Comments/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(long? id)
{
if (id == null)
{
return NotFound();
}
Comment comment = await _context.Comment.SingleAsync(m => m.Id == id);
if (comment == null)
{
return NotFound();
}
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,75 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Mvc;
namespace Yavsc.Controllers
{
using Microsoft.EntityFrameworkCore;
using Models;
using Models.Identity;
public class DevicesController : Controller
{
private readonly ApplicationDbContext _context;
public DevicesController(ApplicationDbContext context)
{
_context = context;
}
// GET: GCMDevices
public async Task<IActionResult> Index()
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
var applicationDbContext = _context.DeviceDeclaration.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 NotFound();
}
DeviceDeclaration googleCloudMobileDeclaration = await _context.DeviceDeclaration.SingleAsync(m => m.DeviceId == id);
if (googleCloudMobileDeclaration == null)
{
return NotFound();
}
return View(googleCloudMobileDeclaration);
}
// GET: GCMDevices/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(string id)
{
if (id == null)
{
return NotFound();
}
DeviceDeclaration googleCloudMobileDeclaration = await _context.DeviceDeclaration.SingleAsync(m => m.DeviceId == id);
if (googleCloudMobileDeclaration == null)
{
return NotFound();
}
return View(googleCloudMobileDeclaration);
}
// POST: GCMDevices/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(string id)
{
DeviceDeclaration googleCloudMobileDeclaration = await _context.DeviceDeclaration.SingleAsync(m => m.DeviceId == id);
_context.DeviceDeclaration.Remove(googleCloudMobileDeclaration);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
}
}

View file

@ -0,0 +1,128 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Models;
using Yavsc.Models.Relationship;
namespace Yavsc.Controllers
{
[Authorize("AdministratorOnly")]
public class HyperLinkController : Controller
{
private readonly ApplicationDbContext _context;
public HyperLinkController(ApplicationDbContext context)
{
_context = context;
}
// GET: HyperLink
public async Task<IActionResult> Index()
{
return View(await _context.HyperLink.ToListAsync());
}
// GET: HyperLink/Details/5
public async Task<IActionResult> Details(string href, string method)
{
if (href == null || method ==null)
{
return NotFound();
}
HyperLink hyperLink = await _context.HyperLink.SingleAsync(m => m.HRef == href && m.Method == method);
if (hyperLink == null)
{
return NotFound();
}
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.HyperLink.Add(hyperLink);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(hyperLink);
}
// GET: HyperLink/Edit/5
public async Task<IActionResult> Edit(string href, string method)
{
if (href == null || method ==null)
{
return NotFound();
}
HyperLink hyperLink = await _context.HyperLink.SingleAsync(m => m.HRef == href && m.Method == method);
if (hyperLink == null)
{
return NotFound();
}
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 href, string method)
{
if (href == null || method ==null)
{
return NotFound();
}
HyperLink hyperLink = await _context.HyperLink.SingleAsync(m => m.HRef == href && m.Method == method);
if (hyperLink == null)
{
return NotFound();
}
return View(hyperLink);
}
// POST: HyperLink/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(string HRef, string Method)
{
if (HRef == null || Method ==null)
{
return NotFound();
}
HyperLink hyperLink = await _context.HyperLink.SingleAsync(m => m.HRef == HRef && m.Method == Method);
_context.HyperLink.Remove(hyperLink);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
}
}

View file

@ -0,0 +1,122 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Abstract.Models.Messaging;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Messaging;
using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
public class NotificationsController : Controller
{
private readonly 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 NotFound();
}
Notification notification = await _context.Notification.SingleAsync(m => m.Id == id);
if (notification == null)
{
return NotFound();
}
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 NotFound();
}
Notification notification = await _context.Notification.SingleAsync(m => m.Id == id);
if (notification == null)
{
return NotFound();
}
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 NotFound();
}
Notification notification = await _context.Notification.SingleAsync(m => m.Id == id);
if (notification == null)
{
return NotFound();
}
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,264 @@
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityServer8.Events;
using IdentityServer8.Models;
using IdentityServer8.Services;
using IdentityServer8.Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Linq;
using System.Threading.Tasks;
using IdentityServer8.Validation;
using System.Collections.Generic;
using System;
using Yavsc;
using Yavsc.Extensions;
namespace IdentityServerHost.Quickstart.UI
{
/// <summary>
/// This controller processes the consent UI
/// </summary>
[SecurityHeaders]
[Authorize]
public class ConsentController : Controller
{
private readonly IIdentityServerInteractionService _interaction;
private readonly IEventService _events;
private readonly ILogger<ConsentController> _logger;
public ConsentController(
IIdentityServerInteractionService interaction,
IEventService events,
ILogger<ConsentController> logger)
{
_interaction = interaction;
_events = events;
_logger = logger;
}
/// <summary>
/// Shows the consent screen
/// </summary>
/// <param name="returnUrl"></param>
/// <returns></returns>
[HttpGet]
public async Task<IActionResult> Index(string returnUrl)
{
var vm = await BuildViewModelAsync(returnUrl);
if (vm != null)
{
return View("Index", vm);
}
return View("Error");
}
/// <summary>
/// Handles the consent screen postback
/// </summary>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Index(ConsentInputModel model)
{
var result = await ProcessConsent(model);
if (result.IsRedirect)
{
var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);
if (context?.IsNativeClient() == true)
{
// The client is native, so this change in how to
// return the response is for better UX for the end user.
return this.LoadingPage("Redirect", result.RedirectUri);
}
return Redirect(result.RedirectUri);
}
if (result.HasValidationError)
{
ModelState.AddModelError(string.Empty, result.ValidationError);
}
if (result.ShowView)
{
return View("Index", result.ViewModel);
}
return View("Error");
}
/*****************************************/
/* helper APIs for the ConsentController */
/*****************************************/
private async Task<ProcessConsentResult> ProcessConsent(ConsentInputModel model)
{
var result = new ProcessConsentResult();
// validate return url is still valid
var request = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);
if (request == null) return result;
ConsentResponse grantedConsent = null;
// user clicked 'no' - send back the standard 'access_denied' response
if (model?.Button == "no")
{
grantedConsent = new ConsentResponse { Error = AuthorizationError.AccessDenied };
// emit event
await _events.RaiseAsync(new ConsentDeniedEvent(User.GetSubjectId(), request.Client.ClientId, request.ValidatedResources.RawScopeValues));
}
// user clicked 'yes' - validate the data
else if (model?.Button == "yes")
{
// if the user consented to some scope, build the response model
if (model.ScopesConsented != null && model.ScopesConsented.Any())
{
var scopes = model.ScopesConsented;
if (ConsentOptions.EnableOfflineAccess == false)
{
scopes = scopes.Where(x => x != IdentityServer8.IdentityServerConstants.StandardScopes.OfflineAccess);
}
grantedConsent = new ConsentResponse
{
RememberConsent = model.RememberConsent,
ScopesValuesConsented = scopes.ToArray(),
Description = model.Description
};
// emit event
await _events.RaiseAsync(new ConsentGrantedEvent(User.GetSubjectId(), request.Client.ClientId, request.ValidatedResources.RawScopeValues, grantedConsent.ScopesValuesConsented, grantedConsent.RememberConsent));
}
else
{
result.ValidationError = ConsentOptions.MustChooseOneErrorMessage;
}
}
else
{
result.ValidationError = ConsentOptions.InvalidSelectionErrorMessage;
}
if (grantedConsent != null)
{
// communicate outcome of consent back to identityserver
await _interaction.GrantConsentAsync(request, grantedConsent);
// indicate that's it ok to redirect back to authorization endpoint
result.RedirectUri = model.ReturnUrl;
result.Client = request.Client;
}
else
{
// we need to redisplay the consent UI
result.ViewModel = await BuildViewModelAsync(model.ReturnUrl, model);
}
return result;
}
private async Task<ConsentViewModel> BuildViewModelAsync(string returnUrl, ConsentInputModel model = null)
{
var request = await _interaction.GetAuthorizationContextAsync(returnUrl);
if (request != null)
{
return CreateConsentViewModel(model, returnUrl, request);
}
else
{
_logger.LogError("No consent request matching request: {0}", returnUrl);
}
return null;
}
private ConsentViewModel CreateConsentViewModel(
ConsentInputModel model, string returnUrl,
AuthorizationRequest request)
{
var vm = new ConsentViewModel
{
RememberConsent = model?.RememberConsent ?? true,
ScopesConsented = model?.ScopesConsented ?? Enumerable.Empty<string>(),
Description = model?.Description,
ReturnUrl = returnUrl,
ClientName = request.Client.ClientName ?? request.Client.ClientId,
ClientUrl = request.Client.ClientUri,
ClientLogoUrl = request.Client.LogoUri,
AllowRememberConsent = request.Client.AllowRememberConsent
};
vm.IdentityScopes = request.ValidatedResources.Resources.IdentityResources.Select(x => CreateScopeViewModel(x, vm.ScopesConsented.Contains(x.Name) || model == null)).ToArray();
var apiScopes = new List<ScopeViewModel>();
foreach(var parsedScope in request.ValidatedResources.ParsedScopes)
{
var apiScope = request.ValidatedResources.Resources.FindApiScope(parsedScope.ParsedName);
if (apiScope != null)
{
var scopeVm = CreateScopeViewModel(parsedScope, apiScope, vm.ScopesConsented.Contains(parsedScope.RawValue) || model == null);
apiScopes.Add(scopeVm);
}
}
if (ConsentOptions.EnableOfflineAccess && request.ValidatedResources.Resources.OfflineAccess)
{
apiScopes.Add(GetOfflineAccessScope(vm.ScopesConsented.Contains(IdentityServer8.IdentityServerConstants.StandardScopes.OfflineAccess) || model == null));
}
vm.ApiScopes = apiScopes;
return vm;
}
private ScopeViewModel CreateScopeViewModel(IdentityResource identity, bool check)
{
return new ScopeViewModel
{
Value = identity.Name,
DisplayName = identity.DisplayName ?? identity.Name,
Description = identity.Description,
Emphasize = identity.Emphasize,
Required = identity.Required,
Checked = check || identity.Required
};
}
public ScopeViewModel CreateScopeViewModel(ParsedScopeValue parsedScopeValue, ApiScope apiScope, bool check)
{
var displayName = apiScope.DisplayName ?? apiScope.Name;
if (!String.IsNullOrWhiteSpace(parsedScopeValue.ParsedParameter))
{
displayName += ":" + parsedScopeValue.ParsedParameter;
}
return new ScopeViewModel
{
Value = parsedScopeValue.RawValue,
DisplayName = displayName,
Description = apiScope.Description,
Emphasize = apiScope.Emphasize,
Required = apiScope.Required,
Checked = check || apiScope.Required
};
}
private ScopeViewModel GetOfflineAccessScope(bool check)
{
return new ScopeViewModel
{
Value = IdentityServer8.IdentityServerConstants.StandardScopes.OfflineAccess,
DisplayName = ConsentOptions.OfflineAccessDisplayName,
Description = ConsentOptions.OfflineAccessDescription,
Emphasize = true,
Checked = check
};
}
}
}

View file

@ -0,0 +1,17 @@
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System.Collections.Generic;
namespace IdentityServerHost.Quickstart.UI
{
public class ConsentInputModel
{
public string Button { get; set; }
public IEnumerable<string> ScopesConsented { get; set; }
public bool RememberConsent { get; set; }
public string ReturnUrl { get; set; }
public string Description { get; set; }
}
}

View file

@ -0,0 +1,16 @@
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace IdentityServerHost.Quickstart.UI
{
public class ConsentOptions
{
public static bool EnableOfflineAccess = true;
public static string OfflineAccessDisplayName = "Offline Access";
public static string OfflineAccessDescription = "Access to your applications and resources, even when you are offline";
public static readonly string MustChooseOneErrorMessage = "You must pick at least one permission";
public static readonly string InvalidSelectionErrorMessage = "Invalid selection";
}
}

View file

@ -0,0 +1,19 @@
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System.Collections.Generic;
namespace IdentityServerHost.Quickstart.UI
{
public class ConsentViewModel : ConsentInputModel
{
public string ClientName { get; set; }
public string ClientUrl { get; set; }
public string ClientLogoUrl { get; set; }
public bool AllowRememberConsent { get; set; }
public IEnumerable<ScopeViewModel> IdentityScopes { get; set; }
public IEnumerable<ScopeViewModel> ApiScopes { get; set; }
}
}

View file

@ -0,0 +1,21 @@
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityServer8.Models;
namespace IdentityServerHost.Quickstart.UI
{
public class ProcessConsentResult
{
public bool IsRedirect => RedirectUri != null;
public string RedirectUri { get; set; }
public Client Client { get; set; }
public bool ShowView => ViewModel != null;
public ConsentViewModel ViewModel { get; set; }
public bool HasValidationError => ValidationError != null;
public string ValidationError { get; set; }
}
}

View file

@ -0,0 +1,16 @@
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace IdentityServerHost.Quickstart.UI
{
public class ScopeViewModel
{
public string Value { get; set; }
public string DisplayName { get; set; }
public string Description { get; set; }
public bool Emphasize { get; set; }
public bool Required { get; set; }
public bool Checked { get; set; }
}
}

View file

@ -0,0 +1,207 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Localization;
namespace Yavsc.Controllers
{
using Microsoft.EntityFrameworkCore;
using Models;
using Models.Workflow;
using Yavsc.Helpers;
using Yavsc.Server.Helpers;
[Authorize("AdministratorOnly")]
public class ActivityController : Controller
{
private readonly ApplicationDbContext _context;
readonly IStringLocalizer<ActivityController> SR;
readonly ILogger logger;
public ActivityController(ApplicationDbContext context,
IStringLocalizer<ActivityController> 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 = Config.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 descendence
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;
RecursivelyFilterChild(acts, existing);
return acts;
}
/// <summary>
/// Filters a activity selection list
/// in order to exclude 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 RecursivelyFilterChild(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)
{
RecursivelyFilterChild(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 NotFound();
}
Activity activity = _context.Activities.Single(m => m.Code == id);
if (activity == null)
{
return NotFound();
}
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 NotFound();
}
Activity activity = _context.Activities.Single(m => m.Code == id);
if (activity == null)
{
return NotFound();
}
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 NotFound();
}
Activity activity = _context.Activities.Single(m => m.Code == id);
if (activity == null)
{
return NotFound();
}
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,131 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Workflow;
using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
public class CoWorkingController : Controller
{
private readonly ApplicationDbContext _context;
public CoWorkingController(ApplicationDbContext context)
{
_context = context;
}
// GET: CoWorking
public async Task<IActionResult> Index()
{
var applicationDbContext = _context.CoWorking.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 NotFound();
}
CoWorking coWorking = await _context.CoWorking.SingleAsync(m => m.Id == id);
if (coWorking == null)
{
return NotFound();
}
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.CoWorking.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 NotFound();
}
CoWorking coWorking = await _context.CoWorking.SingleAsync(m => m.Id == id);
if (coWorking == null)
{
return NotFound();
}
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 NotFound();
}
CoWorking coWorking = await _context.CoWorking.SingleAsync(m => m.Id == id);
if (coWorking == null)
{
return NotFound();
}
return View(coWorking);
}
// POST: CoWorking/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(long id)
{
CoWorking coWorking = await _context.CoWorking.SingleAsync(m => m.Id == id);
_context.CoWorking.Remove(coWorking);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
}
}

View file

@ -0,0 +1,276 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization;
namespace Yavsc.Controllers
{
using Helpers;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Models;
using Models.Google.Messaging;
using Models.Relationship;
using Models.Workflow;
using Services;
using Yavsc.Interface;
using Yavsc.Models.Billing;
using Yavsc.Models.Haircut;
using Yavsc.Server.Helpers;
using Yavsc.Settings;
public class CommandController : Controller
{
protected UserManager<ApplicationUser> _userManager;
protected ApplicationDbContext _context;
protected GoogleAuthSettings _googleSettings;
protected IYavscMessageSender _MessageSender;
protected ITrueEmailSender _emailSender;
protected IStringLocalizer<CommandController> _localizer;
protected SiteSettings _siteSettings;
protected SmtpSettings _smtpSettings;
protected ICalendarManager _calendarManager;
protected readonly ILogger _logger;
public CommandController(ApplicationDbContext context, IOptions<GoogleAuthSettings> googleSettings,
IYavscMessageSender messageSender,
UserManager<ApplicationUser> userManager,
ICalendarManager calendarManager,
IStringLocalizer<CommandController> localizer,
ITrueEmailSender emailSender,
IOptions<SmtpSettings> smtpSettings,
IOptions<SiteSettings> siteSettings,
ILoggerFactory loggerFactory)
{
_context = context;
_MessageSender = messageSender;
_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.FindFirstValue(ClaimTypes.NameIdentifier);
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 NotFound();
}
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)
{
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 NotFound();
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.FindFirstValue(ClaimTypes.NameIdentifier);
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.DeviceDeclaration)
.FirstOrDefault(
x => x.PerformerId == command.PerformerId
);
var user = await _userManager.FindByIdAsync(uid);
command.Client = user;
command.ClientId = uid;
command.PerformerProfile = pro;
// FIXME Why!!
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);
_context.SaveChanges(User.GetUserId());
var yaev = command.CreateEvent("NewCommand");
MessageWithPayloadResponse nrep = null;
if (pro.AcceptNotifications
&& pro.AcceptPublicContact)
{
try
{
_logger.LogInformation("Notifying query");
var uids = new[] { command.PerformerProfile.PerformerId };
nrep = await _MessageSender.NotifyBookQueryAsync(uids, yaev);
// TODO setup a profile choice to allow notifications
// both on mailbox and mobile
// if (grep==null || grep.success<=0 || grep.failure>0)
ViewBag.MessagingResponsePayload = nrep;
}
catch (Exception ex)
{
_logger.LogError("Message sending failed with: " + ex.Message);
throw;
}
}
else
{
nrep = new MessageWithPayloadResponse
{
failure = 1,
results = new MessageWithPayloadResponse.Result[] {
new MessageWithPayloadResponse.Result
{
error=NotificationTypes.ContactRefused,
registration_id= pro.PerformerId
}
}
};
_logger.LogInformation("Command.Create && ( !pro.AcceptNotifications || |pro.AcceptPublicContact ) ");
}
ViewBag.MessagingResponsePayload = nrep;
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 NotFound();
}
RdvQuery command = _context.RdvQueries.Single(m => m.Id == id);
if (command == null)
{
return NotFound();
}
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 NotFound();
}
RdvQuery command = _context.RdvQueries.Single(m => m.Id == id);
if (command == null)
{
return NotFound();
}
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 Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Workflow;
using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
public class CommandFormsController : Controller
{
private readonly 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 NotFound();
}
CommandForm commandForm = await _context.CommandForm.SingleAsync(m => m.Id == id);
if (commandForm == null)
{
return NotFound();
}
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 = _context.CommandForm.Select(c => new SelectListItem { Value = c.Id.ToString(), Text = c.Title, Selected = commandForm.Id == c.Id });
}
// 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 NotFound();
}
CommandForm commandForm = await _context.CommandForm.SingleAsync(m => m.Id == id);
if (commandForm == null)
{
return NotFound();
}
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 NotFound();
}
CommandForm commandForm = await _context.CommandForm.SingleAsync(m => m.Id == id);
if (commandForm == null)
{
return NotFound();
}
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,119 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Models;
using Yavsc.Models.Musical.Profiles;
namespace Yavsc.Controllers
{
public class DjSettingsController : Controller
{
private readonly 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 NotFound();
}
DjSettings djSettings = await _context.DjSettings.SingleAsync(m => m.UserId == id);
if (djSettings == null)
{
return NotFound();
}
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 NotFound();
}
DjSettings djSettings = await _context.DjSettings.SingleAsync(m => m.UserId == id);
if (djSettings == null)
{
return NotFound();
}
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 NotFound();
}
DjSettings djSettings = await _context.DjSettings.SingleAsync(m => m.UserId == id);
if (djSettings == null)
{
return NotFound();
}
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,188 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace Yavsc.Controllers
{
using Microsoft.Extensions.Logging;
using Models;
using Models.Workflow;
using Yavsc.ViewModels.Workflow;
using Yavsc.Services;
using System.Threading.Tasks;
using Yavsc.Helpers;
using Microsoft.EntityFrameworkCore;
using Yavsc.Server.Helpers;
[Authorize]
public class DoController : Controller
{
private readonly ApplicationDbContext dbContext;
readonly ILogger logger;
readonly 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 NotFound();
}
UserActivity userActivity = dbContext.UserActivities.Include(m=>m.Does)
.Include(m=>m.User).Single(m => m.DoesCode == activityCode && m.UserId == id);
if (userActivity == null)
{
return NotFound();
}
bool hasConfigurableSettings = (userActivity.Does.SettingsClassName != null);
var settings = await billing.GetPerformersSettingsAsync(activityCode, id);
ViewBag.ProfileType = Config.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.FindFirstValue(ClaimTypes.NameIdentifier);
if (!User.IsInMsRole("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 NotFound();
}
UserActivity userActivity = dbContext.UserActivities.Include(
u=>u.Does
).Include(
u=>u.User
).Single(m => m.DoesCode == activityCode && m.UserId == id);
if (userActivity == null)
{
return NotFound();
}
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.IsInMsRole("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 NotFound();
}
UserActivity userActivity = dbContext.UserActivities.Single(m => m.UserId == id && m.DoesCode == activityCode);
if (userActivity == null)
{
return NotFound();
}
if (!User.IsInMsRole("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.IsInMsRole("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,208 @@
using System.Net.Mime;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Yavsc.Helpers;
namespace Yavsc.Controllers
{
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Models;
using Models.Billing;
using Models.Workflow;
using ViewModels.Auth;
using Yavsc.Server.Helpers;
[Authorize]
public class EstimateController : Controller
{
private readonly ApplicationDbContext _context;
private readonly SiteSettings _site;
readonly 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.FindFirstValue(ClaimTypes.NameIdentifier);
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.FindFirstValue(ClaimTypes.NameIdentifier);
if (id == null)
{
return NotFound();
}
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 NotFound();
}
if (authorizationService.AuthorizeAsync(User, estimate, new ReadPermission()).IsFaulted)
{
return new ChallengeResult();
}
return View(estimate);
}
// GET: Estimate/Create
[Authorize]
public IActionResult Create()
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
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 async Task<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);
await gr.SaveAsAsync(
Path.Combine(
Path.Combine(billsdir, estimate.Id.ToString()),
contentDisposition.FileName));
}
foreach (var formFile in newFiles)
{
ContentDisposition contentDisposition = new ContentDisposition(formFile.ContentDisposition);
await formFile.SaveAsAsync(
Path.Combine(
Path.Combine(billsdir, estimate.Id.ToString()),
contentDisposition.FileName));
}
return RedirectToAction("Index");
}
return View(estimate);
}
// GET: Estimate/Edit/5
public IActionResult Edit(long? id)
{
if (id == null)
{
return NotFound();
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
Estimate estimate = _context.Estimates
.Where(e=>e.OwnerId==uid||e.ClientId==uid).Single(m => m.Id == id);
if (estimate == null)
{
return NotFound();
}
return View(estimate);
}
// POST: Estimate/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Edit(Estimate estimate)
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (estimate.OwnerId!=uid&&estimate.ClientId!=uid
) return NotFound();
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 NotFound();
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
Estimate estimate = _context.Estimates
.Where(e=>e.OwnerId==uid||e.ClientId==uid) .Single(m => m.Id == id);
if (estimate == null)
{
return NotFound();
}
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,16 @@
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 Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Forms;
using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
public class FormsController : Controller
{
private readonly 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 NotFound();
}
Form form = await _context.Form.SingleAsync(m => m.Id == id);
if (form == null)
{
return NotFound();
}
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 NotFound();
}
Form form = await _context.Form.SingleAsync(m => m.Id == id);
if (form == null)
{
return NotFound();
}
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 NotFound();
}
Form form = await _context.Form.SingleAsync(m => m.Id == id);
if (form == null)
{
return NotFound();
}
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,136 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using System.Security.Claims;
namespace Yavsc.Controllers
{
using Helpers;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Models;
using ViewModels.FrontOffice;
using Yavsc.Server.Helpers;
using Yavsc.Services;
public class FrontOfficeController : Controller
{
readonly ApplicationDbContext _context;
readonly UserManager<ApplicationUser> _userManager;
readonly ILogger _logger;
readonly IStringLocalizer _SR;
private readonly IBillingService _billing;
public FrontOfficeController(ApplicationDbContext context,
UserManager<ApplicationUser> userManager,
IBillingService billing,
ILoggerFactory loggerFactory,
IStringLocalizer<FrontOfficeController> SR)
{
_context = context;
_userManager = userManager;
_logger = loggerFactory.CreateLogger<FrontOfficeController>();
_SR = SR;
_billing = billing;
}
public ActionResult Index()
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
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 async Task<ActionResult> Profiles(string id)
{
if (id == null)
{
throw new NotImplementedException("No Activity code");
}
ViewBag.Activity = await _context.Activities.FirstOrDefaultAsync(a => a.Code == id);
var result = await _context.ListPerformersAsync(_billing, id);
return View(result);
}
[AllowAnonymous]
public async Task <ActionResult> HairCut(string id)
{
if (id == null)
{
throw new NotImplementedException("No Activity code");
}
ViewBag.Activity = await _context.Activities.FirstOrDefaultAsync(a => a.Code == id);
var result = await _context.ListPerformersAsync(_billing, id);
return View(result);
}
[Produces("text/x-tex"), Authorize, Route("estimate-{id}.tex")]
[HttpGet]
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")]
[HttpGet]
public IActionResult EstimatePdf(long id)
{
ViewBag.TempDir = Config.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,119 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Models;
using Yavsc.Models.Musical.Profiles;
namespace Yavsc.Controllers
{
public class GeneralSettingsController : Controller
{
private readonly 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 NotFound();
}
GeneralSettings generalSettings = await _context.GeneralSettings.SingleAsync(m => m.UserId == id);
if (generalSettings == null)
{
return NotFound();
}
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 NotFound();
}
GeneralSettings generalSettings = await _context.GeneralSettings.SingleAsync(m => m.UserId == id);
if (generalSettings == null)
{
return NotFound();
}
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 NotFound();
}
GeneralSettings generalSettings = await _context.GeneralSettings.SingleAsync(m => m.UserId == id);
if (generalSettings == null)
{
return NotFound();
}
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,121 @@
using Microsoft.AspNetCore.Mvc;
namespace Yavsc.Controllers
{
using Models;
using Models.Musical;
using Yavsc.Helpers;
using Yavsc.Server.Helpers;
public class MusicalTendenciesController : Controller
{
private readonly 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 NotFound();
}
MusicalTendency musicalTendency = _context.MusicalTendency.Single(m => m.Id == id);
if (musicalTendency == null)
{
return NotFound();
}
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 NotFound();
}
MusicalTendency musicalTendency = _context.MusicalTendency.Single(m => m.Id == id);
if (musicalTendency == null)
{
return NotFound();
}
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 NotFound();
}
MusicalTendency musicalTendency = _context.MusicalTendency.Single(m => m.Id == id);
if (musicalTendency == null)
{
return NotFound();
}
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 Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Billing;
using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
[Authorize("AdministratorOnly")]
public class SIRENExceptionsController : Controller
{
private readonly 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 NotFound();
}
ExceptionSIREN exceptionSIREN = _context.ExceptionsSIREN.Single(m => m.SIREN == id);
if (exceptionSIREN == null)
{
return NotFound();
}
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 NotFound();
}
ExceptionSIREN exceptionSIREN = _context.ExceptionsSIREN.Single(m => m.SIREN == id);
if (exceptionSIREN == null)
{
return NotFound();
}
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 NotFound();
}
ExceptionSIREN exceptionSIREN = _context.ExceptionsSIREN.Single(m => m.SIREN == id);
if (exceptionSIREN == null)
{
return NotFound();
}
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,233 @@
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IdentityServer8.Configuration;
using IdentityServer8.Events;
using IdentityServer8.Extensions;
using IdentityServer8.Models;
using IdentityServer8.Services;
using IdentityServer8.Validation;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Yavsc.Models.Access;
namespace Yavsc.Controllers
{
[Authorize]
[SecurityHeaders]
public class DeviceController : Controller
{
private readonly IDeviceFlowInteractionService _interaction;
private readonly IEventService _events;
private readonly IOptions<IdentityServerOptions> _options;
private readonly ILogger<DeviceController> _logger;
public DeviceController(
IDeviceFlowInteractionService interaction,
IEventService eventService,
IOptions<IdentityServerOptions> options,
ILogger<DeviceController> logger)
{
_interaction = interaction;
_events = eventService;
_options = options;
_logger = logger;
}
[HttpGet]
public async Task<IActionResult> Index()
{
string userCodeParamName = _options.Value.UserInteraction.DeviceVerificationUserCodeParameter;
string userCode = Request.Query[userCodeParamName];
if (string.IsNullOrWhiteSpace(userCode)) return View("UserCodeCapture");
var vm = await BuildViewModelAsync(userCode);
if (vm == null) return View("Error");
vm.ConfirmUserCode = true;
return View("UserCodeConfirmation", vm);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> UserCodeCapture(string userCode)
{
var vm = await BuildViewModelAsync(userCode);
if (vm == null) return View("Error");
return View("UserCodeConfirmation", vm);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Callback(DeviceAuthorizationInputModel model)
{
if (model == null) throw new ArgumentNullException(nameof(model));
var result = await ProcessConsent(model);
if (result.HasValidationError) return View("Error");
return View("Success");
}
private async Task<ProcessConsentResult> ProcessConsent(DeviceAuthorizationInputModel model)
{
var result = new ProcessConsentResult();
var request = await _interaction.GetAuthorizationContextAsync(model.UserCode);
if (request == null) return result;
ConsentResponse grantedConsent = null;
// user clicked 'no' - send back the standard 'access_denied' response
if (model.Button == "no")
{
grantedConsent = new ConsentResponse { Error = AuthorizationError.AccessDenied };
// emit event
await _events.RaiseAsync(new ConsentDeniedEvent(User.GetSubjectId(), request.Client.ClientId, request.ValidatedResources.RawScopeValues));
}
// user clicked 'yes' - validate the data
else if (model.Button == "yes")
{
// if the user consented to some scope, build the response model
if (model.ScopesConsented != null && model.ScopesConsented.Any())
{
var scopes = model.ScopesConsented;
if (ConsentOptions.EnableOfflineAccess == false)
{
scopes = scopes.Where(x => x != IdentityServer8.IdentityServerConstants.StandardScopes.OfflineAccess);
}
grantedConsent = new ConsentResponse
{
RememberConsent = model.RememberConsent,
ScopesValuesConsented = scopes.ToArray(),
Description = model.Description
};
// emit event
await _events.RaiseAsync(new ConsentGrantedEvent(User.GetSubjectId(), request.Client.ClientId, request.ValidatedResources.RawScopeValues, grantedConsent.ScopesValuesConsented, grantedConsent.RememberConsent));
}
else
{
result.ValidationError = ConsentOptions.MustChooseOneErrorMessage;
}
}
else
{
result.ValidationError = ConsentOptions.InvalidSelectionErrorMessage;
}
if (grantedConsent != null)
{
// communicate outcome of consent back to identityserver
await _interaction.HandleRequestAsync(model.UserCode, grantedConsent);
// indicate that's it ok to redirect back to authorization endpoint
result.RedirectUri = model.ReturnUrl;
result.Client = request.Client;
}
else
{
// we need to redisplay the consent UI
result.ViewModel = await BuildViewModelAsync(model.UserCode, model);
}
return result;
}
private async Task<DeviceAuthorizationViewModel> BuildViewModelAsync(string userCode, DeviceAuthorizationInputModel model = null)
{
var request = await _interaction.GetAuthorizationContextAsync(userCode);
if (request != null)
{
return CreateConsentViewModel(userCode, model, request);
}
return null;
}
private DeviceAuthorizationViewModel CreateConsentViewModel(string userCode, DeviceAuthorizationInputModel model, DeviceFlowAuthorizationRequest request)
{
var vm = new DeviceAuthorizationViewModel
{
UserCode = userCode,
Description = model?.Description,
RememberConsent = model?.RememberConsent ?? true,
ScopesConsented = model?.ScopesConsented ?? Enumerable.Empty<string>(),
ClientName = request.Client.ClientName ?? request.Client.ClientId,
ClientUrl = request.Client.ClientUri,
ClientLogoUrl = request.Client.LogoUri,
AllowRememberConsent = request.Client.AllowRememberConsent
};
vm.IdentityScopes = request.ValidatedResources.Resources.IdentityResources.Select(x => CreateScopeViewModel(x, vm.ScopesConsented.Contains(x.Name) || model == null)).ToArray();
var apiScopes = new List<ScopeViewModel>();
foreach (var parsedScope in request.ValidatedResources.ParsedScopes)
{
var apiScope = request.ValidatedResources.Resources.FindApiScope(parsedScope.ParsedName);
if (apiScope != null)
{
var scopeVm = CreateScopeViewModel(parsedScope, apiScope, vm.ScopesConsented.Contains(parsedScope.RawValue) || model == null);
apiScopes.Add(scopeVm);
}
}
if (ConsentOptions.EnableOfflineAccess && request.ValidatedResources.Resources.OfflineAccess)
{
apiScopes.Add(GetOfflineAccessScope(vm.ScopesConsented.Contains(IdentityServer8.IdentityServerConstants.StandardScopes.OfflineAccess) || model == null));
}
vm.ApiScopes = apiScopes;
return vm;
}
private ScopeViewModel CreateScopeViewModel(IdentityResource identity, bool check)
{
return new ScopeViewModel
{
Value = identity.Name,
DisplayName = identity.DisplayName ?? identity.Name,
Description = identity.Description,
Emphasize = identity.Emphasize,
Required = identity.Required,
Checked = check || identity.Required
};
}
public ScopeViewModel CreateScopeViewModel(ParsedScopeValue parsedScopeValue, ApiScope apiScope, bool check)
{
return new ScopeViewModel
{
Value = parsedScopeValue.RawValue,
// todo: use the parsed scope value in the display?
DisplayName = apiScope.DisplayName ?? apiScope.Name,
Description = apiScope.Description,
Emphasize = apiScope.Emphasize,
Required = apiScope.Required,
Checked = check || apiScope.Required
};
}
private ScopeViewModel GetOfflineAccessScope(bool check)
{
return new ScopeViewModel
{
Value = IdentityServer8.IdentityServerConstants.StandardScopes.OfflineAccess,
DisplayName = ConsentOptions.OfflineAccessDisplayName,
Description = ConsentOptions.OfflineAccessDescription,
Emphasize = true,
Checked = check
};
}
}
}

View file

@ -0,0 +1,30 @@
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Yavsc.Models;
namespace Yavsc.Controllers
{
[SecurityHeaders]
[Authorize]
public class DiagnosticsController : Controller
{
public async Task<IActionResult> Index()
{
var localAddresses = new string[] { "127.0.0.1", "::1", HttpContext.Connection.LocalIpAddress.ToString() };
if (!localAddresses.Contains(HttpContext.Connection.RemoteIpAddress.ToString()))
{
return NotFound();
}
var model = new DiagnosticsViewModel(await HttpContext.AuthenticateAsync());
return View(model);
}
}
}

View file

@ -0,0 +1,32 @@
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityModel;
using Microsoft.AspNetCore.Authentication;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Text;
namespace Yavsc.Models
{
public class DiagnosticsViewModel
{
public DiagnosticsViewModel(AuthenticateResult result)
{
AuthenticateResult = result;
if (result.Properties.Items.ContainsKey("client_list"))
{
var encoded = result.Properties.Items["client_list"];
var bytes = Base64Url.Decode(encoded);
var value = Encoding.UTF8.GetString(bytes);
Clients = JsonConvert.DeserializeObject<string[]>(value);
}
}
public AuthenticateResult AuthenticateResult { get; }
public IEnumerable<string> Clients { get; } = new List<string>();
}
}

View file

@ -0,0 +1,11 @@
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace Yavsc.Models.Access
{
public class LogoutViewModel : LogoutInputModel
{
public bool ShowLogoutPrompt { get; set; } = true;
}
}

View file

@ -0,0 +1,175 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Messaging;
using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
[Produces("application/json")]
[Route("api/dimiss")]
public class DimissClicksApiController : Controller
{
private readonly ApplicationDbContext _context;
public DimissClicksApiController(ApplicationDbContext context)
{
_context = context;
}
// GET: api/DimissClicksApi
[HttpGet]
public IEnumerable<DismissClicked> GetDismissClicked()
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
return _context.DismissClicked.Where(d=>d.UserId == uid);
}
[HttpGet("click/{noteid}"),AllowAnonymous]
public async Task<IActionResult> Click(long noteid )
{
if (User.IsSignedIn())
return await PostDismissClicked(new DismissClicked { NotificationId= noteid, UserId = User.GetUserId()});
await HttpContext.Session.LoadAsync();
var clicked = HttpContext.Session.GetString("clicked");
if (clicked == null) {
HttpContext.Session.SetString("clicked",noteid.ToString());
} else HttpContext.Session.SetString("clicked",$"{clicked}:{noteid}");
await HttpContext.Session.CommitAsync();
return Ok();
}
// GET: api/DimissClicksApi/5
[HttpGet("{id}", Name = "GetDismissClicked")]
public async Task<IActionResult> GetDismissClicked([FromRoute] string id)
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (uid != id) return new ChallengeResult();
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
DismissClicked DismissClicked = await _context.DismissClicked.SingleAsync(m => m.UserId == id);
if (DismissClicked == null)
{
return NotFound();
}
return Ok(DismissClicked);
}
// PUT: api/DimissClicksApi/5
[HttpPut("{id}")]
public async Task<IActionResult> PutDismissClicked([FromRoute] string id, [FromBody] DismissClicked DismissClicked)
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (uid != id || uid != DismissClicked.UserId) return new ChallengeResult();
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != DismissClicked.UserId)
{
return BadRequest();
}
_context.Entry(DismissClicked).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync(User.GetUserId());
}
catch (DbUpdateConcurrencyException)
{
if (!DismissClickedExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return new StatusCodeResult(StatusCodes.Status204NoContent);
}
// POST: api/DimissClicksApi
[HttpPost]
public async Task<IActionResult> PostDismissClicked([FromBody] DismissClicked DismissClicked)
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (uid != DismissClicked.UserId) return new ChallengeResult();
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.DismissClicked.Add(DismissClicked);
try
{
await _context.SaveChangesAsync(User.GetUserId());
}
catch (DbUpdateException)
{
if (DismissClickedExists(DismissClicked.UserId))
{
return new StatusCodeResult(StatusCodes.Status409Conflict);
}
else
{
throw;
}
}
return CreatedAtRoute("GetDismissClicked", new { id = DismissClicked.UserId }, DismissClicked);
}
// DELETE: api/DimissClicksApi/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteDismissClicked([FromRoute] string id)
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (!User.IsInRole("Administrator"))
if (uid != id) return new ChallengeResult();
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
DismissClicked DismissClicked = await _context.DismissClicked.SingleAsync(m => m.UserId == id);
if (DismissClicked == null)
{
return NotFound();
}
_context.DismissClicked.Remove(DismissClicked);
await _context.SaveChangesAsync(User.GetUserId());
return Ok(DismissClicked);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_context.Dispose();
}
base.Dispose(disposing);
}
private bool DismissClickedExists(string id)
{
return _context.DismissClicked.Count(e => e.UserId == id) > 0;
}
}
}

View file

@ -0,0 +1,23 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Yavsc.Helpers;
using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
public class FileSystemController : Controller
{
public FileSystemController()
{
}
public IActionResult Index(string subdir="")
{
if (subdir !=null)
if (!subdir.IsValidYavscPath())
return new BadRequestResult();
var files = AbstractFileSystemHelpers.GetUserFiles(User.GetUserId(), subdir);
return View(files);
}
}
}

View file

@ -0,0 +1,151 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Yavsc.Controllers.Generic
{
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Models;
using Yavsc.Helpers;
using Yavsc.Server.Helpers;
using Yavsc.Services;
[Authorize]
public abstract class SettingsController<TSettings> : Controller where TSettings : class, IUserSettings, 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;
} }
virtual protected async Task<TSettings> GetSettingsAsync(
string userId
)
{
return await Settings.SingleOrDefaultAsync(p=>p.UserId == userId);
}
public SettingsController(ApplicationDbContext context)
{
_context = context;
}
public async Task<IActionResult> Index()
{
return View(await GetSettingsAsync(User.GetUserId()));
}
// GET: BrusherProfile/Details/5
public async Task<IActionResult> Details(string id)
{
if (id == null)
{
id = User.GetUserId();
}
var profile = await GetSettingsAsync(id);
if (profile == null)
{
return NotFound();
}
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 GetSettingsAsync(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 NotFound();
}
var profile = await GetSettingsAsync(id);
if (profile == null)
{
return NotFound();
}
return View(profile);
}
// 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 userSettings = await GetSettingsAsync(id);
Settings.Remove(userSettings);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
}
}

View file

@ -0,0 +1,99 @@
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityServer8.Services;
using IdentityServer8.Stores;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using IdentityServer8.Events;
using IdentityServer8.Extensions;
using Yavsc;
using Yavsc.Models.Access;
namespace IdentityServerHost.Quickstart.UI
{
/// <summary>
/// This sample controller allows a user to revoke grants given to clients
/// </summary>
[SecurityHeaders]
[Authorize]
public class GrantsController : Controller
{
private readonly IIdentityServerInteractionService _interaction;
private readonly IClientStore _clients;
private readonly IResourceStore _resources;
private readonly IEventService _events;
public GrantsController(IIdentityServerInteractionService interaction,
IClientStore clients,
IResourceStore resources,
IEventService events)
{
_interaction = interaction;
_clients = clients;
_resources = resources;
_events = events;
}
/// <summary>
/// Show list of grants
/// </summary>
[HttpGet]
public async Task<IActionResult> Index()
{
return View("Index", await BuildViewModelAsync());
}
/// <summary>
/// Handle postback to revoke a client
/// </summary>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Revoke(string clientId)
{
await _interaction.RevokeUserConsentAsync(clientId);
await _events.RaiseAsync(new GrantsRevokedEvent(User.GetSubjectId(), clientId));
return RedirectToAction("Index");
}
private async Task<GrantsViewModel> BuildViewModelAsync()
{
var grants = await _interaction.GetAllUserGrantsAsync();
var list = new List<GrantViewModel>();
foreach(var grant in grants)
{
var client = await _clients.FindClientByIdAsync(grant.ClientId);
if (client != null)
{
var resources = await _resources.FindResourcesByScopeAsync(grant.Scopes);
var item = new GrantViewModel()
{
ClientId = client.ClientId,
ClientName = client.ClientName ?? client.ClientId,
ClientLogoUrl = client.LogoUri,
ClientUrl = client.ClientUri,
Description = grant.Description,
Created = grant.CreationTime,
Expires = grant.Expiration,
IdentityGrantNames = resources.IdentityResources.Select(x => x.DisplayName ?? x.Name).ToArray(),
ApiGrantNames = resources.ApiScopes.Select(x => x.DisplayName ?? x.Name).ToArray()
};
list.Add(item);
}
}
return new GrantsViewModel
{
Grants = list
};
}
}
}

View file

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

View file

@ -0,0 +1,121 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Drawing;
using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
public class ColorsController : Controller
{
private readonly 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 NotFound();
}
Color color = await _context.Color.SingleAsync(m => m.Id == id);
if (color == null)
{
return NotFound();
}
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 NotFound();
}
Color color = await _context.Color.SingleAsync(m => m.Id == id);
if (color == null)
{
return NotFound();
}
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 NotFound();
}
Color color = await _context.Color.SingleAsync(m => m.Id == id);
if (color == null)
{
return NotFound();
}
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,473 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization;
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.AspNetCore.Http;
using Yavsc.Extensions;
using Yavsc.Models.Haircut;
using System.Globalization;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic;
using PayPal.PayPalAPIInterfaceService.Model;
using Microsoft.Extensions.Options;
using Microsoft.EntityFrameworkCore;
using Yavsc.Interface;
using Yavsc.Settings;
using Yavsc.Abstract.Models.Messaging;
using Yavsc.Server.Helpers;
public class HairCutCommandController : CommandController
{
readonly PayPalSettings payPalSettings;
private readonly IStringLocalizer<HairCutQuery> haircutLocalizer;
public HairCutCommandController(ApplicationDbContext context,
IOptions<PayPalSettings> payPalSettings,
IOptions<GoogleAuthSettings> googleSettings,
IYavscMessageSender GCMSender,
UserManager<ApplicationUser> userManager,
IStringLocalizer<HairCutQuery> haircutLocalizer,
IStringLocalizer<CommandController> localizer,
ITrueEmailSender 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;
this.haircutLocalizer = haircutLocalizer;
}
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.DeviceDeclaration)
.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 NotFound();
}
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 NotFound();
}
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.DeviceDeclaration.Count > 0)
{
var regid = command.PerformerProfile.PerformerId;
grep = await _MessageSender.NotifyAsync(new [] {regid}, 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 NotFound();
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
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.FindFirstValue(ClaimTypes.NameIdentifier);
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 NotFound();
}
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.FindFirstValue(ClaimTypes.NameIdentifier);
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.DeviceDeclaration)
.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(this.haircutLocalizer);
if (pro.AcceptPublicContact)
{
if (pro.AcceptNotifications)
{
if (pro.Performer.DeviceDeclaration.Count > 0)
{
var uids = new[] { pro.PerformerId };
grep = await _MessageSender.NotifyHairCutQueryAsync(uids, 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.FindFirstValue(ClaimTypes.NameIdentifier);
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.FindFirstValue(ClaimTypes.NameIdentifier);
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.DeviceDeclaration)
.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);
_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.DeviceDeclaration?.Count > 0)
{
var uids = new [] { command.PerformerProfile.PerformerId };
grep = await _MessageSender.NotifyHairCutQueryAsync(uids, 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,119 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Models;
using Yavsc.Models.Haircut;
namespace Yavsc.Controllers
{
public class HairPrestationsController : Controller
{
private readonly 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 NotFound();
}
HairPrestation hairPrestation = await _context.HairPrestation.SingleAsync(m => m.Id == id);
if (hairPrestation == null)
{
return NotFound();
}
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 NotFound();
}
HairPrestation hairPrestation = await _context.HairPrestation.SingleAsync(m => m.Id == id);
if (hairPrestation == null)
{
return NotFound();
}
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 NotFound();
}
HairPrestation hairPrestation = await _context.HairPrestation.SingleAsync(m => m.Id == id);
if (hairPrestation == null)
{
return NotFound();
}
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 Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Haircut;
using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
[Authorize("AdministratorOnly")]
public class HairTaintsController : Controller
{
private readonly 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 NotFound();
}
HairTaint hairTaint = await _context.HairTaint.SingleAsync(m => m.Id == id);
if (hairTaint == null)
{
return NotFound();
}
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 NotFound();
}
HairTaint hairTaint = await _context.HairTaint.SingleAsync(m => m.Id == id);
if (hairTaint == null)
{
return NotFound();
}
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 NotFound();
}
HairTaint hairTaint = await _context.HairTaint.SingleAsync(m => m.Id == id);
if (hairTaint == null)
{
return NotFound();
}
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,138 @@
using Microsoft.AspNetCore.Mvc;
using Yavsc.Models;
using Yavsc.Helpers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Localization;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.Extensions.Options;
using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
[AllowAnonymous]
public class HomeController : Controller
{
readonly ApplicationDbContext _dbContext;
readonly IHtmlLocalizer _localizer;
private SiteSettings siteSettings;
public HomeController(ILogger<HomeController> logger,
IHtmlLocalizer<Startup> localizer,
ApplicationDbContext context,
IOptions<SiteSettings> settingsOptions)
{
_localizer = localizer;
_dbContext = context;
siteSettings = settingsOptions.Value;
}
public async Task<IActionResult> Index(string id)
{
ViewBag.IsFromSecureProx = Request.Headers.ContainsKey(Constants.SshHeaderKey) && Request.Headers[Constants.SshHeaderKey] == "on";
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.DismissClicked.Where(d => d.UserId == uid).Select(d => d.NotificationId).ToArray();
var notes = _dbContext.Notification.Where(
n => !clicked.Contains(n.Id)
);
if (notes.Any()) this.Notify(notes);
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);
}
public async Task<IActionResult> About()
{
return View("About");
}
public IActionResult Privacy()
{
return View();
}
public IActionResult AboutMarkdown()
{
return View();
}
public IActionResult Contact()
{
return View(siteSettings);
}
public IActionResult Dash()
{
return View();
}
public ActionResult Chat()
{
if (User.Identity.IsAuthenticated)
{
ViewBag.IsAuthenticated = true;
string uid = User.GetUserId();
ViewBag.Contacts = _dbContext.Contact.Where(c => c.OwnerId == uid)
;
}
else ViewBag.IsAuthenticated = false;
return View();
}
public IActionResult Error()
{
var feature = this.HttpContext.Features.Get<IExceptionHandlerFeature>();
if (feature == null) return View();
var errorType = feature?.Error;
if (errorType == null) return View();
if (errorType is NotSupportedException notSupported)
{
return View(new ErrorViewModel {
Description = notSupported.Message,
RequestId = this.HttpContext.TraceIdentifier
});
}
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,161 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Yavsc.Models;
using Yavsc.Server.Models.IT.SourceCode;
using Yavsc.Helpers;
using Microsoft.EntityFrameworkCore;
using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
[Authorize("AdministratorOnly")]
public class GitController : Controller
{
private readonly ApplicationDbContext _context;
public GitController(ApplicationDbContext context)
{
_context = context;
}
[Route("~/Git/sources/{*path}")]
[HttpGet]
public IActionResult Sources(string path)
{
if (path == null)
{
return NotFound();
}
/*
GitRepositoryReference gitRepositoryReference = await _context.GitRepositoryReference.SingleAsync(m => m.Path == path);
if (gitRepositoryReference == null)
{
return NotFound();
}
*/
var info = Config.GitOptions.FileProvider.GetFileInfo(path);
if (!info.Exists)
return NotFound();
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
[HttpGet]
public async Task<IActionResult> Index()
{
var applicationDbContext = _context.GitRepositoryReference.Include(g => g.Owner);
return View(await applicationDbContext.ToListAsync());
}
// GET: Git/Details/5
[HttpGet]
public async Task<IActionResult> Details(long id)
{
GitRepositoryReference gitRepositoryReference = await _context.GitRepositoryReference.SingleAsync(m => m.Id == id);
if (gitRepositoryReference == null)
{
return NotFound();
}
return View(gitRepositoryReference);
}
// GET: Git/Create
[HttpGet]
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
[HttpGet]
public async Task<IActionResult> Edit(long id)
{
GitRepositoryReference gitRepositoryReference = await _context.GitRepositoryReference.SingleAsync(m => m.Id == id);
if (gitRepositoryReference == null)
{
return NotFound();
}
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")]
[HttpGet]
public async Task<IActionResult> Delete(string id)
{
if (id == null)
{
return NotFound();
}
GitRepositoryReference gitRepositoryReference = await _context.GitRepositoryReference.SingleAsync(m => m.Path == id);
if (gitRepositoryReference == null)
{
return NotFound();
}
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,166 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Yavsc.Models;
using Yavsc.Server.Models.IT;
using Microsoft.AspNetCore.Authorization;
using Yavsc.Server.Helpers;
using Yavsc.Models.Workflow;
using Yavsc.Models.Payment;
using Yavsc.Server.Models.IT.SourceCode;
using Microsoft.Extensions.Localization;
using Microsoft.EntityFrameworkCore;
namespace Yavsc.Controllers
{
[Authorize("AdministratorOnly")]
public class ProjectController : Controller
{
private readonly ApplicationDbContext _context;
readonly IStringLocalizer<ProjectController> _localizer;
readonly IStringLocalizer<BugController> _bugLocalizer;
public ProjectController(ApplicationDbContext context,
IStringLocalizer<ProjectController> localizer,
IStringLocalizer<BugController> bugLocalizer
)
{
_context = context;
_localizer = localizer;
_bugLocalizer = bugLocalizer;
}
// GET: Project
public async Task<IActionResult> Index()
{
var applicationDbContext = _context.Project.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 NotFound();
}
Project project = await _context.Project.SingleAsync(m => m.Id == id);
if (project == null)
{
return NotFound();
}
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.PayPalPayment.CreateSelectListItems<PayPalPayment>
(p => p.OrderReference, p => $"{p.Executor.UserName} {p.PaypalPayerId} {p.OrderReference}");
ViewBag.Status = _bugLocalizer.CreateSelectListItems(typeof(Yavsc.QueryStatus), Yavsc.QueryStatus.Inserted);
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.Project.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.PayPalPayment.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 NotFound();
}
Project project = await _context.Project.SingleAsync(m => m.Id == id);
if (project == null)
{
return NotFound();
}
/* 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 NotFound();
}
Project project = await _context.Project.SingleAsync(m => m.Id == id);
if (project == null)
{
return NotFound();
}
return View(project);
}
// POST: Project/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(long id)
{
Project project = await _context.Project.SingleAsync(m => m.Id == id);
_context.Project.Remove(project);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
}
}

View file

@ -0,0 +1,146 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Yavsc.Models;
using Yavsc.Models.Musical;
using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
public class InstrumentRatingController : Controller
{
private readonly ApplicationDbContext _context;
public InstrumentRatingController(ApplicationDbContext context)
{
_context = context;
}
// GET: InstrumentRating
public async Task<IActionResult> Index()
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
var applicationDbContext =
_context.InstrumentRating
.Include(i => i.Profile)
.Include(i => i.Instrument)
.Where(i => i.OwnerId == uid);
return View(await applicationDbContext.ToListAsync());
}
// GET: InstrumentRating/Details/5
public async Task<IActionResult> Details(long? id)
{
if (id == null)
{
return NotFound();
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
InstrumentRating instrumentRating = await _context.InstrumentRating
.Include(i => i.Instrument).SingleAsync(m => m.Id == id);
if (instrumentRating == null)
{
return NotFound();
}
return View(instrumentRating);
}
// GET: InstrumentRating/Create
public async Task<IActionResult> Create()
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
var actual = await _context.InstrumentRating
.Where(m => m.OwnerId == uid). Select( r => r.InstrumentId ).ToArrayAsync();
ViewBag.YetAvailableInstruments = _context.Instrument.Select(k=>new SelectListItem
{ Text = k.Name, Value = k.Id.ToString(), Disabled = actual.Contains(k.Id) });
if (User.IsInMsRole("Administrator"))
ViewBag.OwnerIds = new SelectList(_context.Performers, "PerformerId", "Profile");
return View();
}
// POST: InstrumentRating/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(InstrumentRating instrumentRating)
{
if (ModelState.IsValid)
{
_context.InstrumentRating.Add(instrumentRating);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewData["OwnerId"] = new SelectList(_context.Performers, "PerformerId", "Profile", instrumentRating.OwnerId);
return View(instrumentRating);
}
// GET: InstrumentRating/Edit/5
public async Task<IActionResult> Edit(long? id)
{
if (id == null)
{
return NotFound();
}
InstrumentRating instrumentRating = await _context.InstrumentRating.SingleAsync(m => m.Id == id);
if (instrumentRating == null)
{
return NotFound();
}
ViewData["OwnerId"] = new SelectList(_context.Performers, "PerformerId", "Profile", instrumentRating.OwnerId);
return View(instrumentRating);
}
// POST: InstrumentRating/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(InstrumentRating instrumentRating)
{
if (ModelState.IsValid)
{
_context.Update(instrumentRating);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewData["OwnerId"] = new SelectList(_context.Performers, "PerformerId", "Profile", instrumentRating.OwnerId);
return View(instrumentRating);
}
// GET: InstrumentRating/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(long? id)
{
if (id == null)
{
return NotFound();
}
InstrumentRating instrumentRating = await _context.InstrumentRating
.Include(i => i.Instrument).SingleAsync(m => m.Id == id);
if (instrumentRating == null)
{
return NotFound();
}
return View(instrumentRating);
}
// POST: InstrumentRating/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(long id)
{
InstrumentRating instrumentRating = await _context.InstrumentRating.SingleAsync(m => m.Id == id);
_context.InstrumentRating.Remove(instrumentRating);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
}
}

View file

@ -0,0 +1,149 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Musical.Profiles;
using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
[Authorize]
public class InstrumentationController : Controller
{
private readonly 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 NotFound();
}
Instrumentation musicianSettings = await _context.Instrumentation.SingleAsync(m => m.UserId == id);
if (musicianSettings == null)
{
return NotFound();
}
return View(musicianSettings);
}
// GET: Instrumentation/Create
public IActionResult Create()
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
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.FindFirstValue(ClaimTypes.NameIdentifier);
if (ModelState.IsValid)
{
if (model.UserId != uid) if (!User.IsInMsRole(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.FindFirstValue(ClaimTypes.NameIdentifier);
if (id == null)
{
return NotFound();
}
if (id != uid) if (!User.IsInMsRole(Constants.AdminGroupName))
return new ChallengeResult();
Instrumentation musicianSettings = await _context.Instrumentation.SingleAsync(m => m.UserId == id);
if (musicianSettings == null)
{
return NotFound();
}
return View(musicianSettings);
}
// POST: Instrumentation/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(Instrumentation musicianSettings)
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (musicianSettings.UserId != uid) if (!User.IsInMsRole(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 NotFound();
}
Instrumentation musicianSettings = await _context.Instrumentation.SingleAsync(m => m.UserId == id);
if (musicianSettings == null)
{
return NotFound();
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (musicianSettings.UserId != uid) if (!User.IsInMsRole(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.FindFirstValue(ClaimTypes.NameIdentifier);
if (musicianSettings.UserId != uid) if (!User.IsInMsRole(Constants.AdminGroupName))
return new ChallengeResult();
_context.Instrumentation.Remove(musicianSettings);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
}
}

View file

@ -0,0 +1,123 @@
using System.Linq;
using Microsoft.AspNetCore.Mvc;
namespace Yavsc.Controllers
{
using System.Security.Claims;
using Models;
using Models.Musical;
using Yavsc.Helpers;
using Yavsc.Server.Helpers;
public class InstrumentsController : Controller
{
private readonly 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 NotFound();
}
Instrument instrument = _context.Instrument.Single(m => m.Id == id);
if (instrument == null)
{
return NotFound();
}
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 NotFound();
}
Instrument instrument = _context.Instrument.Single(m => m.Id == id);
if (instrument == null)
{
return NotFound();
}
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 NotFound();
}
Instrument instrument = _context.Instrument.Single(m => m.Id == id);
if (instrument == null)
{
return NotFound();
}
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,59 @@
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace Yavsc
{
public class SecurityHeadersAttribute : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext context)
{
var result = context.Result;
if (result is ViewResult)
{
#pragma warning disable ASP0019 // Suggest using IHeaderDictionary.Append or the indexer
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options
if (!context.HttpContext.Response.Headers.ContainsKey("X-Content-Type-Options"))
{
context.HttpContext.Response.Headers.Add("X-Content-Type-Options", "nosniff");
}
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options
if (!context.HttpContext.Response.Headers.ContainsKey("X-Frame-Options"))
{
context.HttpContext.Response.Headers.Add("X-Frame-Options", "SAMEORIGIN");
}
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
var csp = "default-src 'self'; object-src 'none'; frame-ancestors 'none'; sandbox allow-forms allow-same-origin allow-scripts; base-uri 'self';";
// also consider adding upgrade-insecure-requests once you have HTTPS in place for production
//csp += "upgrade-insecure-requests;";
// also an example if you need client images to be displayed from twitter
// csp += "img-src 'self' https://pbs.twimg.com;";
// once for standards compliant browsers
if (!context.HttpContext.Response.Headers.ContainsKey("Content-Security-Policy"))
{
context.HttpContext.Response.Headers.Add("Content-Security-Policy", csp);
}
// and once again for IE
if (!context.HttpContext.Response.Headers.ContainsKey("X-Content-Security-Policy"))
{
context.HttpContext.Response.Headers.Add("X-Content-Security-Policy", csp);
}
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy
var referrer_policy = "no-referrer";
if (!context.HttpContext.Response.Headers.ContainsKey("Referrer-Policy"))
{
context.HttpContext.Response.Headers.Add("Referrer-Policy", referrer_policy);
}
#pragma warning restore ASP0019 // Suggest using IHeaderDictionary.Append or the indexer
}
}
}
}

View file

@ -0,0 +1,186 @@
using Microsoft.AspNetCore.Mvc;
using Yavsc.Models;
using Yavsc.Models.IT.Fixing;
using Yavsc.Models.IT.Evolution;
using Yavsc.Server.Helpers;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Localization;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
namespace Yavsc.Controllers
{
public class BugController : Controller
{
readonly ApplicationDbContext _context;
readonly IStringLocalizer<BugController> _localizer;
readonly IStringLocalizer<Yavsc.Models.IT.Fixing.Resources> _statusLocalizer;
public BugController(ApplicationDbContext context,
IStringLocalizer<BugController> localizer,
IStringLocalizer<Resources> statusLocalizer
)
{
_context = context;
_localizer = localizer;
_statusLocalizer = statusLocalizer;
}
// GET: Bug
public async Task<IActionResult> Index(int skip = 0, int take = 25)
{
if (take > 50) return BadRequest();
ViewData["skip"]=skip;
ViewData["take"]=take;
return View(await _context.Bug.Skip(skip).Take(take).ToListAsync());
}
// GET: Bug/Details/5
public async Task<IActionResult> Details(long? id)
{
if (id == null)
{
return NotFound();
}
Bug bug = await _context.Bug.SingleAsync(m => m.Id == id);
if (bug == null)
{
return NotFound();
}
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) =>
_statusLocalizer.CreateSelectListItems(typeof(BugStatus), status);
IEnumerable<SelectListItem> Features(ApplicationDbContext context) =>
context.Feature.CreateSelectListItems<Feature>(f => f.Id.ToString(), f => $"{f.ShortName} ({f.Description})", 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");
}
ViewBag.Features = Features(_context);
ViewBag.Statuses = Statuses(default(BugStatus));
return View(bug);
}
// GET: Bug/Edit/5
[Authorize("AdministratorOnly")]
public async Task<IActionResult> Edit(long? id)
{
if (id == null)
{
return NotFound();
}
Bug bug = await _context.Bug.SingleAsync(m => m.Id == id);
if (bug == null)
{
return NotFound();
}
ViewBag.Features = Features(_context);
ViewBag.Statuses = Statuses(bug.Status);
return View(bug);
}
// POST: Bug/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize("AdministratorOnly")]
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")]
[Authorize("AdministratorOnly")]
public async Task<IActionResult> Delete(long? id)
{
if (id == null)
{
return NotFound();
}
Bug bug = await _context.Bug.SingleAsync(m => m.Id == id);
if (bug == null)
{
return NotFound();
}
return View(bug);
}
// POST: Bug/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
[Authorize("AdministratorOnly")]
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");
}
[Authorize("AdministratorOnly")]
public async Task<IActionResult> DeleteAllLike(long? id)
{
if (id == null)
{
return NotFound();
}
Bug bugref = await _context.Bug.SingleAsync(m => m.Id == id);
if (bugref == null)
{
return null;
}
var bugs = _context.Bug.Where(b => b.Description == bugref.Description);
return View(bugs);
}
// POST: Bug/Delete/5
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize("AdministratorOnly")]
public async Task<IActionResult> DeleteAllLikeConfirmed(long id, int prefixLen = 25)
{
Bug bug = await _context.Bug.SingleAsync(m => m.Id == id);
var bugs = await _context.Bug.Where(b => b.Description.Substring(0, prefixLen) == bug.Description.Substring(0, prefixLen)).ToArrayAsync();
foreach (var btd in bugs)
_context.Bug.Remove(btd);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
}
}

View file

@ -0,0 +1,136 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace Yavsc.Controllers
{
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Models;
using Models.IT.Evolution;
using Yavsc.Server.Helpers;
public class FeatureController : Controller
{
private readonly ApplicationDbContext _context;
private readonly IStringLocalizer<BugController> _bugLocalizer;
IEnumerable<SelectListItem> Statuses(FeatureStatus ?status) =>
_bugLocalizer.CreateSelectListItems(typeof(FeatureStatus), status);
public FeatureController(ApplicationDbContext context, IStringLocalizer<BugController> bugLocalizer)
{
_context = context;
_bugLocalizer = bugLocalizer;
}
// 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 NotFound();
}
Feature feature = await _context.Feature.SingleAsync(m => m.Id == id);
if (feature == null)
{
return NotFound();
}
return View(feature);
}
// GET: Feature/Create
public IActionResult Create()
{
ViewBag.FeatureStatus = Statuses(default(FeatureStatus));
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");
}
ViewBag.FeatureStatus = Statuses(default(FeatureStatus));
return View(feature);
}
// GET: Feature/Edit/5
public async Task<IActionResult> Edit(long? id)
{
if (id == null)
{
return NotFound();
}
Feature feature = await _context.Feature.SingleAsync(m => m.Id == id);
if (feature == null)
{
return NotFound();
}
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 NotFound();
}
Feature feature = await _context.Feature.SingleAsync(m => m.Id == id);
if (feature == null)
{
return NotFound();
}
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,16 @@
using Microsoft.AspNetCore.Mvc;
namespace Yavsc.Controllers
{
public class TestController: Controller
{
public IActionResult CalendarEventDateComponent()
{
return View();
}
public IActionResult MarkdownForms()
{
return View();
}
}
}