This commit is contained in:
511
Yavsc/Controllers/AccountController.cs
Normal file
511
Yavsc/Controllers/AccountController.cs
Normal file
@ -0,0 +1,511 @@
|
||||
|
||||
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNet.Authorization;
|
||||
using Microsoft.AspNet.Identity;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.AspNet.Mvc.Rendering;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.OptionsModel;
|
||||
using Yavsc.Extensions;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Services;
|
||||
using Yavsc.ViewModels.Account;
|
||||
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[ServiceFilter(typeof(LanguageActionFilter)),AllowAnonymous]
|
||||
public class AccountController : Controller
|
||||
{
|
||||
private readonly UserManager<ApplicationUser> _userManager;
|
||||
private readonly SignInManager<ApplicationUser> _signInManager;
|
||||
private readonly IEmailSender _emailSender;
|
||||
// private readonly ISmsSender _smsSender;
|
||||
private readonly ILogger _logger;
|
||||
SiteSettings _siteSettings;
|
||||
SmtpSettings _smtpSettings;
|
||||
TwilioSettings _twilioSettings;
|
||||
|
||||
// TwilioSettings _twilioSettings;
|
||||
|
||||
public AccountController(
|
||||
UserManager<ApplicationUser> userManager,
|
||||
SignInManager<ApplicationUser> signInManager,
|
||||
IEmailSender emailSender,
|
||||
IOptions<SiteSettings> siteSettings,
|
||||
IOptions<SmtpSettings> smtpSettings,
|
||||
ILoggerFactory loggerFactory, IOptions<TwilioSettings> twilioSettings)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_signInManager = signInManager;
|
||||
// _userManager.RegisterTokenProvider("SMS",new UserTokenProvider());
|
||||
// _userManager.RegisterTokenProvider("Phone", new UserTokenProvider());
|
||||
_emailSender = emailSender;
|
||||
_siteSettings = siteSettings.Value;
|
||||
_smtpSettings = smtpSettings.Value;
|
||||
_twilioSettings = twilioSettings.Value;
|
||||
_logger = loggerFactory.CreateLogger<AccountController>();
|
||||
}
|
||||
|
||||
[HttpGet("~/login")]
|
||||
public IActionResult Login(string returnUrl)
|
||||
{
|
||||
return View("SignIn", new LoginViewModel {
|
||||
ReturnUrl = returnUrl,
|
||||
ExternalProviders = HttpContext.GetExternalProviders()
|
||||
});
|
||||
}
|
||||
|
||||
[HttpPost("~/login")]
|
||||
public async Task<IActionResult> SignIn(LoginViewModel model)
|
||||
{
|
||||
if (ModelState.IsValid)
|
||||
{
|
||||
// This doesn't count login failures towards account lockout
|
||||
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
|
||||
var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, lockoutOnFailure: false);
|
||||
if (result.Succeeded)
|
||||
{
|
||||
return RedirectToLocal(model.ReturnUrl);
|
||||
}
|
||||
if (result.RequiresTwoFactor)
|
||||
{
|
||||
return RedirectToAction(nameof(SendCode), new { ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
|
||||
}
|
||||
if (result.IsLockedOut)
|
||||
{
|
||||
_logger.LogWarning(2, "User account locked out.");
|
||||
return View("Lockout");
|
||||
}
|
||||
else
|
||||
{
|
||||
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
|
||||
return View(model);
|
||||
}
|
||||
}
|
||||
|
||||
// If we got this far, something failed, redisplay form
|
||||
ModelState.AddModelError(string.Empty, "Unexpected behavior: something failed ... you could try again, or contact me ...");
|
||||
return View(model);
|
||||
}
|
||||
//
|
||||
// GET: /Account/Register
|
||||
[HttpGet]
|
||||
public IActionResult Register()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
|
||||
//
|
||||
// POST: /Account/Register
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Register(RegisterViewModel model)
|
||||
{
|
||||
if (ModelState.IsValid)
|
||||
{
|
||||
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
|
||||
var result = await _userManager.CreateAsync(user, model.Password);
|
||||
if (result.Succeeded)
|
||||
{
|
||||
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
|
||||
// Send an email with this link
|
||||
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
|
||||
var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
|
||||
await _emailSender.SendEmailAsync(_siteSettings, _smtpSettings, model.Email, "Confirm your account",
|
||||
"Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>");
|
||||
// await _signInManager.SignInAsync(user, isPersistent: false);
|
||||
_logger.LogInformation(3, "User created a new account with password.");
|
||||
return RedirectToAction(nameof(HomeController.Index), "Home");
|
||||
}
|
||||
AddErrors(result);
|
||||
}
|
||||
|
||||
// If we got this far, something failed, redisplay form
|
||||
return View(model);
|
||||
}
|
||||
|
||||
//
|
||||
// POST: /Account/LogOff
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> LogOff(string returnUrl = null)
|
||||
{
|
||||
await _signInManager.SignOutAsync();
|
||||
_logger.LogInformation(4, "User logged out.");
|
||||
if (returnUrl==null) return RedirectToAction(nameof(HomeController.Index), "Home");
|
||||
return Redirect(returnUrl);
|
||||
}
|
||||
|
||||
//
|
||||
// POST: /Account/ExternalLogin
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken]
|
||||
public IActionResult ExternalLogin(string provider, string returnUrl = null)
|
||||
{
|
||||
// Request a redirect to the external login provider.
|
||||
var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl });
|
||||
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
|
||||
return new ChallengeResult(provider, properties);
|
||||
}
|
||||
|
||||
//
|
||||
// GET: /Account/ExternalLoginCallback
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null)
|
||||
{
|
||||
var info = await _signInManager.GetExternalLoginInfoAsync();
|
||||
if (info == null)
|
||||
{
|
||||
return Redirect("~/signin"); // RedirectToAction(nameof(OAuthController.SignIn));
|
||||
}
|
||||
|
||||
// Sign in the user with this external login provider if the user already has a login.
|
||||
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
|
||||
if (result.Succeeded)
|
||||
{
|
||||
_logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider);
|
||||
|
||||
return RedirectToLocal(returnUrl);
|
||||
}
|
||||
if (result.RequiresTwoFactor)
|
||||
{
|
||||
return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl });
|
||||
}
|
||||
if (result.IsLockedOut)
|
||||
{
|
||||
return View("Lockout");
|
||||
}
|
||||
else
|
||||
{
|
||||
// If the user does not have an account, then ask the user to create an account.
|
||||
ViewData["ReturnUrl"] = returnUrl;
|
||||
ViewData["LoginProvider"] = info.LoginProvider;
|
||||
var email = info.ExternalPrincipal.FindFirstValue(ClaimTypes.Email);
|
||||
var name = info.ExternalPrincipal.FindFirstValue(ClaimTypes.Name);
|
||||
var avatar = info.ExternalPrincipal.FindFirstValue("urn:google:profile");
|
||||
/* var phone = info.ExternalPrincipal.FindFirstValue(ClaimTypes.HomePhone);
|
||||
var mobile = info.ExternalPrincipal.FindFirstValue(ClaimTypes.MobilePhone);
|
||||
var postalcode = info.ExternalPrincipal.FindFirstValue(ClaimTypes.PostalCode);
|
||||
var locality = info.ExternalPrincipal.FindFirstValue(ClaimTypes.Locality);
|
||||
var country = info.ExternalPrincipal.FindFirstValue(ClaimTypes.Country);*/
|
||||
foreach (var claim in info.ExternalPrincipal.Claims)
|
||||
_logger.LogWarning("# {0} Claim: {1} {2}", info.LoginProvider, claim.Type, claim.Value);
|
||||
|
||||
var access_token = info.ExternalPrincipal.FindFirstValue("access_token");
|
||||
var token_type = info.ExternalPrincipal.FindFirstValue("token_type");
|
||||
var expires_in = info.ExternalPrincipal.FindFirstValue("expires_in");
|
||||
|
||||
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel
|
||||
{
|
||||
Email = email,
|
||||
Name = name
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// POST: /Account/ExternalLoginConfirmation
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null)
|
||||
{
|
||||
if (User.IsSignedIn())
|
||||
{
|
||||
return RedirectToAction(nameof(ManageController.Index), "Manage");
|
||||
}
|
||||
|
||||
if (ModelState.IsValid)
|
||||
{
|
||||
// Get the information about the user from the external login provider
|
||||
var info = await _signInManager.GetExternalLoginInfoAsync();
|
||||
if (info == null)
|
||||
{
|
||||
return View("ExternalLoginFailure");
|
||||
}
|
||||
var user = new ApplicationUser { UserName = model.Name, Email = model.Email };
|
||||
var result = await _userManager.CreateAsync(user);
|
||||
if (result.Succeeded)
|
||||
{
|
||||
result = await _userManager.AddLoginAsync(user, info);
|
||||
if (result.Succeeded)
|
||||
{
|
||||
await _signInManager.SignInAsync(user, isPersistent: false);
|
||||
_logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider);
|
||||
|
||||
return RedirectToLocal(returnUrl);
|
||||
}
|
||||
}
|
||||
AddErrors(result);
|
||||
}
|
||||
|
||||
ViewData["ReturnUrl"] = returnUrl;
|
||||
return View(model);
|
||||
}
|
||||
|
||||
// GET: /Account/ConfirmEmail
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> ConfirmEmail(string userId, string code)
|
||||
{
|
||||
if (userId == null || code == null)
|
||||
{
|
||||
return View("Error");
|
||||
}
|
||||
var user = await _userManager.FindByIdAsync(userId);
|
||||
if (user == null)
|
||||
{
|
||||
return View("Error");
|
||||
}
|
||||
var result = await _userManager.ConfirmEmailAsync(user, code);
|
||||
return View(result.Succeeded ? "ConfirmEmail" : "Error");
|
||||
}
|
||||
|
||||
//
|
||||
// GET: /Account/ForgotPassword
|
||||
[HttpGet]
|
||||
public IActionResult ForgotPassword()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
|
||||
//
|
||||
// POST: /Account/ForgotPassword
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
|
||||
{
|
||||
if (ModelState.IsValid)
|
||||
{
|
||||
var user = await _userManager.FindByNameAsync(model.Email);
|
||||
if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
|
||||
{
|
||||
// Don't reveal that the user does not exist or is not confirmed
|
||||
return View("ForgotPasswordConfirmation");
|
||||
}
|
||||
|
||||
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
|
||||
// Send an email with this link
|
||||
//var code = await _userManager.GeneratePasswordResetTokenAsync(user);
|
||||
//var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
|
||||
//await _emailSender.SendEmailAsync(model.Email, "Reset Password",
|
||||
// "Please reset your password by clicking here: <a href=\"" + callbackUrl + "\">link</a>");
|
||||
//return View("ForgotPasswordConfirmation");
|
||||
}
|
||||
|
||||
// If we got this far, something failed, redisplay form
|
||||
return View(model);
|
||||
}
|
||||
|
||||
//
|
||||
// GET: /Account/ForgotPasswordConfirmation
|
||||
[HttpGet]
|
||||
public IActionResult ForgotPasswordConfirmation()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
|
||||
//
|
||||
// GET: /Account/ResetPassword
|
||||
[HttpGet]
|
||||
public IActionResult ResetPassword(string code = null)
|
||||
{
|
||||
return code == null ? View("Error") : View();
|
||||
}
|
||||
|
||||
//
|
||||
// POST: /Account/ResetPassword
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return View(model);
|
||||
}
|
||||
var user = await _userManager.FindByNameAsync(model.Email);
|
||||
if (user == null)
|
||||
{
|
||||
// Don't reveal that the user does not exist
|
||||
return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account");
|
||||
}
|
||||
var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password);
|
||||
if (result.Succeeded)
|
||||
{
|
||||
return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account");
|
||||
}
|
||||
AddErrors(result);
|
||||
return View();
|
||||
}
|
||||
|
||||
//
|
||||
// GET: /Account/ResetPasswordConfirmation
|
||||
[HttpGet]
|
||||
public IActionResult ResetPasswordConfirmation()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
|
||||
//
|
||||
// GET: /Account/SendCode
|
||||
[HttpGet, AllowAnonymous]
|
||||
public async Task<ActionResult> SendCode(string returnUrl = null, bool rememberMe = false)
|
||||
{
|
||||
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
|
||||
if (user == null)
|
||||
{
|
||||
return View("Error", new Exception("No Two factor authentication user"));
|
||||
}
|
||||
var userFactors = await _userManager.GetValidTwoFactorProvidersAsync(user);
|
||||
|
||||
|
||||
var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
|
||||
return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
|
||||
}
|
||||
|
||||
//
|
||||
// POST: /Account/SendCode
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken, AllowAnonymous]
|
||||
public async Task<IActionResult> SendCode(SendCodeViewModel model)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return View();
|
||||
}
|
||||
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
|
||||
if (user == null)
|
||||
{
|
||||
return View("Error", new Exception("user is null"));
|
||||
}
|
||||
|
||||
// Generate the token and send it
|
||||
var code = await _userManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider);
|
||||
if (string.IsNullOrWhiteSpace(code))
|
||||
{
|
||||
return View("Error", new Exception("Code is empty"));
|
||||
}
|
||||
|
||||
var message = "Your security code is: " + code;
|
||||
if (model.SelectedProvider == Constants.MobileAppFactor)
|
||||
{
|
||||
return View("Error", new Exception("No SMS service was activated"));
|
||||
}
|
||||
else // if (model.SelectedProvider == Constants.EMailFactor || model.SelectedProvider == "Default" )
|
||||
if (model.SelectedProvider == Constants.SMSFactor)
|
||||
{
|
||||
return View("Error", new Exception("No SMS service was activated"));
|
||||
// await _smsSender.SendSmsAsync(_twilioSettings, await _userManager.GetPhoneNumberAsync(user), message);
|
||||
}
|
||||
else // if (model.SelectedProvider == Constants.EMailFactor || model.SelectedProvider == "Default" )
|
||||
{
|
||||
await _emailSender.SendEmailAsync(_siteSettings, _smtpSettings, await _userManager.GetEmailAsync(user), "Security Code", message);
|
||||
}
|
||||
return RedirectToAction(nameof(VerifyCode), new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
|
||||
}
|
||||
|
||||
//
|
||||
// GET: /Account/VerifyCode
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> VerifyCode(string provider, bool rememberMe, string returnUrl = null)
|
||||
{
|
||||
// Require that the user has already logged in via username/password or external login
|
||||
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
|
||||
if (user == null)
|
||||
{
|
||||
return View("Error", new Exception("user is null"));
|
||||
}
|
||||
return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
|
||||
}
|
||||
|
||||
//
|
||||
// POST: /Account/VerifyCode
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> VerifyCode(VerifyCodeViewModel model)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return View(model);
|
||||
}
|
||||
|
||||
// The following code protects for brute force attacks against the two factor codes.
|
||||
// If a user enters incorrect codes for a specified amount of time then the user account
|
||||
// will be locked out for a specified amount of time.
|
||||
_logger.LogWarning("Signin with code: {0} {1}", model.Provider, model.Code);
|
||||
var result = await _signInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser);
|
||||
if (result.Succeeded)
|
||||
{
|
||||
ViewData["StatusMessage"] = "Your code was verified";
|
||||
return RedirectToLocal(model.ReturnUrl);
|
||||
}
|
||||
if (result.IsLockedOut)
|
||||
{
|
||||
_logger.LogWarning(7, "User account locked out.");
|
||||
return View("Lockout");
|
||||
}
|
||||
else
|
||||
{
|
||||
ModelState.AddModelError("", "Code invalide ");
|
||||
return View(model);
|
||||
}
|
||||
}
|
||||
|
||||
[HttpGet, Authorize]
|
||||
public IActionResult Delete()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
|
||||
[HttpPost, Authorize]
|
||||
public async Task<IActionResult> Delete(UnregisterViewModel model)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return View(model);
|
||||
}
|
||||
var user = await _userManager.FindByIdAsync(User.GetUserId());
|
||||
var result = await _userManager.DeleteAsync(user);
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
AddErrors(result);
|
||||
return new BadRequestObjectResult(ModelState);
|
||||
}
|
||||
await _signInManager.SignOutAsync();
|
||||
|
||||
return RedirectToAction("Index", "Home");
|
||||
}
|
||||
|
||||
#region Helpers
|
||||
|
||||
private void AddErrors(IdentityResult result)
|
||||
{
|
||||
foreach (var error in result.Errors)
|
||||
{
|
||||
ModelState.AddModelError(string.Empty, error.Description);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<ApplicationUser> GetCurrentUserAsync()
|
||||
{
|
||||
return await _userManager.FindByIdAsync(HttpContext.User.GetUserId());
|
||||
}
|
||||
|
||||
private IActionResult RedirectToLocal(string returnUrl)
|
||||
{
|
||||
if (Url.IsLocalUrl(returnUrl))
|
||||
{
|
||||
return Redirect(returnUrl);
|
||||
}
|
||||
else
|
||||
{
|
||||
return RedirectToAction(nameof(HomeController.Index), "Home");
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
120
Yavsc/Controllers/ActivityController.cs
Normal file
120
Yavsc/Controllers/ActivityController.cs
Normal file
@ -0,0 +1,120 @@
|
||||
using System.Linq;
|
||||
using Microsoft.AspNet.Authorization;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Yavsc.Models;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[ServiceFilter(typeof(LanguageActionFilter)),Authorize("AdministratorOnly")]
|
||||
public class ActivityController : Controller
|
||||
{
|
||||
private ApplicationDbContext _context;
|
||||
|
||||
public ActivityController(ApplicationDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
// GET: Activity
|
||||
public IActionResult Index()
|
||||
{
|
||||
return View(_context.Activities.ToList());
|
||||
}
|
||||
|
||||
// GET: Activity/Details/5
|
||||
public IActionResult Details(string id)
|
||||
{
|
||||
if (id == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
Activity activity = _context.Activities.Single(m => m.Code == id);
|
||||
if (activity == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
return View(activity);
|
||||
}
|
||||
|
||||
// GET: Activity/Create
|
||||
public IActionResult Create()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
|
||||
// POST: Activity/Create
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken]
|
||||
public IActionResult Create(Activity activity)
|
||||
{
|
||||
if (ModelState.IsValid)
|
||||
{
|
||||
_context.Activities.Add(activity);
|
||||
_context.SaveChanges();
|
||||
return RedirectToAction("Index");
|
||||
}
|
||||
return View(activity);
|
||||
}
|
||||
|
||||
// GET: Activity/Edit/5
|
||||
public IActionResult Edit(string id)
|
||||
{
|
||||
if (id == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
Activity activity = _context.Activities.Single(m => m.Code == id);
|
||||
if (activity == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
return View(activity);
|
||||
}
|
||||
|
||||
// POST: Activity/Edit/5
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken]
|
||||
public IActionResult Edit(Activity activity)
|
||||
{
|
||||
if (ModelState.IsValid)
|
||||
{
|
||||
_context.Update(activity);
|
||||
_context.SaveChanges();
|
||||
return RedirectToAction("Index");
|
||||
}
|
||||
return View(activity);
|
||||
}
|
||||
|
||||
// GET: Activity/Delete/5
|
||||
[ActionName("Delete")]
|
||||
public IActionResult Delete(string id)
|
||||
{
|
||||
if (id == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
Activity activity = _context.Activities.Single(m => m.Code == id);
|
||||
if (activity == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
return View(activity);
|
||||
}
|
||||
|
||||
// POST: Activity/Delete/5
|
||||
[HttpPost, ActionName("Delete")]
|
||||
[ValidateAntiForgeryToken]
|
||||
public IActionResult DeleteConfirmed(string id)
|
||||
{
|
||||
Activity activity = _context.Activities.Single(m => m.Code == id);
|
||||
_context.Activities.Remove(activity);
|
||||
_context.SaveChanges();
|
||||
return RedirectToAction("Index");
|
||||
}
|
||||
}
|
||||
}
|
94
Yavsc/Controllers/AdministrationController.cs
Normal file
94
Yavsc/Controllers/AdministrationController.cs
Normal file
@ -0,0 +1,94 @@
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNet.Authorization;
|
||||
using Microsoft.AspNet.Identity;
|
||||
using Microsoft.AspNet.Identity.EntityFramework;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Yavsc.Models;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[ServiceFilter(typeof(LanguageActionFilter)), Authorize()]
|
||||
public class AdministrationController : Controller
|
||||
{
|
||||
private readonly UserManager<ApplicationUser> _userManager;
|
||||
private readonly RoleManager<IdentityRole> _roleManager;
|
||||
|
||||
public AdministrationController(UserManager<ApplicationUser> userManager,
|
||||
RoleManager<IdentityRole> roleManager)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_roleManager = roleManager;
|
||||
}
|
||||
|
||||
/// <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) return HttpNotFound();
|
||||
var user = await _userManager.FindByIdAsync(User.GetUserId());
|
||||
|
||||
IdentityRole adminRole;
|
||||
if (!await _roleManager.RoleExistsAsync(Constants.AdminGroupName))
|
||||
{
|
||||
adminRole = new IdentityRole { Name = Constants.AdminGroupName };
|
||||
var resultCreate = await _roleManager.CreateAsync(adminRole);
|
||||
if (!resultCreate.Succeeded)
|
||||
{
|
||||
AddErrors(resultCreate);
|
||||
return new BadRequestObjectResult(ModelState);
|
||||
}
|
||||
}
|
||||
else adminRole = await _roleManager.FindByNameAsync(Constants.AdminGroupName);
|
||||
var addToRoleResult = await _userManager.AddToRoleAsync(user, Constants.AdminGroupName);
|
||||
if (!addToRoleResult.Succeeded)
|
||||
{
|
||||
AddErrors(addToRoleResult);
|
||||
return new BadRequestObjectResult(ModelState);
|
||||
}
|
||||
return Ok(new {message="you owned it."});
|
||||
}
|
||||
public class RoleInfo {
|
||||
public string Name { get; set; }
|
||||
public IEnumerable<string> Users { get; set; }
|
||||
}
|
||||
[Authorize(Roles=Constants.AdminGroupName)]
|
||||
[Produces("application/json")]
|
||||
public async Task<IActionResult> Index() {
|
||||
var adminCount = await _userManager.GetUsersInRoleAsync(
|
||||
Constants.AdminGroupName);
|
||||
var youAreAdmin = await _userManager.IsInRoleAsync(
|
||||
await _userManager.FindByIdAsync(User.GetUserId()),
|
||||
Constants.AdminGroupName);
|
||||
var roles = _roleManager.Roles.Select(x=>
|
||||
new RoleInfo {
|
||||
Name = x.Name,
|
||||
Users = x.Users.Select( u=>u.UserId )
|
||||
} );
|
||||
return Ok (new { Roles = roles, AdminCount = adminCount.Count,
|
||||
YouAreAdmin = youAreAdmin
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
private void AddErrors(IdentityResult result)
|
||||
{
|
||||
foreach (var error in result.Errors)
|
||||
{
|
||||
ModelState.AddModelError(string.Empty, error.Description);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
123
Yavsc/Controllers/ApplicationController.cs
Normal file
123
Yavsc/Controllers/ApplicationController.cs
Normal file
@ -0,0 +1,123 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using Microsoft.AspNet.Authorization;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Data.Entity;
|
||||
using Yavsc.Models;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[Authorize("AdministratorOnly")]
|
||||
public class ApplicationController : Controller
|
||||
{
|
||||
private ApplicationDbContext _context;
|
||||
|
||||
public ApplicationController(ApplicationDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
// GET: Application
|
||||
public IActionResult Index()
|
||||
{
|
||||
return View(_context.Applications.ToList());
|
||||
}
|
||||
|
||||
// GET: Application/Details/5
|
||||
public IActionResult Details(string id)
|
||||
{
|
||||
if (id == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
Application application = _context.Applications.Single(m => m.ApplicationID == id);
|
||||
if (application == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
return View(application);
|
||||
}
|
||||
|
||||
// GET: Application/Create
|
||||
public IActionResult Create()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
|
||||
// POST: Application/Create
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken]
|
||||
public IActionResult Create(Application application)
|
||||
{
|
||||
if (ModelState.IsValid)
|
||||
{
|
||||
application.ApplicationID = Guid.NewGuid().ToString();
|
||||
_context.Applications.Add(application);
|
||||
_context.SaveChanges();
|
||||
return RedirectToAction("Index");
|
||||
}
|
||||
return View(application);
|
||||
}
|
||||
|
||||
// GET: Application/Edit/5
|
||||
public IActionResult Edit(string id)
|
||||
{
|
||||
if (id == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
Application application = _context.Applications.Single(m => m.ApplicationID == id);
|
||||
if (application == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
return View(application);
|
||||
}
|
||||
|
||||
// POST: Application/Edit/5
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken]
|
||||
public IActionResult Edit(Application application)
|
||||
{
|
||||
if (ModelState.IsValid)
|
||||
{
|
||||
_context.Update(application);
|
||||
_context.SaveChanges();
|
||||
return RedirectToAction("Index");
|
||||
}
|
||||
return View(application);
|
||||
}
|
||||
|
||||
// GET: Application/Delete/5
|
||||
[ActionName("Delete")]
|
||||
public IActionResult Delete(string id)
|
||||
{
|
||||
if (id == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
Application application = _context.Applications.Single(m => m.ApplicationID == id);
|
||||
if (application == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
return View(application);
|
||||
}
|
||||
|
||||
// POST: Application/Delete/5
|
||||
[HttpPost, ActionName("Delete")]
|
||||
[ValidateAntiForgeryToken]
|
||||
public IActionResult DeleteConfirmed(string id)
|
||||
{
|
||||
Application application = _context.Applications.Single(m => m.ApplicationID == id);
|
||||
_context.Applications.Remove(application);
|
||||
_context.SaveChanges();
|
||||
return RedirectToAction("Index");
|
||||
}
|
||||
}
|
||||
}
|
203
Yavsc/Controllers/BlogspotController.cs
Normal file
203
Yavsc/Controllers/BlogspotController.cs
Normal file
@ -0,0 +1,203 @@
|
||||
using System.Linq;
|
||||
using Microsoft.AspNet.Identity;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Yavsc.Models;
|
||||
using System;
|
||||
using Microsoft.AspNet.Authorization;
|
||||
using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Data.Entity;
|
||||
using Microsoft.Extensions.OptionsModel;
|
||||
|
||||
// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[ServiceFilter(typeof(LanguageActionFilter))]
|
||||
public class BlogspotController : Controller
|
||||
{
|
||||
ILogger _logger;
|
||||
private ApplicationDbContext _context;
|
||||
|
||||
private SiteSettings _siteSettings;
|
||||
private IAuthorizationService _authorizationService;
|
||||
public BlogspotController(
|
||||
ApplicationDbContext context,
|
||||
UserManager<ApplicationUser> userManager,
|
||||
ILoggerFactory loggerFactory,
|
||||
IAuthorizationService authorizationService,
|
||||
IOptions<SiteSettings> siteSettings)
|
||||
{
|
||||
_context = context;
|
||||
_logger = loggerFactory.CreateLogger<AccountController>();
|
||||
_authorizationService = authorizationService;
|
||||
_siteSettings = siteSettings.Value;
|
||||
}
|
||||
|
||||
// GET: Blog
|
||||
[AllowAnonymous]
|
||||
public IActionResult Index(string id)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(id))
|
||||
return UserPosts(id);
|
||||
return View(_context.Blogspot.Include(
|
||||
b => b.Author
|
||||
).Where(p => p.visible));
|
||||
}
|
||||
|
||||
[Route("/Title/{id?}")]
|
||||
[AllowAnonymous]
|
||||
public IActionResult Title(string id)
|
||||
{
|
||||
return View("Index", _context.Blogspot.Include(
|
||||
b => b.Author
|
||||
).Where(x => x.title == id).ToList());
|
||||
}
|
||||
|
||||
[Route("/Blog/{id?}")]
|
||||
[AllowAnonymous]
|
||||
public IActionResult UserPosts(string id)
|
||||
{
|
||||
if (string.IsNullOrEmpty(id))
|
||||
return View("Index",_context.Blogspot.Include(
|
||||
b => b.Author
|
||||
).Where(p => p.visible));
|
||||
if (User.IsSignedIn())
|
||||
return View("Index", _context.Blogspot.Include(
|
||||
b => b.Author
|
||||
).Where(x => x.Author.UserName == id).ToList());
|
||||
return View("Index", _context.Blogspot.Include(
|
||||
b => b.Author
|
||||
).Where(x => x.Author.UserName == id && x.visible).ToList());
|
||||
}
|
||||
// GET: Blog/Details/5
|
||||
[AllowAnonymous]
|
||||
public IActionResult Details(long? id)
|
||||
{
|
||||
if (id == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
Blog blog = _context.Blogspot.Include(
|
||||
b => b.Author
|
||||
).Single(m => m.Id == id);
|
||||
if (blog == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
return View(blog);
|
||||
}
|
||||
|
||||
// GET: Blog/Create
|
||||
[Authorize()]
|
||||
public IActionResult Create()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
|
||||
// POST: Blog/Create
|
||||
[HttpPost, Authorize(), ValidateAntiForgeryToken]
|
||||
public IActionResult Create(Blog blog)
|
||||
{
|
||||
blog.modified = blog.posted = DateTime.Now;
|
||||
blog.rate = 0;
|
||||
blog.AuthorId = User.GetUserId();
|
||||
_logger.LogWarning($"Post from: {blog.AuthorId}");
|
||||
ModelState.ClearValidationState("AuthorId");
|
||||
if (ModelState.IsValid)
|
||||
{
|
||||
blog.posted = DateTime.Now;
|
||||
_context.Blogspot.Add(blog);
|
||||
_context.SaveChanges();
|
||||
return RedirectToAction("Index");
|
||||
}
|
||||
_logger.LogWarning("Invalid Blog posted ...");
|
||||
return View(blog);
|
||||
}
|
||||
[Authorize()]
|
||||
// GET: Blog/Edit/5
|
||||
public async Task<IActionResult> Edit(long? id)
|
||||
{
|
||||
if (id == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
Blog blog = _context.Blogspot.Include(x => x.Author).Single(m => m.Id == id);
|
||||
if (blog == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
if (await _authorizationService.AuthorizeAsync(User, blog, new EditRequirement()))
|
||||
{
|
||||
return View(blog);
|
||||
}
|
||||
else
|
||||
{
|
||||
return new ChallengeResult();
|
||||
}
|
||||
}
|
||||
|
||||
// POST: Blog/Edit/5
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken,Authorize()]
|
||||
public IActionResult Edit(Blog blog)
|
||||
{
|
||||
if (ModelState.IsValid)
|
||||
{
|
||||
var auth = _authorizationService.AuthorizeAsync(User, blog, new EditRequirement());
|
||||
if (auth.Result)
|
||||
{
|
||||
blog.modified = DateTime.Now;
|
||||
_context.Update(blog);
|
||||
_context.SaveChanges();
|
||||
ViewData["StatusMessage"] = "Post modified";
|
||||
return RedirectToAction("Index");
|
||||
} // TODO Else hit me hard
|
||||
else
|
||||
{
|
||||
ViewData["StatusMessage"] = "Access denied ...";
|
||||
}
|
||||
}
|
||||
return View(blog);
|
||||
}
|
||||
|
||||
// GET: Blog/Delete/5
|
||||
[ActionName("Delete"),Authorize()]
|
||||
public IActionResult Delete(long? id)
|
||||
{
|
||||
if (id == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
Blog blog = _context.Blogspot.Include(
|
||||
b => b.Author
|
||||
).Single(m => m.Id == id);
|
||||
if (blog == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
return View(blog);
|
||||
}
|
||||
|
||||
// POST: Blog/Delete/5
|
||||
[HttpPost, ActionName("Delete"), Authorize()]
|
||||
[ValidateAntiForgeryToken]
|
||||
public IActionResult DeleteConfirmed(long id)
|
||||
{
|
||||
Blog blog = _context.Blogspot.Single(m => m.Id == id);
|
||||
var auth = _authorizationService.AuthorizeAsync(User, blog, new EditRequirement());
|
||||
if (auth.Result)
|
||||
{
|
||||
_context.Blogspot.Remove(blog);
|
||||
_context.SaveChanges();
|
||||
}
|
||||
return RedirectToAction("Index");
|
||||
}
|
||||
}
|
||||
}
|
119
Yavsc/Controllers/CircleController.cs
Normal file
119
Yavsc/Controllers/CircleController.cs
Normal file
@ -0,0 +1,119 @@
|
||||
using System.Linq;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Yavsc.Models;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[ServiceFilter(typeof(LanguageActionFilter))]
|
||||
public class CircleController : Controller
|
||||
{
|
||||
private ApplicationDbContext _context;
|
||||
|
||||
public CircleController(ApplicationDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
// GET: Circle
|
||||
public IActionResult Index()
|
||||
{
|
||||
return View(_context.CircleMembers.ToList());
|
||||
}
|
||||
|
||||
// GET: Circle/Details/5
|
||||
public IActionResult Details(long? id)
|
||||
{
|
||||
if (id == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
CircleMember circleMember = _context.CircleMembers.Single(m => m.Id == id);
|
||||
if (circleMember == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
return View(circleMember);
|
||||
}
|
||||
|
||||
// GET: Circle/Create
|
||||
public IActionResult Create()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
|
||||
// POST: Circle/Create
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken]
|
||||
public IActionResult Create(CircleMember circleMember)
|
||||
{
|
||||
if (ModelState.IsValid)
|
||||
{
|
||||
_context.CircleMembers.Add(circleMember);
|
||||
_context.SaveChanges();
|
||||
return RedirectToAction("Index");
|
||||
}
|
||||
return View(circleMember);
|
||||
}
|
||||
|
||||
// GET: Circle/Edit/5
|
||||
public IActionResult Edit(long? id)
|
||||
{
|
||||
if (id == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
CircleMember circleMember = _context.CircleMembers.Single(m => m.Id == id);
|
||||
if (circleMember == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
return View(circleMember);
|
||||
}
|
||||
|
||||
// POST: Circle/Edit/5
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken]
|
||||
public IActionResult Edit(CircleMember circleMember)
|
||||
{
|
||||
if (ModelState.IsValid)
|
||||
{
|
||||
_context.Update(circleMember);
|
||||
_context.SaveChanges();
|
||||
return RedirectToAction("Index");
|
||||
}
|
||||
return View(circleMember);
|
||||
}
|
||||
|
||||
// GET: Circle/Delete/5
|
||||
[ActionName("Delete")]
|
||||
public IActionResult Delete(long? id)
|
||||
{
|
||||
if (id == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
CircleMember circleMember = _context.CircleMembers.Single(m => m.Id == id);
|
||||
if (circleMember == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
return View(circleMember);
|
||||
}
|
||||
|
||||
// POST: Circle/Delete/5
|
||||
[HttpPost, ActionName("Delete")]
|
||||
[ValidateAntiForgeryToken]
|
||||
public IActionResult DeleteConfirmed(long id)
|
||||
{
|
||||
CircleMember circleMember = _context.CircleMembers.Single(m => m.Id == id);
|
||||
_context.CircleMembers.Remove(circleMember);
|
||||
_context.SaveChanges();
|
||||
return RedirectToAction("Index");
|
||||
}
|
||||
}
|
||||
}
|
219
Yavsc/Controllers/CommandController.cs
Normal file
219
Yavsc/Controllers/CommandController.cs
Normal file
@ -0,0 +1,219 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNet.Authorization;
|
||||
using Microsoft.AspNet.Identity;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Data.Entity;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.OptionsModel;
|
||||
using Yavsc.Helpers;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Models.Booking;
|
||||
using Yavsc.Models.Google.Messaging;
|
||||
using Yavsc.Services;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[ServiceFilter(typeof(LanguageActionFilter))]
|
||||
public class CommandController : Controller
|
||||
{
|
||||
private UserManager<ApplicationUser> _userManager;
|
||||
private ApplicationDbContext _context;
|
||||
private GoogleAuthSettings _googleSettings;
|
||||
private IGoogleCloudMessageSender _GCMSender;
|
||||
private IEmailSender _emailSender;
|
||||
private IStringLocalizer _localizer;
|
||||
SiteSettings _siteSettings;
|
||||
SmtpSettings _smtpSettings;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
public CommandController(ApplicationDbContext context,IOptions<GoogleAuthSettings> googleSettings,
|
||||
IGoogleCloudMessageSender GCMSender,
|
||||
UserManager<ApplicationUser> userManager,
|
||||
IStringLocalizer<Yavsc.Resources.YavscLocalisation> localizer,
|
||||
IEmailSender emailSender,
|
||||
IOptions<SmtpSettings> smtpSettings,
|
||||
IOptions<SiteSettings> siteSettings,
|
||||
ILoggerFactory loggerFactory)
|
||||
{
|
||||
_context = context;
|
||||
_GCMSender = GCMSender;
|
||||
_emailSender = emailSender;
|
||||
_googleSettings = googleSettings.Value;
|
||||
_userManager = userManager;
|
||||
_smtpSettings = smtpSettings.Value;
|
||||
_siteSettings = siteSettings.Value;
|
||||
_localizer = localizer;
|
||||
_logger = loggerFactory.CreateLogger<CommandController>();
|
||||
}
|
||||
|
||||
// GET: Command
|
||||
public IActionResult Index()
|
||||
{
|
||||
return View(_context.BookQueries
|
||||
.Include(x=>x.Client)
|
||||
.Include(x=>x.PerformerProfile)
|
||||
.Include(x=>x.PerformerProfile.Performer)
|
||||
.Include(x=>x.Location)
|
||||
.Include(x=>x.Bill).ToList());
|
||||
}
|
||||
|
||||
// GET: Command/Details/5
|
||||
public IActionResult Details(long? id)
|
||||
{
|
||||
if (id == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
BookQuery command = _context.BookQueries
|
||||
.Include(x=>x.Location)
|
||||
.Include(x=>x.PerformerProfile)
|
||||
.Single(m => m.Id == id);
|
||||
if (command == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
return View(command);
|
||||
}
|
||||
|
||||
[Authorize]
|
||||
/// <summary>
|
||||
/// Gives a view on
|
||||
/// Creating a command for a specified performer
|
||||
/// </summary>
|
||||
/// <param name="id"></param>
|
||||
/// <returns></returns>
|
||||
public IActionResult Create(string id)
|
||||
{
|
||||
var pro = _context.Performers.Include(
|
||||
x=>x.Performer).FirstOrDefault(
|
||||
x=>x.PerfomerId == id
|
||||
);
|
||||
if (pro==null)
|
||||
return HttpNotFound();
|
||||
|
||||
ViewBag.GoogleSettings = _googleSettings;
|
||||
var userid = User.GetUserId();
|
||||
var user = _userManager.FindByIdAsync(userid).Result;
|
||||
return View(new BookQuery{
|
||||
PerformerProfile = pro,
|
||||
PerformerId = pro.PerfomerId,
|
||||
ClientId = userid,
|
||||
Client = user,
|
||||
Location = new Location(),
|
||||
EventDate = DateTime.Now.AddHours(4)
|
||||
});
|
||||
}
|
||||
|
||||
// POST: Command/Create
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Create(BookQuery command)
|
||||
{
|
||||
var pro = _context.Performers.FirstOrDefault(
|
||||
x=>x.PerfomerId == command.PerformerId
|
||||
);
|
||||
command.PerformerProfile = pro;
|
||||
var user = _userManager.FindByIdAsync(
|
||||
User.GetUserId()
|
||||
).Result;
|
||||
command.Client = user;
|
||||
if (ModelState.IsValid)
|
||||
{
|
||||
var yaev = command.CreateEvent(_localizer);
|
||||
MessageWithPayloadResponse grep=null;
|
||||
|
||||
_context.Attach<Location>(command.Location);
|
||||
_context.BookQueries.Add(command,GraphBehavior.IncludeDependents);
|
||||
_context.SaveChanges();
|
||||
if (command.PerformerProfile.AcceptNotifications
|
||||
&& command.PerformerProfile.AcceptPublicContact
|
||||
&& command.PerformerProfile.Performer.Devices.Select(d=>d.RegistrationId)!=null) {
|
||||
grep = await _GCMSender.NotifyAsync(_googleSettings,
|
||||
command.PerformerProfile.Performer.Devices.Select(d=>d.RegistrationId),
|
||||
yaev
|
||||
);
|
||||
}
|
||||
// TODO setup a profile choice to allow notifications
|
||||
// both on mailbox and mobile
|
||||
// if (grep==null || grep.success<=0 || grep.failure>0)
|
||||
{
|
||||
await _emailSender.SendEmailAsync(
|
||||
_siteSettings, _smtpSettings,
|
||||
command.PerformerProfile.Performer.Email,
|
||||
yaev.Title,
|
||||
$"{yaev.Description}\r\n-- \r\n{yaev.Comment}\r\n"
|
||||
);
|
||||
|
||||
}
|
||||
return RedirectToAction("Index");
|
||||
}
|
||||
ViewBag.GoogleSettings = _googleSettings;
|
||||
return View(command);
|
||||
}
|
||||
|
||||
// GET: Command/Edit/5
|
||||
public IActionResult Edit(long? id)
|
||||
{
|
||||
if (id == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
BookQuery command = _context.BookQueries.Single(m => m.Id == id);
|
||||
if (command == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
return View(command);
|
||||
}
|
||||
|
||||
// POST: Command/Edit/5
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken]
|
||||
public IActionResult Edit(BookQuery command)
|
||||
{
|
||||
if (ModelState.IsValid)
|
||||
{
|
||||
_context.Update(command);
|
||||
_context.SaveChanges();
|
||||
return RedirectToAction("Index");
|
||||
}
|
||||
return View(command);
|
||||
}
|
||||
|
||||
// GET: Command/Delete/5
|
||||
[ActionName("Delete")]
|
||||
public IActionResult Delete(long? id)
|
||||
{
|
||||
if (id == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
BookQuery command = _context.BookQueries.Single(m => m.Id == id);
|
||||
if (command == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
return View(command);
|
||||
}
|
||||
|
||||
// POST: Command/Delete/5
|
||||
[HttpPost, ActionName("Delete")]
|
||||
[ValidateAntiForgeryToken]
|
||||
public IActionResult DeleteConfirmed(long id)
|
||||
{
|
||||
BookQuery command = _context.BookQueries.Single(m => m.Id == id);
|
||||
_context.BookQueries.Remove(command);
|
||||
_context.SaveChanges();
|
||||
return RedirectToAction("Index");
|
||||
}
|
||||
}
|
||||
}
|
169
Yavsc/Controllers/EstimateController.cs
Normal file
169
Yavsc/Controllers/EstimateController.cs
Normal file
@ -0,0 +1,169 @@
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using Microsoft.AspNet.FileProviders;
|
||||
using Microsoft.AspNet.Http;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Data.Entity;
|
||||
using Microsoft.Extensions.OptionsModel;
|
||||
using Yavsc.Helpers;
|
||||
using Yavsc.Models;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
public class EstimateController : Controller
|
||||
{
|
||||
private ApplicationDbContext _context;
|
||||
private SiteSettings _site;
|
||||
|
||||
public EstimateController(ApplicationDbContext context, IOptions<SiteSettings> siteSettings)
|
||||
{
|
||||
_context = context;
|
||||
_site = siteSettings.Value;
|
||||
}
|
||||
|
||||
// GET: Estimate
|
||||
public IActionResult Index()
|
||||
{
|
||||
return View(_context.Estimates.ToList());
|
||||
}
|
||||
|
||||
// GET: Estimate/Details/5
|
||||
public IActionResult Details(long? id)
|
||||
{
|
||||
if (id == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
Estimate estimate = _context.Estimates
|
||||
.Include(e => e.Command)
|
||||
.Include(e => e.Command.PerformerProfile)
|
||||
.Include(e => e.Command.PerformerProfile.Performer)
|
||||
.Single(m => m.Id == id);
|
||||
if (estimate == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
ViewBag.Files = estimate.GetFileContent(_site.UserFiles.DirName);
|
||||
return View(estimate);
|
||||
}
|
||||
|
||||
|
||||
// GET: Estimate/Create
|
||||
public IActionResult Create()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
|
||||
// POST: Estimate/Create
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken]
|
||||
public IActionResult Create(Estimate estimate,
|
||||
ICollection<IFormFile> newGraphics,
|
||||
ICollection<IFormFile> newFiles
|
||||
)
|
||||
{
|
||||
if (ModelState.IsValid)
|
||||
{
|
||||
_context.Estimates
|
||||
.Add(estimate);
|
||||
_context.SaveChanges();
|
||||
|
||||
var perfomerProfile = _context.Performers
|
||||
.Include(
|
||||
perpr => perpr.Performer).FirstOrDefault(
|
||||
x=>x.PerfomerId == estimate.Command.PerformerId
|
||||
);
|
||||
var command = _context.Commands.FirstOrDefault(
|
||||
cmd => cmd.Id == estimate.CommandId
|
||||
);
|
||||
|
||||
var userdir = Path.Combine(
|
||||
_site.UserFiles.DirName,
|
||||
perfomerProfile.Performer.UserName
|
||||
);
|
||||
|
||||
var fsp = new PhysicalFileProvider(userdir);
|
||||
var billsdir = Path.Combine(userdir,
|
||||
Constants.UserBillsFilesDir);
|
||||
|
||||
foreach (var gr in newGraphics)
|
||||
{
|
||||
gr.SaveAs(
|
||||
Path.Combine(
|
||||
Path.Combine(billsdir, estimate.Id.ToString()),
|
||||
gr.ContentDisposition));
|
||||
}
|
||||
return RedirectToAction("Index");
|
||||
}
|
||||
return View(estimate);
|
||||
}
|
||||
|
||||
|
||||
private void Save( ICollection<IFormFile> newGraphics,
|
||||
ICollection<IFormFile> newFiles) {
|
||||
|
||||
}
|
||||
// GET: Estimate/Edit/5
|
||||
public IActionResult Edit(long? id)
|
||||
{
|
||||
if (id == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
Estimate estimate = _context.Estimates.Single(m => m.Id == id);
|
||||
if (estimate == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
ViewBag.Files = estimate.GetFileContent(_site.UserFiles.DirName);
|
||||
return View(estimate);
|
||||
}
|
||||
|
||||
// POST: Estimate/Edit/5
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken]
|
||||
public IActionResult Edit(Estimate estimate)
|
||||
{
|
||||
if (ModelState.IsValid)
|
||||
{
|
||||
_context.Update(estimate);
|
||||
_context.SaveChanges();
|
||||
return RedirectToAction("Index");
|
||||
}
|
||||
return View(estimate);
|
||||
}
|
||||
|
||||
// GET: Estimate/Delete/5
|
||||
[ActionName("Delete")]
|
||||
public IActionResult Delete(long? id)
|
||||
{
|
||||
if (id == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
Estimate estimate = _context.Estimates.Single(m => m.Id == id);
|
||||
if (estimate == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
return View(estimate);
|
||||
}
|
||||
|
||||
// POST: Estimate/Delete/5
|
||||
[HttpPost, ActionName("Delete")]
|
||||
[ValidateAntiForgeryToken]
|
||||
public IActionResult DeleteConfirmed(long id)
|
||||
{
|
||||
Estimate estimate = _context.Estimates.Single(m => m.Id == id);
|
||||
_context.Estimates.Remove(estimate);
|
||||
_context.SaveChanges();
|
||||
return RedirectToAction("Index");
|
||||
}
|
||||
}
|
||||
}
|
104
Yavsc/Controllers/FrontOfficeController.cs
Normal file
104
Yavsc/Controllers/FrontOfficeController.cs
Normal file
@ -0,0 +1,104 @@
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.AspNet.Authorization;
|
||||
using Yavsc.Models;
|
||||
using System.Linq;
|
||||
using Microsoft.AspNet.Identity;
|
||||
using Microsoft.Data.Entity;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Yavsc.Models.Booking;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[ServiceFilter(typeof(LanguageActionFilter)),
|
||||
Route("do")]
|
||||
public class FrontOfficeController : Controller
|
||||
{
|
||||
ApplicationDbContext _context;
|
||||
UserManager<ApplicationUser> _userManager;
|
||||
|
||||
ILogger _logger;
|
||||
public FrontOfficeController(ApplicationDbContext context,
|
||||
UserManager<ApplicationUser> userManager,
|
||||
ILoggerFactory loggerFactory)
|
||||
{
|
||||
_context = context;
|
||||
_userManager = userManager;
|
||||
_logger = loggerFactory.CreateLogger<FrontOfficeController>();
|
||||
}
|
||||
public ActionResult Index()
|
||||
{
|
||||
var latestPosts = _context.Blogspot.Where(
|
||||
x => x.visible == true
|
||||
).OrderBy(x => x.modified).Take(25).ToArray();
|
||||
return View(latestPosts);
|
||||
}
|
||||
|
||||
[Route("Book/{id?}"),HttpGet]
|
||||
|
||||
public ActionResult Book(string id)
|
||||
{
|
||||
if (id != null) {
|
||||
ViewBag.Activities = _context.ActivityItems(id);
|
||||
ViewBag.Activity = _context.Activities.FirstOrDefault(
|
||||
a => a.Code == id
|
||||
);
|
||||
|
||||
return View(
|
||||
_context.Performers.Include(p=>p.Performer).Where
|
||||
(p => p.ActivityCode == id && p.Active).OrderBy(
|
||||
x=>x.MinDailyCost
|
||||
)
|
||||
);
|
||||
}
|
||||
ViewBag.Activities = _context.ActivityItems(null);
|
||||
|
||||
return View (
|
||||
_context.Performers.Include(p=>p.Performer).Where
|
||||
(p => p.Active).OrderBy(
|
||||
x=>x.MinDailyCost
|
||||
));
|
||||
}
|
||||
|
||||
[Route("Book/{id}"),HttpPost]
|
||||
|
||||
public ActionResult Book(BookQuery bookQuery)
|
||||
{
|
||||
if (ModelState.IsValid) {
|
||||
var pro = _context.Performers.Include(
|
||||
pr => pr.Performer
|
||||
).FirstOrDefault(
|
||||
x=>x.PerfomerId == bookQuery.PerformerId
|
||||
);
|
||||
if (pro==null)
|
||||
return HttpNotFound();
|
||||
// Let's create a command
|
||||
if (bookQuery.Id==0)
|
||||
{
|
||||
_context.BookQueries.Add(bookQuery);
|
||||
}
|
||||
else {
|
||||
_context.BookQueries.Update(bookQuery);
|
||||
}
|
||||
_context.SaveChanges();
|
||||
// TODO Send sys notifications &
|
||||
// notify the user (make him a basket badge)
|
||||
return View("Index");
|
||||
}
|
||||
ViewBag.Activities = _context.ActivityItems(null);
|
||||
return View( _context.Performers.Include(p=>p.Performer).Where
|
||||
(p => p.Active).OrderBy(
|
||||
x=>x.MinDailyCost
|
||||
));
|
||||
}
|
||||
|
||||
[Produces("text/x-tex"), Authorize,
|
||||
Route("Release/Estimate-{id}.tex")]
|
||||
public Estimate Estimate(long id)
|
||||
{
|
||||
var estimate = _context.Estimates.Include(x=>x.Command).
|
||||
Include(x=>x.Command.Client).FirstOrDefault(x=>x.Id==id);
|
||||
var adc = estimate.Command.Client.UserName;
|
||||
return estimate;
|
||||
}
|
||||
}
|
||||
}
|
61
Yavsc/Controllers/HomeController.cs
Normal file
61
Yavsc/Controllers/HomeController.cs
Normal file
@ -0,0 +1,61 @@
|
||||
using Microsoft.AspNet.Mvc.Localization;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.AspNet.Http.Features;
|
||||
using Microsoft.AspNet.Diagnostics;
|
||||
using Microsoft.AspNet.Authorization;
|
||||
using Microsoft.AspNet.Hosting;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[ServiceFilter(typeof(LanguageActionFilter)),AllowAnonymous]
|
||||
public class HomeController : Controller
|
||||
{
|
||||
public IHostingEnvironment Hosting { get; set; }
|
||||
|
||||
private readonly IHtmlLocalizer _localizer;
|
||||
|
||||
public HomeController(IHtmlLocalizer<Startup> localizer, IHostingEnvironment hosting)
|
||||
{
|
||||
_localizer = localizer;
|
||||
Hosting = hosting;
|
||||
}
|
||||
|
||||
public IActionResult Index()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
|
||||
public IActionResult About()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
|
||||
public IActionResult Contact()
|
||||
{
|
||||
|
||||
return View();
|
||||
}
|
||||
|
||||
public ActionResult Chat()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
|
||||
public IActionResult Error()
|
||||
{
|
||||
var feature = this.HttpContext.Features.Get<IExceptionHandlerFeature>();
|
||||
|
||||
return View("~/Views/Shared/Error.cshtml", feature?.Error);
|
||||
}
|
||||
public IActionResult Status(int id)
|
||||
{
|
||||
ViewBag.StatusCode = id;
|
||||
return View("~/Views/Shared/Status.cshtml");
|
||||
}
|
||||
public IActionResult Todo()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
588
Yavsc/Controllers/ManageController.cs
Normal file
588
Yavsc/Controllers/ManageController.cs
Normal file
@ -0,0 +1,588 @@
|
||||
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNet.Authorization;
|
||||
using Microsoft.AspNet.Identity;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Services;
|
||||
using Yavsc.ViewModels.Manage;
|
||||
using Microsoft.Extensions.OptionsModel;
|
||||
using Microsoft.Data.Entity;
|
||||
using System;
|
||||
using PayPal.PayPalAPIInterfaceService;
|
||||
using System.Collections.Generic;
|
||||
using Yavsc.Helpers;
|
||||
using Yavsc.ViewModels.Calendar;
|
||||
using System.Net;
|
||||
using Microsoft.Extensions.Localization;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[Authorize, ServiceFilter(typeof(LanguageActionFilter))]
|
||||
public class ManageController : Controller
|
||||
{
|
||||
private readonly UserManager<ApplicationUser> _userManager;
|
||||
private readonly SignInManager<ApplicationUser> _signInManager;
|
||||
private readonly IEmailSender _emailSender;
|
||||
private readonly ILogger _logger;
|
||||
private SiteSettings _siteSettings;
|
||||
|
||||
private ApplicationDbContext _dbContext;
|
||||
|
||||
private GoogleAuthSettings _googleSettings;
|
||||
|
||||
private PayPalSettings _payPalSettings;
|
||||
private IGoogleCloudMessageSender _GCMSender;
|
||||
private SIRENChecker _cchecker;
|
||||
private IStringLocalizer _SR;
|
||||
private CompanyInfoSettings _cinfoSettings;
|
||||
|
||||
public ManageController(
|
||||
ApplicationDbContext context,
|
||||
UserManager<ApplicationUser> userManager,
|
||||
SignInManager<ApplicationUser> signInManager,
|
||||
IEmailSender emailSender,
|
||||
IGoogleCloudMessageSender GCMSender,
|
||||
IOptions<SiteSettings> siteSettings,
|
||||
IOptions<GoogleAuthSettings> googleSettings,
|
||||
IOptions<PayPalSettings> paypalSettings,
|
||||
IOptions<CompanyInfoSettings> cinfoSettings,
|
||||
IStringLocalizer <Yavsc.Resources.YavscLocalisation>SR,
|
||||
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;
|
||||
_logger = loggerFactory.CreateLogger<ManageController>();
|
||||
}
|
||||
|
||||
//
|
||||
// GET: /Manage/Index
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> Index(ManageMessageId? message = null)
|
||||
{
|
||||
ViewData["StatusMessage"] =
|
||||
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
|
||||
: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
|
||||
: message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
|
||||
: message == ManageMessageId.Error ? "An error has occurred."
|
||||
: message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
|
||||
: message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
|
||||
: message == ManageMessageId.ChangeNameSuccess ? "Your name was updated."
|
||||
: message == ManageMessageId.SetActivitySuccess ? "Your activity was set."
|
||||
: "";
|
||||
|
||||
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.BookQueries.Count(x => (x.ClientId == user.Id) && (x.EventDate > DateTime.Now)),
|
||||
HasDedicatedCalendar = !string.IsNullOrEmpty(user.DedicatedGoogleCalendar)
|
||||
};
|
||||
if (_dbContext.Performers.Any(x => x.PerfomerId == user.Id))
|
||||
{
|
||||
var code = _dbContext.Performers.First(x => x.PerfomerId == user.Id).ActivityCode;
|
||||
model.Activity = _dbContext.Activities.First(x => x.Code == code);
|
||||
}
|
||||
return View(model);
|
||||
}
|
||||
|
||||
|
||||
//
|
||||
// POST: /Manage/RemoveLogin
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> RemoveLogin(RemoveLoginViewModel account)
|
||||
{
|
||||
ManageMessageId? message = ManageMessageId.Error;
|
||||
var user = await GetCurrentUserAsync();
|
||||
if (user != null)
|
||||
{
|
||||
var result = await _userManager.RemoveLoginAsync(user, account.LoginProvider, account.ProviderKey);
|
||||
if (result.Succeeded)
|
||||
{
|
||||
await _signInManager.SignInAsync(user, isPersistent: false);
|
||||
message = ManageMessageId.RemoveLoginSuccess;
|
||||
}
|
||||
}
|
||||
return RedirectToAction(nameof(ManageLogins), new { Message = message });
|
||||
}
|
||||
|
||||
//
|
||||
// GET: /Manage/AddPhoneNumber
|
||||
public IActionResult AddPhoneNumber()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
|
||||
//
|
||||
// POST: /Manage/AddPhoneNumber
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> AddPhoneNumber(AddPhoneNumberViewModel model)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return View(model);
|
||||
}
|
||||
// Generate the token and send it
|
||||
var user = await GetCurrentUserAsync();
|
||||
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber);
|
||||
// TODO await _smsSender.SendSmsAsync(_twilioSettings, model.PhoneNumber, "Your security code is: " + code);
|
||||
|
||||
return RedirectToAction(nameof(VerifyPhoneNumber), new { PhoneNumber = model.PhoneNumber });
|
||||
}
|
||||
|
||||
//
|
||||
// POST: /Manage/EnableTwoFactorAuthentication
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> EnableTwoFactorAuthentication()
|
||||
{
|
||||
var user = await GetCurrentUserAsync();
|
||||
if (user != null)
|
||||
{
|
||||
await _userManager.SetTwoFactorEnabledAsync(user, true);
|
||||
await _signInManager.SignInAsync(user, isPersistent: false);
|
||||
_logger.LogInformation(1, "User enabled two-factor authentication.");
|
||||
}
|
||||
return RedirectToAction(nameof(Index), "Manage");
|
||||
}
|
||||
|
||||
//
|
||||
// POST: /Manage/DisableTwoFactorAuthentication
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> DisableTwoFactorAuthentication()
|
||||
{
|
||||
var user = await GetCurrentUserAsync();
|
||||
if (user != null)
|
||||
{
|
||||
await _userManager.SetTwoFactorEnabledAsync(user, false);
|
||||
await _signInManager.SignInAsync(user, isPersistent: false);
|
||||
_logger.LogInformation(2, "User disabled two-factor authentication.");
|
||||
}
|
||||
return RedirectToAction(nameof(Index), "Manage");
|
||||
}
|
||||
|
||||
//
|
||||
// GET: /Manage/VerifyPhoneNumber
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> VerifyPhoneNumber(string phoneNumber)
|
||||
{
|
||||
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(await GetCurrentUserAsync(), phoneNumber);
|
||||
// Send an SMS to verify the phone number
|
||||
return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber });
|
||||
}
|
||||
|
||||
//
|
||||
// POST: /Manage/VerifyPhoneNumber
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return View(model);
|
||||
}
|
||||
var user = await GetCurrentUserAsync();
|
||||
if (user != null)
|
||||
{
|
||||
var result = await _userManager.ChangePhoneNumberAsync(user, model.PhoneNumber, model.Code);
|
||||
if (result.Succeeded)
|
||||
{
|
||||
await _signInManager.SignInAsync(user, isPersistent: false);
|
||||
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.AddPhoneSuccess });
|
||||
}
|
||||
}
|
||||
// If we got this far, something failed, redisplay the form
|
||||
ModelState.AddModelError(string.Empty, "Failed to verify phone number");
|
||||
return View(model);
|
||||
}
|
||||
|
||||
//
|
||||
// GET: /Manage/RemovePhoneNumber
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> RemovePhoneNumber()
|
||||
{
|
||||
var user = await GetCurrentUserAsync();
|
||||
if (user != null)
|
||||
{
|
||||
var result = await _userManager.SetPhoneNumberAsync(user, null);
|
||||
if (result.Succeeded)
|
||||
{
|
||||
await _signInManager.SignInAsync(user, isPersistent: false);
|
||||
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.RemovePhoneSuccess });
|
||||
}
|
||||
}
|
||||
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
|
||||
}
|
||||
|
||||
//
|
||||
// GET: /Manage/ChangePassword
|
||||
[HttpGet]
|
||||
public IActionResult ChangePassword()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
[HttpGet]
|
||||
public IActionResult AddMobileApp(GoogleCloudMobileDeclaration model)
|
||||
{
|
||||
return View();
|
||||
}
|
||||
|
||||
[HttpGet, Authorize]
|
||||
public async Task<IActionResult> SetGoogleCalendar(string returnUrl)
|
||||
{
|
||||
var credential = await _userManager.GetCredentialForGoogleApiAsync(
|
||||
_dbContext, User.GetUserId());
|
||||
if (credential==null)
|
||||
return RedirectToAction("LinkLogin",new { provider = "Google" });
|
||||
|
||||
try {
|
||||
ViewBag.Calendars = new GoogleApis.CalendarApi(_googleSettings.ApiKey)
|
||||
.GetCalendars(credential);
|
||||
}
|
||||
catch (WebException ex)
|
||||
{
|
||||
// a bug
|
||||
_logger.LogError("Google token, an Forbidden calendar");
|
||||
if (ex.HResult == (int) HttpStatusCode.Forbidden)
|
||||
{
|
||||
return RedirectToAction("LinkLogin",new { provider = "Google" });
|
||||
}
|
||||
}
|
||||
return View(new SetGoogleCalendarViewModel { ReturnUrl=returnUrl });
|
||||
}
|
||||
|
||||
[HttpPost,ValidateAntiForgeryToken,
|
||||
Authorize]
|
||||
public async Task<IActionResult> SetGoogleCalendar(SetGoogleCalendarViewModel model)
|
||||
{
|
||||
var user = _dbContext.Users.FirstOrDefault(u=>u.Id == User.GetUserId());
|
||||
user.DedicatedGoogleCalendar = model.GoogleCalendarId;
|
||||
await _dbContext.SaveChangesAsync();
|
||||
if (string.IsNullOrEmpty(model.ReturnUrl))
|
||||
return RedirectToAction("Index");
|
||||
else return Redirect(model.ReturnUrl);
|
||||
}
|
||||
|
||||
//
|
||||
// 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 });
|
||||
}
|
||||
|
||||
//
|
||||
// GET: /Manage/ChangeUserName
|
||||
public IActionResult ChangeUserName()
|
||||
{
|
||||
return View(new ChangeUserNameViewModel() { NewUserName = User.Identity.Name });
|
||||
}
|
||||
|
||||
public IActionResult CHUN()
|
||||
{
|
||||
return View(new ChangeUserNameViewModel() { NewUserName = User.Identity.Name });
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> CHUN(ChangeUserNameViewModel model)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return View(model);
|
||||
}
|
||||
var user = await GetCurrentUserAsync();
|
||||
if (user != null)
|
||||
{
|
||||
var oldUserName = user.UserName;
|
||||
|
||||
var result = await this._userManager.SetUserNameAsync(user, model.NewUserName);
|
||||
|
||||
if (result.Succeeded)
|
||||
{
|
||||
/* Obsolete : files are no more prefixed using the user name.
|
||||
|
||||
var userdirinfo = new DirectoryInfo(
|
||||
Path.Combine(_siteSettings.UserFiles.DirName,
|
||||
oldUserName));
|
||||
var newdir = Path.Combine(_siteSettings.UserFiles.DirName,
|
||||
model.NewUserName);
|
||||
if (userdirinfo.Exists)
|
||||
userdirinfo.MoveTo(newdir);
|
||||
*/
|
||||
|
||||
await _signInManager.SignInAsync(user, isPersistent: false);
|
||||
_logger.LogInformation(3, "User changed his user name successfully.");
|
||||
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.ChangeNameSuccess });
|
||||
}
|
||||
AddErrors(result);
|
||||
return View(model);
|
||||
}
|
||||
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
|
||||
}
|
||||
|
||||
//
|
||||
// GET: /Manage/SetPassword
|
||||
[HttpGet]
|
||||
public IActionResult SetPassword()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
|
||||
//
|
||||
// POST: /Manage/SetPassword
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> SetPassword(SetPasswordViewModel model)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return View(model);
|
||||
}
|
||||
|
||||
var user = await GetCurrentUserAsync();
|
||||
if (user != null)
|
||||
{
|
||||
var result = await _userManager.AddPasswordAsync(user, model.NewPassword);
|
||||
if (result.Succeeded)
|
||||
{
|
||||
await _signInManager.SignInAsync(user, isPersistent: false);
|
||||
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.SetPasswordSuccess });
|
||||
}
|
||||
AddErrors(result);
|
||||
return View(model);
|
||||
}
|
||||
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
|
||||
}
|
||||
|
||||
//GET: /Manage/ManageLogins
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> ManageLogins(ManageMessageId? message = null)
|
||||
{
|
||||
ViewData["StatusMessage"] =
|
||||
message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
|
||||
: message == ManageMessageId.AddLoginSuccess ? "The external login was added."
|
||||
: message == ManageMessageId.Error ? "An error has occurred."
|
||||
: "";
|
||||
var user = await GetCurrentUserAsync();
|
||||
if (user == null)
|
||||
{
|
||||
return View("Error");
|
||||
}
|
||||
var userLogins = await _userManager.GetLoginsAsync(user);
|
||||
var otherLogins = _signInManager.GetExternalAuthenticationSchemes().Where(auth => userLogins.All(ul => auth.AuthenticationScheme != ul.LoginProvider)).ToList();
|
||||
ViewData["ShowRemoveButton"] = user.PasswordHash != null || userLogins.Count > 1;
|
||||
|
||||
return View(new ManageLoginsViewModel
|
||||
{
|
||||
CurrentLogins = userLogins,
|
||||
OtherLogins = otherLogins
|
||||
});
|
||||
}
|
||||
|
||||
//
|
||||
// POST: /Manage/LinkLogin
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken]
|
||||
public IActionResult LinkLogin(string provider)
|
||||
{
|
||||
// Request a redirect to the external login provider to link a login for the current user
|
||||
var redirectUrl = Url.Action("LinkLoginCallback", "Manage");
|
||||
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, User.GetUserId());
|
||||
return new ChallengeResult(provider, properties);
|
||||
}
|
||||
|
||||
//
|
||||
// GET: /Manage/LinkLoginCallback
|
||||
[HttpGet]
|
||||
public async Task<ActionResult> LinkLoginCallback()
|
||||
{
|
||||
var user = await GetCurrentUserAsync();
|
||||
if (user == null)
|
||||
{
|
||||
return View("Error");
|
||||
}
|
||||
var info = await _signInManager.GetExternalLoginInfoAsync(User.GetUserId());
|
||||
if (info == null)
|
||||
{
|
||||
return RedirectToAction(nameof(ManageLogins), new { Message = ManageMessageId.Error });
|
||||
}
|
||||
var result = await _userManager.AddLoginAsync(user, info);
|
||||
var message = result.Succeeded ? ManageMessageId.AddLoginSuccess : ManageMessageId.Error;
|
||||
return RedirectToAction(nameof(ManageLogins), new { Message = message });
|
||||
}
|
||||
|
||||
[HttpGet, Authorize]
|
||||
public IActionResult SetActivity()
|
||||
{
|
||||
var user = GetCurrentUserAsync().Result;
|
||||
var uid = user.Id;
|
||||
bool existing = _dbContext.Performers.Any(x => x.PerfomerId == uid);
|
||||
ViewBag.Activities = _dbContext.ActivityItems(null);
|
||||
ViewBag.GoogleSettings = _googleSettings;
|
||||
if (existing)
|
||||
{
|
||||
var currentProfile = _dbContext.Performers.Include(x => x.OrganisationAddress)
|
||||
.First(x => x.PerfomerId == uid);
|
||||
string currentCode = currentProfile.ActivityCode;
|
||||
return View(currentProfile);
|
||||
}
|
||||
return View(new PerformerProfile
|
||||
{
|
||||
PerfomerId = user.Id,
|
||||
OrganisationAddress = new Location()
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken, Authorize]
|
||||
public async Task<IActionResult> SetActivity(PerformerProfile model)
|
||||
{
|
||||
var user = GetCurrentUserAsync().Result;
|
||||
var uid = user.Id;
|
||||
|
||||
if (ModelState.IsValid)
|
||||
{
|
||||
var taskCheck = await _cchecker.CheckAsync(model.SIREN);
|
||||
if (!taskCheck.success) {
|
||||
ModelState.AddModelError(
|
||||
"SIREN",
|
||||
_SR["Invalid company number"]+" ("+taskCheck.errorCode+")"
|
||||
);
|
||||
_logger.LogWarning("Invalid company number, using key:"+_cinfoSettings.ApiKey);
|
||||
}
|
||||
}
|
||||
if (ModelState.IsValid)
|
||||
{
|
||||
if (uid == model.PerfomerId)
|
||||
{
|
||||
bool addrexists = _dbContext.Map.Any(x => model.OrganisationAddress.Id == x.Id);
|
||||
if (!addrexists)
|
||||
{
|
||||
_dbContext.Map.Add(model.OrganisationAddress);
|
||||
}
|
||||
bool existing = _dbContext.Performers.Any(x => x.PerfomerId == uid);
|
||||
if (existing)
|
||||
{
|
||||
_dbContext.Update(model);
|
||||
}
|
||||
else _dbContext.Performers.Add(model);
|
||||
_dbContext.SaveChanges();
|
||||
var message = ManageMessageId.SetActivitySuccess;
|
||||
|
||||
return RedirectToAction(nameof(Index), new { Message = message });
|
||||
|
||||
}
|
||||
else ModelState.AddModelError(string.Empty, "Acces denied");
|
||||
}
|
||||
ViewBag.GoogleSettings = _googleSettings;
|
||||
ViewBag.Activities = _dbContext.ActivityItems(model.ActivityCode);
|
||||
return View(model);
|
||||
}
|
||||
|
||||
[HttpPost, Authorize]
|
||||
public IActionResult UnsetActivity()
|
||||
{
|
||||
var user = GetCurrentUserAsync().Result;
|
||||
var uid = user.Id;
|
||||
bool existing = _dbContext.Performers.Any(x => x.PerfomerId == uid);
|
||||
if (existing)
|
||||
{
|
||||
_dbContext.Performers.Remove(
|
||||
_dbContext.Performers.First(x => x.PerfomerId == uid)
|
||||
);
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
var message = ManageMessageId.UnsetActivitySuccess;
|
||||
return RedirectToAction(nameof(Index), new { Message = message });
|
||||
}
|
||||
|
||||
[HttpGet, Route("/Manage/Credits")]
|
||||
public IActionResult Credits()
|
||||
{
|
||||
Dictionary<string, string> config = new Dictionary<string, string>();
|
||||
config.Add("mode", "sandbox");
|
||||
config.Add("account1.apiUsername", _payPalSettings.UserId);
|
||||
config.Add("account1.apiPassword", _payPalSettings.Secret);
|
||||
config.Add("account1.apiSignature", _payPalSettings.Signature);
|
||||
PayPalAPIInterfaceServiceService s = new PayPalAPIInterfaceServiceService(config);
|
||||
|
||||
return View();
|
||||
}
|
||||
|
||||
#region Helpers
|
||||
|
||||
private void AddErrors(IdentityResult result)
|
||||
{
|
||||
foreach (var error in result.Errors)
|
||||
{
|
||||
ModelState.AddModelError(string.Empty, error.Description);
|
||||
}
|
||||
}
|
||||
|
||||
public enum ManageMessageId
|
||||
{
|
||||
AddPhoneSuccess,
|
||||
AddLoginSuccess,
|
||||
ChangePasswordSuccess,
|
||||
ChangeNameSuccess,
|
||||
SetTwoFactorSuccess,
|
||||
SetPasswordSuccess,
|
||||
RemoveLoginSuccess,
|
||||
RemovePhoneSuccess,
|
||||
SetActivitySuccess,
|
||||
UnsetActivitySuccess,
|
||||
Error
|
||||
}
|
||||
|
||||
|
||||
private async Task<ApplicationUser> GetCurrentUserAsync()
|
||||
{
|
||||
return await _userManager.FindByIdAsync(HttpContext.User.GetUserId());
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
158
Yavsc/Controllers/OAuthController.cs
Normal file
158
Yavsc/Controllers/OAuthController.cs
Normal file
@ -0,0 +1,158 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNet.Authentication;
|
||||
using Microsoft.AspNet.Authorization;
|
||||
using Microsoft.AspNet.Builder;
|
||||
using Microsoft.AspNet.DataProtection.KeyManagement;
|
||||
using Microsoft.AspNet.Http.Authentication;
|
||||
using Microsoft.AspNet.Identity;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Data.Entity;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.OptionsModel;
|
||||
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
|
||||
using Yavsc.Extensions;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.ViewModels.Account;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[AllowAnonymous]
|
||||
public class OAuthController : Controller
|
||||
{
|
||||
ApplicationDbContext _context;
|
||||
UserManager<ApplicationUser> _userManager;
|
||||
|
||||
SiteSettings _siteSettings;
|
||||
|
||||
ILogger _logger;
|
||||
private readonly SignInManager<ApplicationUser> _signInManager;
|
||||
private TokenAuthOptions _tokenOptions;
|
||||
|
||||
public OAuthController(ApplicationDbContext context, SignInManager<ApplicationUser> signInManager, IKeyManager keyManager,
|
||||
IOptions<TokenAuthOptions> tokenOptions,
|
||||
UserManager<ApplicationUser> userManager,
|
||||
IOptions<SiteSettings> siteSettings,
|
||||
ILoggerFactory loggerFactory
|
||||
)
|
||||
{
|
||||
_siteSettings = siteSettings.Value;
|
||||
_context = context;
|
||||
_signInManager = signInManager;
|
||||
_tokenOptions = tokenOptions.Value;
|
||||
_userManager = userManager;
|
||||
_logger = loggerFactory.CreateLogger<OAuthController>();
|
||||
}
|
||||
|
||||
|
||||
[HttpGet("~/signin")]
|
||||
public ActionResult SignIn(string returnUrl = null)
|
||||
{
|
||||
_logger.LogWarning($"Singin wanted: returnUrl: {returnUrl} ");
|
||||
// Note: the "returnUrl" parameter corresponds to the endpoint the user agent
|
||||
// will be redirected to after a successful authentication and not
|
||||
// the redirect_uri of the requesting client application.
|
||||
return View("SignIn", new LoginViewModel
|
||||
{
|
||||
ReturnUrl = returnUrl,
|
||||
ExternalProviders = HttpContext.GetExternalProviders()
|
||||
});
|
||||
/* Note: When using an external login provider, redirect the query :
|
||||
var properties = _signInManager.ConfigureExternalAuthenticationProperties(OpenIdConnectDefaults.AuthenticationScheme, returnUrl);
|
||||
return new ChallengeResult(OpenIdConnectDefaults.AuthenticationScheme, properties);
|
||||
*/
|
||||
}
|
||||
|
||||
[HttpGet("~/authenticate")]
|
||||
public ActionResult Authenticate(string returnUrl = null)
|
||||
{
|
||||
return SignIn(returnUrl);
|
||||
}
|
||||
|
||||
[HttpGet("~/forbidden")]
|
||||
public ActionResult Forbidden(string returnUrl = null)
|
||||
{
|
||||
return View("Forbidden",returnUrl);
|
||||
}
|
||||
|
||||
[HttpPost("~/signin")]
|
||||
public IActionResult SignIn(string Provider, string ReturnUrl)
|
||||
{
|
||||
// Note: the "provider" parameter corresponds to the external
|
||||
// authentication provider choosen by the user agent.
|
||||
if (string.IsNullOrEmpty(Provider))
|
||||
{
|
||||
_logger.LogWarning("Provider not specified");
|
||||
return HttpBadRequest();
|
||||
}
|
||||
|
||||
if (!_signInManager.GetExternalAuthenticationSchemes().Any(x => x.AuthenticationScheme == Provider))
|
||||
{
|
||||
_logger.LogWarning($"Provider not found : {Provider}");
|
||||
return HttpBadRequest();
|
||||
}
|
||||
|
||||
// Instruct the middleware corresponding to the requested external identity
|
||||
// provider to redirect the user agent to its own authorization endpoint.
|
||||
// Note: the authenticationScheme parameter must match the value configured in Startup.cs
|
||||
|
||||
// Note: the "returnUrl" parameter corresponds to the endpoint the user agent
|
||||
// will be redirected to after a successful authentication and not
|
||||
// the redirect_uri of the requesting client application.
|
||||
if (string.IsNullOrEmpty(ReturnUrl))
|
||||
{
|
||||
_logger.LogWarning("ReturnUrl not specified");
|
||||
return HttpBadRequest();
|
||||
}
|
||||
var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = ReturnUrl });
|
||||
var properties = _signInManager.ConfigureExternalAuthenticationProperties(Provider, redirectUrl);
|
||||
// var properties = new AuthenticationProperties{RedirectUri=ReturnUrl};
|
||||
return new ChallengeResult(Provider,properties);
|
||||
}
|
||||
|
||||
|
||||
|
||||
[HttpGet("~/signout"), HttpPost("~/signout")]
|
||||
public async Task SignOut()
|
||||
{
|
||||
// Instruct the cookies middleware to delete the local cookie created
|
||||
// when the user agent is redirected from the external identity provider
|
||||
// after a successful authentication flow (e.g Google or Facebook).
|
||||
|
||||
await HttpContext.Authentication.SignOutAsync("ServerCookie");
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
[HttpGet("~/api/getclaims"), Produces("application/json")]
|
||||
|
||||
public IActionResult GetClaims()
|
||||
{
|
||||
var identity = User.Identity as ClaimsIdentity;
|
||||
|
||||
var claims = from c in identity.Claims
|
||||
select new
|
||||
{
|
||||
subject = c.Subject.Name,
|
||||
type = c.Type,
|
||||
value = c.Value
|
||||
};
|
||||
|
||||
return Ok(claims);
|
||||
}
|
||||
|
||||
protected virtual Task<Application> GetApplicationAsync(string identifier, CancellationToken cancellationToken)
|
||||
{
|
||||
// Retrieve the application details corresponding to the requested client_id.
|
||||
return (from application in _context.Applications
|
||||
where application.ApplicationID == identifier
|
||||
select application).SingleOrDefaultAsync(cancellationToken);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
119
Yavsc/Controllers/TokenController.cs
Normal file
119
Yavsc/Controllers/TokenController.cs
Normal file
@ -0,0 +1,119 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using System.IdentityModel.Tokens;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNet.Authorization;
|
||||
using System.Security.Principal;
|
||||
using Microsoft.AspNet.Authentication.JwtBearer;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.OptionsModel;
|
||||
using Yavsc.Auth;
|
||||
using Microsoft.AspNet.Identity;
|
||||
using Yavsc.Models;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[Produces("application/json"),AllowAnonymous]
|
||||
public class TokenController : Controller
|
||||
{
|
||||
private readonly TokenAuthOptions tokenOptions;
|
||||
private ILogger logger;
|
||||
UserManager<ApplicationUser> manager;
|
||||
SignInManager<ApplicationUser> signInManager;
|
||||
public class TokenResponse {
|
||||
public string access_token { get; set; }
|
||||
public int expires_in { get; set; }
|
||||
public string grant_type { get; set; }
|
||||
|
||||
public int entity_id { get; set; }
|
||||
}
|
||||
UserTokenProvider tokenProvider;
|
||||
|
||||
public TokenController( UserManager<ApplicationUser> userManager,
|
||||
SignInManager<ApplicationUser> signInManager,
|
||||
IOptions<TokenAuthOptions> token_options, ILoggerFactory loggerFactory, UserTokenProvider tokenProvider)
|
||||
{
|
||||
this.manager = userManager;
|
||||
this.tokenOptions = token_options.Value;
|
||||
this.signInManager = signInManager;
|
||||
this.tokenProvider = tokenProvider;
|
||||
//this.bearerOptions = options.Value;
|
||||
//this.signingCredentials = signingCredentials;
|
||||
logger = loggerFactory.CreateLogger<TokenController>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Check if currently authenticated. Will throw an exception of some sort which shoudl be caught by a general
|
||||
/// exception handler and returned to the user as a 401, if not authenticated. Will return a fresh token if
|
||||
/// the user is authenticated, which will reset the expiry.
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpGet,HttpPost,Authorize]
|
||||
[Route("~/api/token/get")]
|
||||
public async Task<dynamic> Get()
|
||||
{
|
||||
bool authenticated = false;
|
||||
string user = null;
|
||||
int entityId = -1;
|
||||
string token = null;
|
||||
DateTime? tokenExpires = default(DateTime?);
|
||||
var currentUser = User;
|
||||
if (currentUser != null)
|
||||
{
|
||||
authenticated = currentUser.Identity.IsAuthenticated;
|
||||
if (authenticated)
|
||||
{
|
||||
user = User.GetUserId();
|
||||
logger.LogInformation($"authenticated user:{user}");
|
||||
|
||||
foreach (Claim c in currentUser.Claims) if (c.Type == "EntityID") entityId = Convert.ToInt32(c.Value);
|
||||
|
||||
tokenExpires = DateTime.UtcNow.AddMinutes(2);
|
||||
token = await GetToken("id_token", user, tokenExpires);
|
||||
return new TokenResponse { access_token = token, expires_in = 3400, entity_id = entityId };
|
||||
}
|
||||
}
|
||||
return new { authenticated = false };
|
||||
}
|
||||
|
||||
public class AuthRequest
|
||||
{
|
||||
public string username { get; set; }
|
||||
public string password { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Request a new token for a given username/password pair.
|
||||
/// </summary>
|
||||
/// <param name="req"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost,Route("~/api/token/post")]
|
||||
public async Task<IActionResult> Post(AuthRequest req)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
return new BadRequestObjectResult(ModelState);
|
||||
// Obviously, at this point you need to validate the username and password against whatever system you wish.
|
||||
var signResult = await signInManager.PasswordSignInAsync(req.username, req.password,false,true);
|
||||
|
||||
if (signResult.Succeeded)
|
||||
{
|
||||
DateTime? expires = DateTime.UtcNow.AddMinutes(tokenOptions.ExpiresIn);
|
||||
var token = await GetToken("id_token",User.GetUserId(), expires);
|
||||
return Ok(new TokenResponse {access_token = token, expires_in = 3400, grant_type="id_token" });
|
||||
}
|
||||
return new BadRequestObjectResult(new { authenticated = false } ) ;
|
||||
}
|
||||
|
||||
private async Task<string> GetToken(string purpose, string userid, DateTime? expires)
|
||||
{
|
||||
// Here, you should create or look up an identity for the user which is being authenticated.
|
||||
// For now, just creating a simple generic identity.
|
||||
var identuser = await manager.FindByIdAsync(userid);
|
||||
|
||||
return await tokenProvider.GenerateAsync(purpose,manager,identuser);
|
||||
}
|
||||
}
|
||||
}
|
71
Yavsc/Controllers/UserFilesController.cs
Normal file
71
Yavsc/Controllers/UserFilesController.cs
Normal file
@ -0,0 +1,71 @@
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNet.Authorization;
|
||||
using Microsoft.AspNet.Hosting;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.OptionsModel;
|
||||
using Microsoft.Net.Http.Headers;
|
||||
using Yavsc.Models;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[Authorize, ServiceFilter(typeof(LanguageActionFilter))]
|
||||
public class UserFilesController : Controller
|
||||
{
|
||||
private SiteSettings _siteSettings;
|
||||
IHostingEnvironment _environment;
|
||||
private IAuthorizationService _authorizationService;
|
||||
ApplicationDbContext _context;
|
||||
ILogger _logger;
|
||||
public UserFilesController(
|
||||
ApplicationDbContext context,
|
||||
IHostingEnvironment environment, IOptions<SiteSettings> siteSettings,
|
||||
IAuthorizationService authorizationService, ILoggerFactory loggerFactory)
|
||||
{
|
||||
_context = context;
|
||||
_siteSettings = siteSettings.Value;
|
||||
_environment = environment;
|
||||
_authorizationService = authorizationService;
|
||||
_logger = loggerFactory.CreateLogger<UserFilesController>();
|
||||
}
|
||||
|
||||
[HttpPost, Produces("application/json")]
|
||||
public async Task<IActionResult> Create(BlogFilesPost model)
|
||||
{
|
||||
var blogEntry = _context.Blogspot.FirstOrDefault(
|
||||
be => be.Id == model.PostId);
|
||||
if (blogEntry == null)
|
||||
return new HttpNotFoundResult();
|
||||
if (!ModelState.IsValid)
|
||||
return new BadRequestObjectResult(ModelState);
|
||||
var results = new List<string>();
|
||||
var uploads = Path.Combine(_environment.WebRootPath, _siteSettings.UserFiles.DirName);
|
||||
uploads = Path.Combine(uploads, model.PostId.ToString());
|
||||
var spot = new FileSpotInfo(uploads, blogEntry);
|
||||
if (!await _authorizationService.AuthorizeAsync(User, spot, new EditRequirement()))
|
||||
{
|
||||
return new HttpStatusCodeResult(403);
|
||||
}
|
||||
if (!spot.PathInfo.Exists) spot.PathInfo.Create();
|
||||
foreach (var file in model.File)
|
||||
{
|
||||
var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
|
||||
var permUrl = $"~/{_siteSettings.UserFiles.DirName}/{model.PostId}/{fileName}";
|
||||
results.Add(permUrl);
|
||||
_logger.LogWarning($"Create: {model.PostId} {file.ContentDisposition}");
|
||||
/* if (file.Length > 0)
|
||||
{
|
||||
var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
|
||||
var fullName = Path.Combine(spot.PathInfo.FullName, fileName);
|
||||
results.Add(permUrl);
|
||||
await file.SaveAsAsync(fullName);
|
||||
} */
|
||||
}
|
||||
return Ok(results);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
29
Yavsc/Controllers/ValuesController.cs
Normal file
29
Yavsc/Controllers/ValuesController.cs
Normal file
@ -0,0 +1,29 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.AspNet.Authorization;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[Route("api/[controller]")]
|
||||
public class ValuesController : Controller
|
||||
{
|
||||
// GET: api/values
|
||||
[HttpGet]
|
||||
public IEnumerable<string> Get()
|
||||
{
|
||||
//throw new Exception("Horsed");
|
||||
return new string[] { "value1", "value2" };
|
||||
}
|
||||
|
||||
// GET api/values/5
|
||||
[HttpGet("{id}")]
|
||||
[Authorize("Bearer")]
|
||||
public string Get(int id)
|
||||
{
|
||||
return "value";
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user