files tree made better.
207
src/Yavsc/ApiControllers/AccountController.cs
Normal file
|
|
@ -0,0 +1,207 @@
|
|||
using Microsoft.AspNet.Identity;
|
||||
using Microsoft.AspNet.Authorization;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yavsc.WebApi.Controllers
|
||||
{
|
||||
using Models;
|
||||
using Models.Account;
|
||||
using ViewModels.Account;
|
||||
using Yavsc.Helpers;
|
||||
using System.Linq;
|
||||
using Microsoft.Data.Entity;
|
||||
using Microsoft.AspNet.Identity.EntityFramework;
|
||||
using Yavsc.Abstract.Identity;
|
||||
|
||||
[Authorize(),Route("~/api/account")]
|
||||
public class ApiAccountController : Controller
|
||||
{
|
||||
|
||||
private UserManager<ApplicationUser> _userManager;
|
||||
private readonly SignInManager<ApplicationUser> _signInManager;
|
||||
|
||||
ApplicationDbContext _dbContext;
|
||||
private ILogger _logger;
|
||||
|
||||
public ApiAccountController(UserManager<ApplicationUser> userManager,
|
||||
SignInManager<ApplicationUser> signInManager, ILoggerFactory loggerFactory, ApplicationDbContext dbContext)
|
||||
{
|
||||
UserManager = userManager;
|
||||
_signInManager = signInManager;
|
||||
_logger = loggerFactory.CreateLogger("ApiAuth");
|
||||
_dbContext = dbContext;
|
||||
}
|
||||
|
||||
public UserManager<ApplicationUser> UserManager
|
||||
{
|
||||
get
|
||||
{
|
||||
return _userManager;
|
||||
}
|
||||
private set
|
||||
{
|
||||
_userManager = value;
|
||||
}
|
||||
}
|
||||
|
||||
// POST api/Account/ChangePassword
|
||||
[Authorize]
|
||||
public async Task<IActionResult> ChangePassword(ChangePasswordBindingModel model)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return new BadRequestObjectResult(ModelState);
|
||||
}
|
||||
var user = await _userManager.FindByIdAsync(User.GetUserId());
|
||||
if (user == null || !(await _userManager.IsEmailConfirmedAsync(user))) {
|
||||
IdentityResult result = await UserManager.ChangePasswordAsync(user, model.OldPassword,
|
||||
model.NewPassword);
|
||||
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
AddErrors("NewPassword",result);
|
||||
return new BadRequestObjectResult(ModelState);
|
||||
}
|
||||
}
|
||||
return Ok();
|
||||
}
|
||||
|
||||
// POST api/Account/SetPassword
|
||||
[Authorize]
|
||||
public async Task<IActionResult> SetPassword(SetPasswordBindingModel model)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return new BadRequestObjectResult(ModelState);
|
||||
}
|
||||
var user = await _userManager.FindByIdAsync(User.GetUserId());
|
||||
if (user == null || !(await _userManager.IsEmailConfirmedAsync(user))) {
|
||||
IdentityResult result = await UserManager.AddPasswordAsync(user, model.NewPassword);
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
AddErrors ("NewPassword",result);
|
||||
return new BadRequestObjectResult(ModelState);
|
||||
}
|
||||
}
|
||||
return Ok();
|
||||
}
|
||||
|
||||
// POST api/Account/Register
|
||||
[AllowAnonymous]
|
||||
public async Task<IActionResult> Register(RegisterViewModel model)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return new BadRequestObjectResult(ModelState);
|
||||
}
|
||||
|
||||
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
|
||||
|
||||
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
|
||||
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
AddErrors ("Register",result);
|
||||
return new BadRequestObjectResult(ModelState);
|
||||
}
|
||||
await _signInManager.SignInAsync(user, isPersistent: false);
|
||||
return Ok();
|
||||
}
|
||||
private void AddErrors(string key, IdentityResult result)
|
||||
{
|
||||
foreach (var error in result.Errors)
|
||||
{
|
||||
ModelState.AddModelError(key, error.Description);
|
||||
}
|
||||
}
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
UserManager.Dispose();
|
||||
}
|
||||
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
[HttpGet("~/api/me"),Authorize]
|
||||
public async Task<IActionResult> Me ()
|
||||
{
|
||||
if (User==null)
|
||||
return new BadRequestObjectResult(
|
||||
new { error = "user not found" });
|
||||
var uid = User.GetUserId();
|
||||
|
||||
var userData = await _dbContext.Users
|
||||
.Include(u=>u.PostalAddress)
|
||||
.Include(u=>u.AccountBalance)
|
||||
.Include(u=>u.Roles)
|
||||
.FirstAsync(u=>u.Id == uid);
|
||||
|
||||
var user = new Yavsc.Models.Auth.Me(userData.Id, userData.UserName, userData.Email,
|
||||
userData.Avatar ,
|
||||
userData.PostalAddress, userData.DedicatedGoogleCalendar );
|
||||
|
||||
var userRoles = _dbContext.UserRoles.Where(u=>u.UserId == uid).ToArray();
|
||||
|
||||
IdentityRole [] roles = _dbContext.Roles.Where(r=>userRoles.Any(ur=>ur.RoleId==r.Id)).ToArray();
|
||||
|
||||
user.Roles = roles.Select(r=>r.Name).ToArray();
|
||||
|
||||
return Ok(user);
|
||||
}
|
||||
|
||||
[HttpGet("~/api/myip"),Authorize]
|
||||
public IActionResult MyIp ()
|
||||
{
|
||||
string ip = null;
|
||||
|
||||
ip = Request.Headers["X-Forwarded-For"];
|
||||
|
||||
if (string.IsNullOrEmpty(ip)) {
|
||||
ip = Request.Host.Value;
|
||||
} else { // Using X-Forwarded-For last address
|
||||
ip = ip.Split(',')
|
||||
.Last()
|
||||
.Trim();
|
||||
}
|
||||
|
||||
return Ok(ip);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Actually only updates the user's name.
|
||||
/// </summary>
|
||||
/// <param name="me">MyUpdate containing the new user name </param>
|
||||
/// <returns>Ok when all is ok.</returns>
|
||||
[HttpPut("~/api/me"),Authorize]
|
||||
public async Task<IActionResult> UpdateMe(UserInfo me)
|
||||
{
|
||||
if (!ModelState.IsValid) return new BadRequestObjectResult(
|
||||
new { error = "Specify some valid user update request." });
|
||||
var user = await _userManager.FindByIdAsync(User.GetUserId());
|
||||
var result = await _userManager.SetUserNameAsync(user, me.UserName);
|
||||
if (result.Succeeded)
|
||||
return Ok();
|
||||
else return new BadRequestObjectResult(result);
|
||||
}
|
||||
/// <summary>
|
||||
/// Updates the avatar
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpPost("~/api/setavatar"),Authorize]
|
||||
public async Task<IActionResult> SetAvatar()
|
||||
{
|
||||
var root = User.InitPostToFileSystem(null);
|
||||
var user = await _userManager.FindByIdAsync(User.GetUserId());
|
||||
if (Request.Form.Files.Count!=1)
|
||||
return new BadRequestResult();
|
||||
var info = user.ReceiveAvatar(Request.Form.Files[0]);
|
||||
await _userManager.UpdateAsync(user);
|
||||
return Ok(info);
|
||||
}
|
||||
}
|
||||
}
|
||||
153
src/Yavsc/ApiControllers/ActivityApiController.cs
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNet.Authorization;
|
||||
using Microsoft.AspNet.Http;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Data.Entity;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Models.Workflow;
|
||||
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[Produces("application/json")]
|
||||
[Route("api/activity")]
|
||||
[AllowAnonymous]
|
||||
public class ActivityApiController : Controller
|
||||
{
|
||||
private ApplicationDbContext _context;
|
||||
|
||||
public ActivityApiController(ApplicationDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
// GET: api/ActivityApi
|
||||
[HttpGet]
|
||||
public IEnumerable<Activity> GetActivities()
|
||||
{
|
||||
return _context.Activities.Include(a=>a.Forms).Where( a => !a.Hidden );
|
||||
}
|
||||
|
||||
// GET: api/ActivityApi/5
|
||||
[HttpGet("{id}", Name = "GetActivity")]
|
||||
public async Task<IActionResult> GetActivity([FromRoute] string id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
Activity activity = await _context.Activities.SingleAsync(m => m.Code == id);
|
||||
|
||||
if (activity == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
// Also return hidden ones
|
||||
// hidden doesn't mean disabled
|
||||
return Ok(activity);
|
||||
}
|
||||
|
||||
// PUT: api/ActivityApi/5
|
||||
[HttpPut("{id}"),Authorize("AdministratorOnly")]
|
||||
public async Task<IActionResult> PutActivity([FromRoute] string id, [FromBody] Activity activity)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
if (id != activity.Code)
|
||||
{
|
||||
return HttpBadRequest();
|
||||
}
|
||||
|
||||
_context.Entry(activity).State = EntityState.Modified;
|
||||
|
||||
try
|
||||
{
|
||||
await _context.SaveChangesAsync(User.GetUserId());
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
if (!ActivityExists(id))
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return new HttpStatusCodeResult(StatusCodes.Status204NoContent);
|
||||
}
|
||||
|
||||
// POST: api/ActivityApi
|
||||
[HttpPost,Authorize("AdministratorOnly")]
|
||||
public async Task<IActionResult> PostActivity([FromBody] Activity activity)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
_context.Activities.Add(activity);
|
||||
try
|
||||
{
|
||||
await _context.SaveChangesAsync(User.GetUserId());
|
||||
}
|
||||
catch (DbUpdateException)
|
||||
{
|
||||
if (ActivityExists(activity.Code))
|
||||
{
|
||||
return new HttpStatusCodeResult(StatusCodes.Status409Conflict);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return CreatedAtRoute("GetActivity", new { id = activity.Code }, activity);
|
||||
}
|
||||
|
||||
// DELETE: api/ActivityApi/5
|
||||
[HttpDelete("{id}"),Authorize("AdministratorOnly")]
|
||||
public async Task<IActionResult> DeleteActivity([FromRoute] string id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
Activity activity = await _context.Activities.SingleAsync(m => m.Code == id);
|
||||
if (activity == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
_context.Activities.Remove(activity);
|
||||
await _context.SaveChangesAsync(User.GetUserId());
|
||||
|
||||
return Ok(activity);
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_context.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
private bool ActivityExists(string id)
|
||||
{
|
||||
return _context.Activities.Count(e => e.Code == id) > 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
148
src/Yavsc/ApiControllers/ApplicationUserApiController.cs
Normal file
|
|
@ -0,0 +1,148 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNet.Authorization;
|
||||
using Microsoft.AspNet.Http;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Data.Entity;
|
||||
using Yavsc.Models;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[Produces("application/json"),Authorize(Roles="Administrator")]
|
||||
[Route("api/users")]
|
||||
public class ApplicationUserApiController : Controller
|
||||
{
|
||||
private ApplicationDbContext _context;
|
||||
|
||||
public ApplicationUserApiController(ApplicationDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
// GET: api/ApplicationUserApi
|
||||
[HttpGet]
|
||||
public IEnumerable<ApplicationUser> GetApplicationUser()
|
||||
{
|
||||
return _context.Users.Include(u=>u.Roles).Include(u=>u.Logins).Include(u=>u.Claims);
|
||||
}
|
||||
|
||||
// GET: api/ApplicationUserApi/5
|
||||
[HttpGet("{id}", Name = "GetApplicationUser")]
|
||||
public IActionResult GetApplicationUser([FromRoute] string id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
ApplicationUser applicationUser = _context.Users.Single(m => m.Id == id);
|
||||
|
||||
if (applicationUser == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
return Ok(applicationUser);
|
||||
}
|
||||
|
||||
// PUT: api/ApplicationUserApi/5
|
||||
[HttpPut("{id}")]
|
||||
public IActionResult PutApplicationUser(string id, [FromBody] ApplicationUser applicationUser)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
if (id != applicationUser.Id)
|
||||
{
|
||||
return HttpBadRequest();
|
||||
}
|
||||
|
||||
_context.Entry(applicationUser).State = EntityState.Modified;
|
||||
|
||||
try
|
||||
{
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
if (!ApplicationUserExists(id))
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return new HttpStatusCodeResult(StatusCodes.Status204NoContent);
|
||||
}
|
||||
|
||||
// POST: api/ApplicationUserApi
|
||||
[HttpPost]
|
||||
public IActionResult PostApplicationUser([FromBody] ApplicationUser applicationUser)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
_context.Users.Add(applicationUser);
|
||||
try
|
||||
{
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
}
|
||||
catch (DbUpdateException)
|
||||
{
|
||||
if (ApplicationUserExists(applicationUser.Id))
|
||||
{
|
||||
return new HttpStatusCodeResult(StatusCodes.Status409Conflict);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return CreatedAtRoute("GetApplicationUser", new { id = applicationUser.Id }, applicationUser);
|
||||
}
|
||||
|
||||
// DELETE: api/ApplicationUserApi/5
|
||||
[HttpDelete("{id}")]
|
||||
public IActionResult DeleteApplicationUser(string id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
ApplicationUser applicationUser = _context.Users.Single(m => m.Id == id);
|
||||
if (applicationUser == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
_context.Users.Remove(applicationUser);
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
|
||||
return Ok(applicationUser);
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_context.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
private bool ApplicationUserExists(string id)
|
||||
{
|
||||
return _context.Users.Count(e => e.Id == id) > 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
190
src/Yavsc/ApiControllers/BillingController.cs
Normal file
|
|
@ -0,0 +1,190 @@
|
|||
using System.IO;
|
||||
using Microsoft.AspNet.Authorization;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using System.Web.Routing;
|
||||
using System.Linq;
|
||||
using Microsoft.Data.Entity;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using Microsoft.Extensions.OptionsModel;
|
||||
using System;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace Yavsc.ApiControllers
|
||||
{
|
||||
using Models;
|
||||
using Helpers;
|
||||
using Services;
|
||||
|
||||
using Models.Messaging;
|
||||
using ViewModels.Auth;
|
||||
using Newtonsoft.Json;
|
||||
using Yavsc.ViewModels;
|
||||
using Yavsc.Abstract.FileSystem;
|
||||
|
||||
[Route("api/bill"), Authorize]
|
||||
public class BillingController : Controller
|
||||
{
|
||||
ApplicationDbContext dbContext;
|
||||
private IStringLocalizer _localizer;
|
||||
private GoogleAuthSettings _googleSettings;
|
||||
private IGoogleCloudMessageSender _GCMSender;
|
||||
private IAuthorizationService authorizationService;
|
||||
|
||||
|
||||
private ILogger logger;
|
||||
private IBillingService billingService;
|
||||
|
||||
public BillingController(
|
||||
IAuthorizationService authorizationService,
|
||||
ILoggerFactory loggerFactory,
|
||||
IStringLocalizer<Yavsc.Resources.YavscLocalisation> SR,
|
||||
ApplicationDbContext context,
|
||||
IOptions<GoogleAuthSettings> googleSettings,
|
||||
IGoogleCloudMessageSender GCMSender,
|
||||
IBillingService billingService
|
||||
)
|
||||
{
|
||||
_googleSettings=googleSettings.Value;
|
||||
this.authorizationService = authorizationService;
|
||||
dbContext = context;
|
||||
logger = loggerFactory.CreateLogger<BillingController>();
|
||||
this._localizer = SR;
|
||||
_GCMSender=GCMSender;
|
||||
this.billingService=billingService;
|
||||
}
|
||||
|
||||
[HttpGet("facture-{billingCode}-{id}.pdf"), Authorize]
|
||||
public async Task<IActionResult> GetPdf(string billingCode, long id)
|
||||
{
|
||||
var bill = await billingService.GetBillAsync(billingCode, id);
|
||||
|
||||
if (!await authorizationService.AuthorizeAsync(User, bill, new ViewRequirement()))
|
||||
{
|
||||
return new ChallengeResult();
|
||||
}
|
||||
|
||||
var fi = bill.GetBillInfo(billingService);
|
||||
|
||||
if (!fi.Exists) return Ok(new { Error = "Not generated" });
|
||||
return File(fi.OpenRead(), "application/x-pdf", fi.Name);
|
||||
}
|
||||
|
||||
[HttpGet("facture-{billingCode}-{id}.tex"), Authorize]
|
||||
public async Task<IActionResult> GetTex(string billingCode, long id)
|
||||
{
|
||||
var bill = await billingService.GetBillAsync(billingCode, id);
|
||||
|
||||
if (bill==null) {
|
||||
logger.LogCritical ( $"# not found !! {id} in {billingCode}");
|
||||
return this.HttpNotFound();
|
||||
}
|
||||
logger.LogVerbose(JsonConvert.SerializeObject(bill));
|
||||
|
||||
if (!await authorizationService.AuthorizeAsync(User, bill, new ViewRequirement()))
|
||||
{
|
||||
return new ChallengeResult();
|
||||
}
|
||||
Response.ContentType = "text/x-tex";
|
||||
return ViewComponent("Bill",new object[] { billingCode, bill , OutputFormat.LaTeX, true });
|
||||
}
|
||||
|
||||
[HttpPost("genpdf/{billingCode}/{id}")]
|
||||
public async Task<IActionResult> GeneratePdf(string billingCode, long id)
|
||||
{
|
||||
var bill = await billingService.GetBillAsync(billingCode, id);
|
||||
|
||||
if (bill==null) {
|
||||
logger.LogCritical ( $"# not found !! {id} in {billingCode}");
|
||||
return this.HttpNotFound();
|
||||
}
|
||||
logger.LogWarning("Got bill ack:"+bill.GetIsAcquitted().ToString());
|
||||
return ViewComponent("Bill",new object[] { billingCode, bill, OutputFormat.Pdf, true } );
|
||||
}
|
||||
|
||||
|
||||
[HttpPost("prosign/{billingCode}/{id}")]
|
||||
public async Task<IActionResult> ProSign(string billingCode, long id)
|
||||
{
|
||||
var estimate = dbContext.Estimates.
|
||||
Include(e=>e.Client).Include(e=>e.Client.Devices)
|
||||
.Include(e=>e.Bill).Include(e=>e.Owner).Include(e=>e.Owner.Performer)
|
||||
.FirstOrDefault(e=>e.Id == id);
|
||||
if (estimate == null)
|
||||
return new BadRequestResult();
|
||||
if (!await authorizationService.AuthorizeAsync(User, estimate, new ViewRequirement()))
|
||||
{
|
||||
return new ChallengeResult();
|
||||
}
|
||||
if (Request.Form.Files.Count!=1)
|
||||
return new BadRequestResult();
|
||||
User.ReceiveProSignature(billingCode,id,Request.Form.Files[0],"pro");
|
||||
estimate.ProviderValidationDate = DateTime.Now;
|
||||
dbContext.SaveChanges(User.GetUserId());
|
||||
// Notify the client
|
||||
var locstr = _localizer["EstimationMessageToClient"];
|
||||
|
||||
var yaev = new EstimationEvent(estimate,_localizer);
|
||||
|
||||
var regids = estimate.Client.Devices.Select(d => d.GCMRegistrationId).ToArray();
|
||||
bool gcmSent = false;
|
||||
if (regids.Length>0) {
|
||||
var grep = await _GCMSender.NotifyEstimateAsync(regids,yaev);
|
||||
gcmSent = grep.success>0;
|
||||
}
|
||||
return Ok (new { ProviderValidationDate = estimate.ProviderValidationDate, GCMSent = gcmSent });
|
||||
}
|
||||
|
||||
[HttpGet("prosign/{billingCode}/{id}")]
|
||||
public async Task<IActionResult> GetProSign(string billingCode, long id)
|
||||
{
|
||||
// For authorization purpose
|
||||
var estimate = dbContext.Estimates.FirstOrDefault(e=>e.Id == id);
|
||||
if (!await authorizationService.AuthorizeAsync(User, estimate, new ViewRequirement()))
|
||||
{
|
||||
return new ChallengeResult();
|
||||
}
|
||||
|
||||
var filename = FileSystemHelpers.SignFileNameFormat("pro",billingCode,id);
|
||||
FileInfo fi = new FileInfo(Path.Combine(AbstractFileSystemHelpers.UserBillsDirName, filename));
|
||||
if (!fi.Exists) return HttpNotFound(new { Error = "Professional signature not found" });
|
||||
return File(fi.OpenRead(), "application/x-pdf", filename); ;
|
||||
}
|
||||
|
||||
[HttpPost("clisign/{billingCode}/{id}")]
|
||||
public async Task<IActionResult> CliSign(string billingCode, long id)
|
||||
{
|
||||
var uid = User.GetUserId();
|
||||
var estimate = dbContext.Estimates.Include( e=>e.Query
|
||||
).Include(e=>e.Owner).Include(e=>e.Owner.Performer).Include(e=>e.Client)
|
||||
.FirstOrDefault( e=> e.Id == id && e.Query.ClientId == uid );
|
||||
if (!await authorizationService.AuthorizeAsync(User, estimate, new ViewRequirement()))
|
||||
{
|
||||
return new ChallengeResult();
|
||||
}
|
||||
if (Request.Form.Files.Count!=1)
|
||||
return new BadRequestResult();
|
||||
User.ReceiveProSignature(billingCode,id,Request.Form.Files[0],"cli");
|
||||
estimate.ClientValidationDate = DateTime.Now;
|
||||
dbContext.SaveChanges(User.GetUserId());
|
||||
return Ok (new { ClientValidationDate = estimate.ClientValidationDate });
|
||||
}
|
||||
|
||||
[HttpGet("clisign/{billingCode}/{id}")]
|
||||
public async Task<IActionResult> GetCliSign(string billingCode, long id)
|
||||
{
|
||||
// For authorization purpose
|
||||
var estimate = dbContext.Estimates.FirstOrDefault(e=>e.Id == id);
|
||||
if (!await authorizationService.AuthorizeAsync(User, estimate, new ViewRequirement()))
|
||||
{
|
||||
return new ChallengeResult();
|
||||
}
|
||||
|
||||
var filename = FileSystemHelpers.SignFileNameFormat("pro",billingCode,id);
|
||||
FileInfo fi = new FileInfo(Path.Combine(AbstractFileSystemHelpers.UserBillsDirName, filename));
|
||||
if (!fi.Exists) return HttpNotFound(new { Error = "Professional signature not found" });
|
||||
return File(fi.OpenRead(), "application/x-pdf", filename); ;
|
||||
}
|
||||
}
|
||||
}
|
||||
165
src/Yavsc/ApiControllers/BlackListApiController.cs
Normal file
|
|
@ -0,0 +1,165 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNet.Authorization;
|
||||
using Microsoft.AspNet.Http;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Data.Entity;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Models.Access;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[Produces("application/json")]
|
||||
[Route("api/blacklist"), Authorize]
|
||||
public class BlackListApiController : Controller
|
||||
{
|
||||
private ApplicationDbContext _context;
|
||||
|
||||
public BlackListApiController(ApplicationDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
// GET: api/BlackListApi
|
||||
[HttpGet]
|
||||
public IEnumerable<BlackListed> GetBlackListed()
|
||||
{
|
||||
return _context.BlackListed;
|
||||
}
|
||||
|
||||
// GET: api/BlackListApi/5
|
||||
[HttpGet("{id}", Name = "GetBlackListed")]
|
||||
public IActionResult GetBlackListed([FromRoute] long id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
BlackListed blackListed = _context.BlackListed.Single(m => m.Id == id);
|
||||
if (blackListed == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
if (!CheckPermission(blackListed))
|
||||
return HttpBadRequest();
|
||||
|
||||
return Ok(blackListed);
|
||||
}
|
||||
|
||||
private bool CheckPermission(BlackListed blackListed)
|
||||
{
|
||||
var uid = User.GetUserId();
|
||||
if (uid != blackListed.OwnerId)
|
||||
if (!User.IsInRole(Constants.AdminGroupName))
|
||||
if (!User.IsInRole(Constants.FrontOfficeGroupName))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
// PUT: api/BlackListApi/5
|
||||
[HttpPut("{id}")]
|
||||
public IActionResult PutBlackListed(long id, [FromBody] BlackListed blackListed)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
if (id != blackListed.Id)
|
||||
{
|
||||
return HttpBadRequest();
|
||||
}
|
||||
if (!CheckPermission(blackListed))
|
||||
return HttpBadRequest();
|
||||
_context.Entry(blackListed).State = EntityState.Modified;
|
||||
|
||||
try
|
||||
{
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
if (!BlackListedExists(id))
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return new HttpStatusCodeResult(StatusCodes.Status204NoContent);
|
||||
}
|
||||
|
||||
// POST: api/BlackListApi
|
||||
[HttpPost]
|
||||
public IActionResult PostBlackListed([FromBody] BlackListed blackListed)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
if (!CheckPermission(blackListed))
|
||||
return HttpBadRequest();
|
||||
|
||||
_context.BlackListed.Add(blackListed);
|
||||
try
|
||||
{
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
}
|
||||
catch (DbUpdateException)
|
||||
{
|
||||
if (BlackListedExists(blackListed.Id))
|
||||
{
|
||||
return new HttpStatusCodeResult(StatusCodes.Status409Conflict);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return CreatedAtRoute("GetBlackListed", new { id = blackListed.Id }, blackListed);
|
||||
}
|
||||
|
||||
// DELETE: api/BlackListApi/5
|
||||
[HttpDelete("{id}")]
|
||||
public IActionResult DeleteBlackListed(long id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
BlackListed blackListed = _context.BlackListed.Single(m => m.Id == id);
|
||||
if (blackListed == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
if (!CheckPermission(blackListed))
|
||||
return HttpBadRequest();
|
||||
|
||||
_context.BlackListed.Remove(blackListed);
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
|
||||
return Ok(blackListed);
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_context.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
private bool BlackListedExists(long id)
|
||||
{
|
||||
return _context.BlackListed.Count(e => e.Id == id) > 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
167
src/Yavsc/ApiControllers/BlogAclApiController.cs
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNet.Http;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Data.Entity;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Models.Access;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[Produces("application/json")]
|
||||
[Route("api/blogacl")]
|
||||
public class BlogAclApiController : Controller
|
||||
{
|
||||
private ApplicationDbContext _context;
|
||||
|
||||
public BlogAclApiController(ApplicationDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
// GET: api/BlogAclApi
|
||||
[HttpGet]
|
||||
public IEnumerable<CircleAuthorizationToBlogPost> GetBlogACL()
|
||||
{
|
||||
return _context.BlogACL;
|
||||
}
|
||||
|
||||
// GET: api/BlogAclApi/5
|
||||
[HttpGet("{id}", Name = "GetCircleAuthorizationToBlogPost")]
|
||||
public async Task<IActionResult> GetCircleAuthorizationToBlogPost([FromRoute] long id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
var uid = User.GetUserId();
|
||||
CircleAuthorizationToBlogPost circleAuthorizationToBlogPost = await _context.BlogACL.SingleAsync(
|
||||
m => m.CircleId == id && m.Allowed.OwnerId == uid );
|
||||
|
||||
if (circleAuthorizationToBlogPost == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
return Ok(circleAuthorizationToBlogPost);
|
||||
}
|
||||
|
||||
// PUT: api/BlogAclApi/5
|
||||
[HttpPut("{id}")]
|
||||
public async Task<IActionResult> PutCircleAuthorizationToBlogPost([FromRoute] long id, [FromBody] CircleAuthorizationToBlogPost circleAuthorizationToBlogPost)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
if (id != circleAuthorizationToBlogPost.CircleId)
|
||||
{
|
||||
return HttpBadRequest();
|
||||
}
|
||||
|
||||
if (!CheckOwner(circleAuthorizationToBlogPost.CircleId))
|
||||
{
|
||||
return new ChallengeResult();
|
||||
}
|
||||
_context.Entry(circleAuthorizationToBlogPost).State = EntityState.Modified;
|
||||
|
||||
try
|
||||
{
|
||||
await _context.SaveChangesAsync(User.GetUserId());
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
if (!CircleAuthorizationToBlogPostExists(id))
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return new HttpStatusCodeResult(StatusCodes.Status204NoContent);
|
||||
}
|
||||
private bool CheckOwner (long circleId)
|
||||
{
|
||||
|
||||
var uid = User.GetUserId();
|
||||
var circle = _context.Circle.First(c=>c.Id==circleId);
|
||||
_context.Entry(circle).State = EntityState.Detached;
|
||||
return (circle.OwnerId == uid);
|
||||
}
|
||||
// POST: api/BlogAclApi
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> PostCircleAuthorizationToBlogPost([FromBody] CircleAuthorizationToBlogPost circleAuthorizationToBlogPost)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
if (!CheckOwner(circleAuthorizationToBlogPost.CircleId))
|
||||
{
|
||||
return new ChallengeResult();
|
||||
}
|
||||
_context.BlogACL.Add(circleAuthorizationToBlogPost);
|
||||
try
|
||||
{
|
||||
await _context.SaveChangesAsync(User.GetUserId());
|
||||
}
|
||||
catch (DbUpdateException)
|
||||
{
|
||||
if (CircleAuthorizationToBlogPostExists(circleAuthorizationToBlogPost.CircleId))
|
||||
{
|
||||
return new HttpStatusCodeResult(StatusCodes.Status409Conflict);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return CreatedAtRoute("GetCircleAuthorizationToBlogPost", new { id = circleAuthorizationToBlogPost.CircleId }, circleAuthorizationToBlogPost);
|
||||
}
|
||||
|
||||
// DELETE: api/BlogAclApi/5
|
||||
[HttpDelete("{id}")]
|
||||
public async Task<IActionResult> DeleteCircleAuthorizationToBlogPost([FromRoute] long id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
var uid = User.GetUserId();
|
||||
|
||||
CircleAuthorizationToBlogPost circleAuthorizationToBlogPost = await _context.BlogACL.Include(
|
||||
a=>a.Allowed
|
||||
).SingleAsync(m => m.CircleId == id
|
||||
&& m.Allowed.OwnerId == uid);
|
||||
if (circleAuthorizationToBlogPost == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
_context.BlogACL.Remove(circleAuthorizationToBlogPost);
|
||||
await _context.SaveChangesAsync(User.GetUserId());
|
||||
|
||||
return Ok(circleAuthorizationToBlogPost);
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_context.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
private bool CircleAuthorizationToBlogPostExists(long id)
|
||||
{
|
||||
return _context.BlogACL.Count(e => e.CircleId == id) > 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
148
src/Yavsc/ApiControllers/BlogApiController.cs
Normal file
|
|
@ -0,0 +1,148 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNet.Http;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Data.Entity;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Models.Blog;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[Produces("application/json")]
|
||||
[Route("api/blog")]
|
||||
public class BlogApiController : Controller
|
||||
{
|
||||
private ApplicationDbContext _context;
|
||||
|
||||
public BlogApiController(ApplicationDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
// GET: api/BlogApi
|
||||
[HttpGet]
|
||||
public IEnumerable<BlogPost> GetBlogspot()
|
||||
{
|
||||
return _context.Blogspot.Where(b=>b.Visible).OrderByDescending(b=>b.UserModified);
|
||||
}
|
||||
|
||||
// GET: api/BlogApi/5
|
||||
[HttpGet("{id}", Name = "GetBlog")]
|
||||
public IActionResult GetBlog([FromRoute] long id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
BlogPost blog = _context.Blogspot.Single(m => m.Id == id);
|
||||
|
||||
if (blog == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
return Ok(blog);
|
||||
}
|
||||
|
||||
// PUT: api/BlogApi/5
|
||||
[HttpPut("{id}")]
|
||||
public IActionResult PutBlog(long id, [FromBody] BlogPost blog)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
if (id != blog.Id)
|
||||
{
|
||||
return HttpBadRequest();
|
||||
}
|
||||
|
||||
_context.Entry(blog).State = EntityState.Modified;
|
||||
|
||||
try
|
||||
{
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
if (!BlogExists(id))
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return new HttpStatusCodeResult(StatusCodes.Status204NoContent);
|
||||
}
|
||||
|
||||
// POST: api/BlogApi
|
||||
[HttpPost]
|
||||
public IActionResult PostBlog([FromBody] Models.Blog.BlogPost blog)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
_context.Blogspot.Add(blog);
|
||||
try
|
||||
{
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
}
|
||||
catch (DbUpdateException)
|
||||
{
|
||||
if (BlogExists(blog.Id))
|
||||
{
|
||||
return new HttpStatusCodeResult(StatusCodes.Status409Conflict);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return CreatedAtRoute("GetBlog", new { id = blog.Id }, blog);
|
||||
}
|
||||
|
||||
// DELETE: api/BlogApi/5
|
||||
[HttpDelete("{id}")]
|
||||
public IActionResult DeleteBlog(long id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
BlogPost blog = _context.Blogspot.Single(m => m.Id == id);
|
||||
if (blog == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
_context.Blogspot.Remove(blog);
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
|
||||
return Ok(blog);
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_context.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
private bool BlogExists(long id)
|
||||
{
|
||||
return _context.Blogspot.Count(e => e.Id == id) > 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
147
src/Yavsc/ApiControllers/BlogTagsApiController.cs
Normal file
|
|
@ -0,0 +1,147 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNet.Http;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Data.Entity;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Models.Blog;
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[Produces("application/json")]
|
||||
[Route("api/blogtags")]
|
||||
public class BlogTagsApiController : Controller
|
||||
{
|
||||
private ApplicationDbContext _context;
|
||||
|
||||
public BlogTagsApiController(ApplicationDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
// GET: api/BlogTagsApi
|
||||
[HttpGet]
|
||||
public IEnumerable<BlogTag> GetTagsDomain()
|
||||
{
|
||||
return _context.TagsDomain;
|
||||
}
|
||||
|
||||
// GET: api/BlogTagsApi/5
|
||||
[HttpGet("{id}", Name = "GetBlogTag")]
|
||||
public async Task<IActionResult> GetBlogTag([FromRoute] long id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
BlogTag blogTag = await _context.TagsDomain.SingleAsync(m => m.PostId == id);
|
||||
|
||||
if (blogTag == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
return Ok(blogTag);
|
||||
}
|
||||
|
||||
// PUT: api/BlogTagsApi/5
|
||||
[HttpPut("{id}")]
|
||||
public async Task<IActionResult> PutBlogTag([FromRoute] long id, [FromBody] BlogTag blogTag)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
if (id != blogTag.PostId)
|
||||
{
|
||||
return HttpBadRequest();
|
||||
}
|
||||
|
||||
_context.Entry(blogTag).State = EntityState.Modified;
|
||||
|
||||
try
|
||||
{
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
if (!BlogTagExists(id))
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return new HttpStatusCodeResult(StatusCodes.Status204NoContent);
|
||||
}
|
||||
|
||||
// POST: api/BlogTagsApi
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> PostBlogTag([FromBody] BlogTag blogTag)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
_context.TagsDomain.Add(blogTag);
|
||||
try
|
||||
{
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
catch (DbUpdateException)
|
||||
{
|
||||
if (BlogTagExists(blogTag.PostId))
|
||||
{
|
||||
return new HttpStatusCodeResult(StatusCodes.Status409Conflict);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return CreatedAtRoute("GetBlogTag", new { id = blogTag.PostId }, blogTag);
|
||||
}
|
||||
|
||||
// DELETE: api/BlogTagsApi/5
|
||||
[HttpDelete("{id}")]
|
||||
public async Task<IActionResult> DeleteBlogTag([FromRoute] long id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
BlogTag blogTag = await _context.TagsDomain.SingleAsync(m => m.PostId == id);
|
||||
if (blogTag == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
_context.TagsDomain.Remove(blogTag);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
return Ok(blogTag);
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_context.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
private bool BlogTagExists(long id)
|
||||
{
|
||||
return _context.TagsDomain.Count(e => e.PostId == id) > 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
195
src/Yavsc/ApiControllers/BookQueryApiController.cs
Normal file
|
|
@ -0,0 +1,195 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNet.Authorization;
|
||||
using Microsoft.AspNet.Http;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Data.Entity;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
using System;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Models.Workflow;
|
||||
using Yavsc.Models.Billing;
|
||||
using Yavsc.Abstract.Identity;
|
||||
|
||||
[Produces("application/json")]
|
||||
[Route("api/bookquery"), Authorize(Roles = "Performer,Administrator")]
|
||||
public class BookQueryApiController : Controller
|
||||
{
|
||||
private ApplicationDbContext _context;
|
||||
private ILogger _logger;
|
||||
|
||||
public BookQueryApiController(ApplicationDbContext context, ILoggerFactory loggerFactory)
|
||||
{
|
||||
_context = context;
|
||||
_logger = loggerFactory.CreateLogger<BookQueryApiController>();
|
||||
}
|
||||
|
||||
// GET: api/BookQueryApi
|
||||
/// <summary>
|
||||
/// Book queries, by creation order
|
||||
/// </summary>
|
||||
/// <param name="maxId">returned Ids must be lower than this value</param>
|
||||
/// <returns>book queries</returns>
|
||||
[HttpGet]
|
||||
public IEnumerable<RdvQueryProviderInfo> GetCommands(long maxId=long.MaxValue)
|
||||
{
|
||||
var uid = User.GetUserId();
|
||||
var now = DateTime.Now;
|
||||
|
||||
var result = _context.RdvQueries.Include(c => c.Location).
|
||||
Include(c => c.Client).Where(c => c.PerformerId == uid && c.Id < maxId && c.EventDate > now
|
||||
&& c.ValidationDate == null).
|
||||
Select(c => new RdvQueryProviderInfo
|
||||
{
|
||||
Client = new ClientProviderInfo {
|
||||
UserName = c.Client.UserName,
|
||||
UserId = c.ClientId,
|
||||
Avatar = c.Client.Avatar },
|
||||
Location = c.Location,
|
||||
EventDate = c.EventDate,
|
||||
Id = c.Id,
|
||||
Previsional = c.Previsional,
|
||||
Reason = c.Reason,
|
||||
ActivityCode = c.ActivityCode,
|
||||
BillingCode = BillingCodes.Rdv
|
||||
}).
|
||||
OrderBy(c=>c.Id).
|
||||
Take(25);
|
||||
return result;
|
||||
}
|
||||
|
||||
// GET: api/BookQueryApi/5
|
||||
[HttpGet("{id}", Name = "GetBookQuery")]
|
||||
public IActionResult GetBookQuery([FromRoute] long id)
|
||||
{
|
||||
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
var uid = User.GetUserId();
|
||||
|
||||
RdvQuery bookQuery = _context.RdvQueries.Where(c => c.ClientId == uid || c.PerformerId == uid).Single(m => m.Id == id);
|
||||
|
||||
if (bookQuery == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
return Ok(bookQuery);
|
||||
}
|
||||
|
||||
// PUT: api/BookQueryApi/5
|
||||
[HttpPut("{id}")]
|
||||
public IActionResult PutBookQuery(long id, [FromBody] RdvQuery bookQuery)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
if (id != bookQuery.Id)
|
||||
{
|
||||
return HttpBadRequest();
|
||||
}
|
||||
var uid = User.GetUserId();
|
||||
if (bookQuery.ClientId != uid)
|
||||
return HttpNotFound();
|
||||
|
||||
_context.Entry(bookQuery).State = EntityState.Modified;
|
||||
|
||||
try
|
||||
{
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
if (!BookQueryExists(id))
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return new HttpStatusCodeResult(StatusCodes.Status204NoContent);
|
||||
}
|
||||
|
||||
// POST: api/BookQueryApi
|
||||
[HttpPost]
|
||||
public IActionResult PostBookQuery([FromBody] RdvQuery bookQuery)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
var uid = User.GetUserId();
|
||||
if (bookQuery.ClientId != uid)
|
||||
{
|
||||
ModelState.AddModelError("ClientId", "You must be the client at creating a book query");
|
||||
return new BadRequestObjectResult(ModelState);
|
||||
}
|
||||
_context.RdvQueries.Add(bookQuery);
|
||||
try
|
||||
{
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
}
|
||||
catch (DbUpdateException)
|
||||
{
|
||||
if (BookQueryExists(bookQuery.Id))
|
||||
{
|
||||
return new HttpStatusCodeResult(StatusCodes.Status409Conflict);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return CreatedAtRoute("GetBookQuery", new { id = bookQuery.Id }, bookQuery);
|
||||
}
|
||||
|
||||
// DELETE: api/BookQueryApi/5
|
||||
[HttpDelete("{id}")]
|
||||
public IActionResult DeleteBookQuery(long id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
var uid = User.GetUserId();
|
||||
RdvQuery bookQuery = _context.RdvQueries.Single(m => m.Id == id);
|
||||
|
||||
if (bookQuery == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
if (bookQuery.ClientId != uid) return HttpNotFound();
|
||||
|
||||
_context.RdvQueries.Remove(bookQuery);
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
|
||||
return Ok(bookQuery);
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_context.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
private bool BookQueryExists(long id)
|
||||
{
|
||||
return _context.RdvQueries.Count(e => e.Id == id) > 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
52
src/Yavsc/ApiControllers/ChatApiController.cs
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Data.Entity;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
using Microsoft.AspNet.Identity;
|
||||
using Models;
|
||||
using ViewModels.Chat;
|
||||
[Route("api/chat")]
|
||||
public class ChatApiController : Controller
|
||||
{
|
||||
ApplicationDbContext dbContext;
|
||||
UserManager<ApplicationUser> userManager;
|
||||
public ChatApiController(ApplicationDbContext dbContext,
|
||||
UserManager<ApplicationUser> userManager)
|
||||
{
|
||||
this.dbContext = dbContext;
|
||||
this.userManager = userManager;
|
||||
}
|
||||
|
||||
[HttpGet("users")]
|
||||
public IEnumerable<ChatUserInfo> GetUserList()
|
||||
{
|
||||
List<ChatUserInfo> result = new List<ChatUserInfo>();
|
||||
var cxsQuery = dbContext.Connections?.Include(c=>c.Owner).GroupBy( c => c.ApplicationUserId );
|
||||
|
||||
// List<ChatUserInfo> result = new List<ChatUserInfo>();
|
||||
if (cxsQuery!=null)
|
||||
foreach (var g in cxsQuery) {
|
||||
|
||||
var uid = g.Key;
|
||||
var cxs = g.ToList();
|
||||
if (cxs !=null)
|
||||
if (cxs.Count>0) {
|
||||
var user = cxs.First().Owner;
|
||||
if (user!=null ) {
|
||||
result.Add(new ChatUserInfo { UserName = user.UserName,
|
||||
UserId = user.Id, Avatar = user.Avatar, Connections = cxs,
|
||||
Roles = ( userManager.GetRolesAsync(user) ).Result.ToArray() });
|
||||
}
|
||||
else {
|
||||
result.Add(new ChatUserInfo { Connections = cxs });
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
149
src/Yavsc/ApiControllers/CircleApiController.cs
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNet.Http;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Data.Entity;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Models.Relationship;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[Produces("application/json")]
|
||||
[Route("api/cirle")]
|
||||
public class CircleApiController : Controller
|
||||
{
|
||||
private ApplicationDbContext _context;
|
||||
|
||||
public CircleApiController(ApplicationDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
// GET: api/CircleApi
|
||||
[HttpGet]
|
||||
public IEnumerable<Circle> GetCircle()
|
||||
{
|
||||
return _context.Circle;
|
||||
}
|
||||
|
||||
// GET: api/CircleApi/5
|
||||
[HttpGet("{id}", Name = "GetCircle")]
|
||||
public async Task<IActionResult> GetCircle([FromRoute] long id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
Circle circle = await _context.Circle.SingleAsync(m => m.Id == id);
|
||||
|
||||
if (circle == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
return Ok(circle);
|
||||
}
|
||||
|
||||
// PUT: api/CircleApi/5
|
||||
[HttpPut("{id}")]
|
||||
public async Task<IActionResult> PutCircle([FromRoute] long id, [FromBody] Circle circle)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
if (id != circle.Id)
|
||||
{
|
||||
return HttpBadRequest();
|
||||
}
|
||||
|
||||
_context.Entry(circle).State = EntityState.Modified;
|
||||
|
||||
try
|
||||
{
|
||||
await _context.SaveChangesAsync(User.GetUserId());
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
if (!CircleExists(id))
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return new HttpStatusCodeResult(StatusCodes.Status204NoContent);
|
||||
}
|
||||
|
||||
// POST: api/CircleApi
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> PostCircle([FromBody] Circle circle)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
_context.Circle.Add(circle);
|
||||
try
|
||||
{
|
||||
await _context.SaveChangesAsync(User.GetUserId());
|
||||
}
|
||||
catch (DbUpdateException)
|
||||
{
|
||||
if (CircleExists(circle.Id))
|
||||
{
|
||||
return new HttpStatusCodeResult(StatusCodes.Status409Conflict);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return CreatedAtRoute("GetCircle", new { id = circle.Id }, circle);
|
||||
}
|
||||
|
||||
// DELETE: api/CircleApi/5
|
||||
[HttpDelete("{id}")]
|
||||
public async Task<IActionResult> DeleteCircle([FromRoute] long id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
Circle circle = await _context.Circle.SingleAsync(m => m.Id == id);
|
||||
if (circle == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
_context.Circle.Remove(circle);
|
||||
await _context.SaveChangesAsync(User.GetUserId());
|
||||
|
||||
return Ok(circle);
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_context.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
private bool CircleExists(long id)
|
||||
{
|
||||
return _context.Circle.Count(e => e.Id == id) > 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
161
src/Yavsc/ApiControllers/CommentsApiController.cs
Normal file
|
|
@ -0,0 +1,161 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNet.Http;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Data.Entity;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Models.Blog;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[Produces("application/json")]
|
||||
[Route("api/blogcomments")]
|
||||
public class CommentsApiController : Controller
|
||||
{
|
||||
private ApplicationDbContext _context;
|
||||
|
||||
public CommentsApiController(ApplicationDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
// GET: api/CommentsApi
|
||||
[HttpGet]
|
||||
public IEnumerable<Comment> GetComment()
|
||||
{
|
||||
return _context.Comment;
|
||||
}
|
||||
|
||||
// GET: api/CommentsApi/5
|
||||
[HttpGet("{id}", Name = "GetComment")]
|
||||
public async Task<IActionResult> GetComment([FromRoute] long id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
Comment comment = await _context.Comment.SingleAsync(m => m.Id == id);
|
||||
|
||||
if (comment == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
return Ok(comment);
|
||||
}
|
||||
|
||||
// PUT: api/CommentsApi/5
|
||||
[HttpPut("{id}")]
|
||||
public async Task<IActionResult> PutComment([FromRoute] long id, [FromBody] Comment comment)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
if (id != comment.Id)
|
||||
{
|
||||
return HttpBadRequest();
|
||||
}
|
||||
|
||||
_context.Entry(comment).State = EntityState.Modified;
|
||||
|
||||
try
|
||||
{
|
||||
await _context.SaveChangesAsync(User.GetUserId());
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
if (!CommentExists(id))
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return new HttpStatusCodeResult(StatusCodes.Status204NoContent);
|
||||
}
|
||||
|
||||
// POST: api/CommentsApi
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> PostComment([FromBody] Comment comment)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return new BadRequestObjectResult(ModelState);
|
||||
}
|
||||
if (!User.IsInRole(Constants.AdminGroupName))
|
||||
{
|
||||
if (User.GetUserId()!=comment.AuthorId) {
|
||||
ModelState.AddModelError("Content","Vous ne pouvez pas poster au nom d'un autre.");
|
||||
return new BadRequestObjectResult(ModelState);
|
||||
}
|
||||
}
|
||||
_context.Comment.Add(comment);
|
||||
try
|
||||
{
|
||||
await _context.SaveChangesAsync(User.GetUserId());
|
||||
}
|
||||
catch (DbUpdateException)
|
||||
{
|
||||
if (CommentExists(comment.Id))
|
||||
{
|
||||
return new HttpStatusCodeResult(StatusCodes.Status409Conflict);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
return CreatedAtRoute("GetComment", new { id = comment.Id }, comment);
|
||||
}
|
||||
|
||||
// DELETE: api/CommentsApi/5
|
||||
[HttpDelete("{id}")]
|
||||
public async Task<IActionResult> DeleteComment([FromRoute] long id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
Comment comment = await _context.Comment.SingleAsync(m => m.Id == id);
|
||||
if (comment == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
RemoveRecursive(comment);
|
||||
await _context.SaveChangesAsync(User.GetUserId());
|
||||
|
||||
return Ok(comment);
|
||||
}
|
||||
private void RemoveRecursive (Comment comment)
|
||||
{
|
||||
var children = _context.Comment.Where(c=>c.ParentId==comment.Id).ToList();
|
||||
foreach (var child in children) {
|
||||
RemoveRecursive(child);
|
||||
}
|
||||
_context.Comment.Remove(comment);
|
||||
}
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_context.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
private bool CommentExists(long id)
|
||||
{
|
||||
return _context.Comment.Count(e => e.Id == id) > 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
128
src/Yavsc/ApiControllers/ContactsApiController.cs
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNet.Http;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Data.Entity;
|
||||
using Yavsc.Abstract.Identity;
|
||||
using Yavsc.Models;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[Produces("application/json")]
|
||||
[Route("api/ContactsApi")]
|
||||
public class ContactsApiController : Controller
|
||||
{
|
||||
private ApplicationDbContext _context;
|
||||
|
||||
public ContactsApiController(ApplicationDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
// GET: api/ContactsApi
|
||||
[HttpGet("{id}")]
|
||||
public ClientProviderInfo GetClientProviderInfo(string id)
|
||||
{
|
||||
return _context.ClientProviderInfo.FirstOrDefault(c=>c.UserId == id);
|
||||
}
|
||||
|
||||
// PUT: api/ContactsApi/5
|
||||
[HttpPut("{id}")]
|
||||
public IActionResult PutClientProviderInfo(string id, [FromBody] ClientProviderInfo clientProviderInfo)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
if (id != clientProviderInfo.UserId)
|
||||
{
|
||||
return HttpBadRequest();
|
||||
}
|
||||
|
||||
_context.Entry(clientProviderInfo).State = EntityState.Modified;
|
||||
|
||||
try
|
||||
{
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
if (!ClientProviderInfoExists(id))
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return new HttpStatusCodeResult(StatusCodes.Status204NoContent);
|
||||
}
|
||||
|
||||
// POST: api/ContactsApi
|
||||
[HttpPost]
|
||||
public IActionResult PostClientProviderInfo([FromBody] ClientProviderInfo clientProviderInfo)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
_context.ClientProviderInfo.Add(clientProviderInfo);
|
||||
try
|
||||
{
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
}
|
||||
catch (DbUpdateException)
|
||||
{
|
||||
if (ClientProviderInfoExists(clientProviderInfo.UserId))
|
||||
{
|
||||
return new HttpStatusCodeResult(StatusCodes.Status409Conflict);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return CreatedAtRoute("GetClientProviderInfo", new { id = clientProviderInfo.UserId }, clientProviderInfo);
|
||||
}
|
||||
|
||||
// DELETE: api/ContactsApi/5
|
||||
[HttpDelete("{id}")]
|
||||
public IActionResult DeleteClientProviderInfo(string id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
ClientProviderInfo clientProviderInfo = _context.ClientProviderInfo.Single(m => m.UserId == id);
|
||||
if (clientProviderInfo == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
_context.ClientProviderInfo.Remove(clientProviderInfo);
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
|
||||
return Ok(clientProviderInfo);
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_context.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
private bool ClientProviderInfoExists(string id)
|
||||
{
|
||||
return _context.ClientProviderInfo.Count(e => e.UserId == id) > 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
177
src/Yavsc/ApiControllers/DimissClicksApiController.cs
Normal file
|
|
@ -0,0 +1,177 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNet.Authorization;
|
||||
using Microsoft.AspNet.Http;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Data.Entity;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Models.Messaging;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[Produces("application/json")]
|
||||
[Route("api/dimiss")]
|
||||
public class DimissClicksApiController : Controller
|
||||
{
|
||||
private ApplicationDbContext _context;
|
||||
|
||||
public DimissClicksApiController(ApplicationDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
// GET: api/DimissClicksApi
|
||||
[HttpGet]
|
||||
public IEnumerable<DimissClicked> GetDimissClicked()
|
||||
{
|
||||
var uid = User.GetUserId();
|
||||
return _context.DimissClicked.Where(d=>d.UserId == uid);
|
||||
}
|
||||
|
||||
[HttpGet("click/{noteid}"),AllowAnonymous]
|
||||
public async Task<IActionResult> Click(long noteid )
|
||||
{
|
||||
if (User.IsSignedIn())
|
||||
return await PostDimissClicked(new DimissClicked { 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 = "GetDimissClicked")]
|
||||
public async Task<IActionResult> GetDimissClicked([FromRoute] string id)
|
||||
{
|
||||
var uid = User.GetUserId();
|
||||
if (uid != id) return new ChallengeResult();
|
||||
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
DimissClicked dimissClicked = await _context.DimissClicked.SingleAsync(m => m.UserId == id);
|
||||
|
||||
if (dimissClicked == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
return Ok(dimissClicked);
|
||||
}
|
||||
|
||||
// PUT: api/DimissClicksApi/5
|
||||
[HttpPut("{id}")]
|
||||
public async Task<IActionResult> PutDimissClicked([FromRoute] string id, [FromBody] DimissClicked dimissClicked)
|
||||
{
|
||||
var uid = User.GetUserId();
|
||||
if (uid != id || uid != dimissClicked.UserId) return new ChallengeResult();
|
||||
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
if (id != dimissClicked.UserId)
|
||||
{
|
||||
return HttpBadRequest();
|
||||
}
|
||||
|
||||
_context.Entry(dimissClicked).State = EntityState.Modified;
|
||||
|
||||
try
|
||||
{
|
||||
await _context.SaveChangesAsync(User.GetUserId());
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
if (!DimissClickedExists(id))
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return new HttpStatusCodeResult(StatusCodes.Status204NoContent);
|
||||
}
|
||||
|
||||
// POST: api/DimissClicksApi
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> PostDimissClicked([FromBody] DimissClicked dimissClicked)
|
||||
{
|
||||
var uid = User.GetUserId();
|
||||
if (uid != dimissClicked.UserId) return new ChallengeResult();
|
||||
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
_context.DimissClicked.Add(dimissClicked);
|
||||
try
|
||||
{
|
||||
await _context.SaveChangesAsync(User.GetUserId());
|
||||
}
|
||||
catch (DbUpdateException)
|
||||
{
|
||||
if (DimissClickedExists(dimissClicked.UserId))
|
||||
{
|
||||
return new HttpStatusCodeResult(StatusCodes.Status409Conflict);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return CreatedAtRoute("GetDimissClicked", new { id = dimissClicked.UserId }, dimissClicked);
|
||||
}
|
||||
|
||||
// DELETE: api/DimissClicksApi/5
|
||||
[HttpDelete("{id}")]
|
||||
public async Task<IActionResult> DeleteDimissClicked([FromRoute] string id)
|
||||
{
|
||||
var uid = User.GetUserId();
|
||||
if (!User.IsInRole("Administrator"))
|
||||
if (uid != id) return new ChallengeResult();
|
||||
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
DimissClicked dimissClicked = await _context.DimissClicked.SingleAsync(m => m.UserId == id);
|
||||
if (dimissClicked == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
_context.DimissClicked.Remove(dimissClicked);
|
||||
await _context.SaveChangesAsync(User.GetUserId());
|
||||
|
||||
return Ok(dimissClicked);
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_context.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
private bool DimissClickedExists(string id)
|
||||
{
|
||||
return _context.DimissClicked.Count(e => e.UserId == id) > 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
213
src/Yavsc/ApiControllers/EstimateApiController.cs
Normal file
|
|
@ -0,0 +1,213 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNet.Authorization;
|
||||
using Microsoft.AspNet.Http;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Data.Entity;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Newtonsoft.Json;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Models.Billing;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[Produces("application/json")]
|
||||
[Route("api/estimate"),Authorize()]
|
||||
public class EstimateApiController : Controller
|
||||
{
|
||||
private ApplicationDbContext _context;
|
||||
private ILogger _logger;
|
||||
public EstimateApiController(ApplicationDbContext context, ILoggerFactory loggerFactory)
|
||||
{
|
||||
_context = context;
|
||||
_logger = loggerFactory.CreateLogger<EstimateApiController>();
|
||||
}
|
||||
bool UserIsAdminOrThis(string uid)
|
||||
{
|
||||
if (User.IsInRole(Constants.AdminGroupName)) return true;
|
||||
return uid == User.GetUserId();
|
||||
}
|
||||
bool UserIsAdminOrInThese (string oid, string uid)
|
||||
{
|
||||
if (User.IsInRole(Constants.AdminGroupName)) return true;
|
||||
var cuid = User.GetUserId();
|
||||
return cuid == uid || cuid == oid;
|
||||
}
|
||||
// GET: api/Estimate{?ownerId=User.GetUserId()}
|
||||
[HttpGet]
|
||||
public IActionResult GetEstimates(string ownerId=null)
|
||||
{
|
||||
if ( ownerId == null ) ownerId = User.GetUserId();
|
||||
else if (!UserIsAdminOrThis(ownerId)) // throw new Exception("Not authorized") ;
|
||||
// or just do nothing
|
||||
return new HttpStatusCodeResult(StatusCodes.Status403Forbidden);
|
||||
return Ok(_context.Estimates.Include(e=>e.Bill).Where(e=>e.OwnerId == ownerId));
|
||||
}
|
||||
// GET: api/Estimate/5
|
||||
[HttpGet("{id}", Name = "GetEstimate")]
|
||||
public IActionResult GetEstimate([FromRoute] long id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
Estimate estimate = _context.Estimates.Include(e=>e.Bill).Single(m => m.Id == id);
|
||||
|
||||
if (estimate == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
if (UserIsAdminOrInThese(estimate.ClientId,estimate.OwnerId))
|
||||
return Ok(estimate);
|
||||
return new HttpStatusCodeResult(StatusCodes.Status403Forbidden);
|
||||
}
|
||||
|
||||
// PUT: api/Estimate/5
|
||||
[HttpPut("{id}"),Produces("application/json")]
|
||||
public IActionResult PutEstimate(long id, [FromBody] Estimate estimate)
|
||||
{
|
||||
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return new BadRequestObjectResult(ModelState);
|
||||
}
|
||||
|
||||
if (id != estimate.Id)
|
||||
{
|
||||
return HttpBadRequest();
|
||||
}
|
||||
var uid = User.GetUserId();
|
||||
if (!User.IsInRole(Constants.AdminGroupName))
|
||||
{
|
||||
if (uid != estimate.OwnerId)
|
||||
{
|
||||
ModelState.AddModelError("OwnerId","You can only modify your own estimates");
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
}
|
||||
|
||||
var entry = _context.Attach(estimate);
|
||||
try
|
||||
{
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
if (!EstimateExists(id))
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return Ok( new { Id = estimate.Id });
|
||||
}
|
||||
|
||||
// POST: api/Estimate
|
||||
[HttpPost,Produces("application/json")]
|
||||
public IActionResult PostEstimate([FromBody] Estimate estimate)
|
||||
{
|
||||
var uid = User.GetUserId();
|
||||
if (estimate.OwnerId==null) estimate.OwnerId = uid;
|
||||
|
||||
if (!User.IsInRole(Constants.AdminGroupName)) {
|
||||
if (uid != estimate.OwnerId)
|
||||
{
|
||||
ModelState.AddModelError("OwnerId","You can only create your own estimates");
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
}
|
||||
|
||||
if (estimate.CommandId!=null) {
|
||||
var query = _context.RdvQueries.FirstOrDefault(q => q.Id == estimate.CommandId);
|
||||
if (query == null) {
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
query.ValidationDate = DateTime.Now;
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
_context.Entry(query).State = EntityState.Detached;
|
||||
}
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
_logger.LogError(JsonConvert.SerializeObject(ModelState));
|
||||
return Json(ModelState);
|
||||
}
|
||||
_context.Estimates.Add(estimate);
|
||||
|
||||
|
||||
/* _context.AttachRange(estimate.Bill);
|
||||
_context.Attach(estimate);
|
||||
_context.Entry(estimate).State = EntityState.Added;
|
||||
foreach (var line in estimate.Bill)
|
||||
_context.Entry(line).State = EntityState.Added;
|
||||
// foreach (var l in estimate.Bill) _context.Attach<CommandLine>(l);
|
||||
*/
|
||||
try
|
||||
{
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
}
|
||||
catch (DbUpdateException)
|
||||
{
|
||||
if (EstimateExists(estimate.Id))
|
||||
{
|
||||
return new HttpStatusCodeResult(StatusCodes.Status409Conflict);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
return Ok( new { Id = estimate.Id, Bill = estimate.Bill });
|
||||
}
|
||||
|
||||
// DELETE: api/Estimate/5
|
||||
[HttpDelete("{id}")]
|
||||
public IActionResult DeleteEstimate(long id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
Estimate estimate = _context.Estimates.Include(e=>e.Bill).Single(m => m.Id == id);
|
||||
|
||||
if (estimate == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
var uid = User.GetUserId();
|
||||
if (!User.IsInRole(Constants.AdminGroupName))
|
||||
{
|
||||
if (uid != estimate.OwnerId)
|
||||
{
|
||||
ModelState.AddModelError("OwnerId","You can only create your own estimates");
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
}
|
||||
_context.Estimates.Remove(estimate);
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
|
||||
return Ok(estimate);
|
||||
}
|
||||
|
||||
protected override void Dispose (bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_context.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
private bool EstimateExists(long id)
|
||||
{
|
||||
return _context.Estimates.Count(e => e.Id == id) > 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
159
src/Yavsc/ApiControllers/EstimateTemplatesApiController.cs
Normal file
|
|
@ -0,0 +1,159 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNet.Http;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Data.Entity;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Models.Billing;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[Produces("application/json")]
|
||||
[Route("api/EstimateTemplatesApi")]
|
||||
public class EstimateTemplatesApiController : Controller
|
||||
{
|
||||
private ApplicationDbContext _context;
|
||||
|
||||
public EstimateTemplatesApiController(ApplicationDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
// GET: api/EstimateTemplatesApi
|
||||
[HttpGet]
|
||||
public IEnumerable<EstimateTemplate> GetEstimateTemplate()
|
||||
{
|
||||
var uid = User.GetUserId();
|
||||
return _context.EstimateTemplates.Where(x=>x.OwnerId==uid);
|
||||
}
|
||||
|
||||
// GET: api/EstimateTemplatesApi/5
|
||||
[HttpGet("{id}", Name = "GetEstimateTemplate")]
|
||||
public IActionResult GetEstimateTemplate([FromRoute] long id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
var uid = User.GetUserId();
|
||||
|
||||
EstimateTemplate estimateTemplate = _context.EstimateTemplates.Where(x=>x.OwnerId==uid).Single(m => m.Id == id);
|
||||
|
||||
if (estimateTemplate == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
return Ok(estimateTemplate);
|
||||
}
|
||||
|
||||
// PUT: api/EstimateTemplatesApi/5
|
||||
[HttpPut("{id}")]
|
||||
public IActionResult PutEstimateTemplate(long id, [FromBody] EstimateTemplate estimateTemplate)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
if (id != estimateTemplate.Id)
|
||||
{
|
||||
return HttpBadRequest();
|
||||
}
|
||||
var uid = User.GetUserId();
|
||||
if (estimateTemplate.OwnerId!=uid)
|
||||
if (!User.IsInRole(Constants.AdminGroupName))
|
||||
return new HttpStatusCodeResult(StatusCodes.Status403Forbidden);
|
||||
|
||||
_context.Entry(estimateTemplate).State = EntityState.Modified;
|
||||
|
||||
try
|
||||
{
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
if (!EstimateTemplateExists(id))
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return new HttpStatusCodeResult(StatusCodes.Status204NoContent);
|
||||
}
|
||||
|
||||
// POST: api/EstimateTemplatesApi
|
||||
[HttpPost]
|
||||
public IActionResult PostEstimateTemplate([FromBody] EstimateTemplate estimateTemplate)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
estimateTemplate.OwnerId=User.GetUserId();
|
||||
|
||||
_context.EstimateTemplates.Add(estimateTemplate);
|
||||
try
|
||||
{
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
}
|
||||
catch (DbUpdateException)
|
||||
{
|
||||
if (EstimateTemplateExists(estimateTemplate.Id))
|
||||
{
|
||||
return new HttpStatusCodeResult(StatusCodes.Status409Conflict);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return CreatedAtRoute("GetEstimateTemplate", new { id = estimateTemplate.Id }, estimateTemplate);
|
||||
}
|
||||
|
||||
// DELETE: api/EstimateTemplatesApi/5
|
||||
[HttpDelete("{id}")]
|
||||
public IActionResult DeleteEstimateTemplate(long id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
EstimateTemplate estimateTemplate = _context.EstimateTemplates.Single(m => m.Id == id);
|
||||
if (estimateTemplate == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
var uid = User.GetUserId();
|
||||
if (estimateTemplate.OwnerId!=uid)
|
||||
if (!User.IsInRole(Constants.AdminGroupName))
|
||||
return new HttpStatusCodeResult(StatusCodes.Status403Forbidden);
|
||||
|
||||
_context.EstimateTemplates.Remove(estimateTemplate);
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
|
||||
return Ok(estimateTemplate);
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_context.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
private bool EstimateTemplateExists(long id)
|
||||
{
|
||||
return _context.EstimateTemplates.Count(e => e.Id == id) > 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
113
src/Yavsc/ApiControllers/FileSystemApiController.cs
Normal file
|
|
@ -0,0 +1,113 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNet.Authorization;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Yavsc.Helpers;
|
||||
using Yavsc.Models;
|
||||
|
||||
namespace Yavsc.ApiControllers
|
||||
{
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Yavsc.Abstract.FileSystem;
|
||||
using Yavsc.Exceptions;
|
||||
using Yavsc.Models.FileSystem;
|
||||
|
||||
public class FSQuotaException : Exception {
|
||||
|
||||
}
|
||||
|
||||
[Authorize,Route("api/fs")]
|
||||
public class FileSystemApiController : Controller
|
||||
{
|
||||
ApplicationDbContext dbContext;
|
||||
private IAuthorizationService AuthorizationService;
|
||||
private ILogger logger;
|
||||
|
||||
public FileSystemApiController(ApplicationDbContext context,
|
||||
IAuthorizationService authorizationService,
|
||||
ILoggerFactory loggerFactory)
|
||||
|
||||
{
|
||||
AuthorizationService = authorizationService;
|
||||
dbContext = context;
|
||||
logger = loggerFactory.CreateLogger<FileSystemApiController>();
|
||||
}
|
||||
|
||||
[HttpGet()]
|
||||
public IActionResult Get()
|
||||
{
|
||||
return GetDir(null);
|
||||
}
|
||||
|
||||
[HttpGet("{*subdir}")]
|
||||
public IActionResult GetDir(string subdir="")
|
||||
{
|
||||
if (subdir !=null)
|
||||
if (!subdir.IsValidYavscPath())
|
||||
return new BadRequestResult();
|
||||
var files = User.GetUserFiles(subdir);
|
||||
return Ok(files);
|
||||
}
|
||||
|
||||
[HttpPost("{*subdir}")]
|
||||
public IActionResult Post(string subdir="")
|
||||
{
|
||||
string destDir = null;
|
||||
List<FileRecievedInfo> received = new List<FileRecievedInfo>();
|
||||
InvalidPathException pathex = null;
|
||||
try {
|
||||
destDir = User.InitPostToFileSystem(subdir);
|
||||
} catch (InvalidPathException ex) {
|
||||
pathex = ex;
|
||||
}
|
||||
if (pathex!=null) {
|
||||
logger.LogError($"invalid sub path: '{subdir}'.");
|
||||
return HttpBadRequest(pathex);
|
||||
}
|
||||
logger.LogInformation($"Receiving files, saved in '{destDir}' (specified as '{subdir}').");
|
||||
|
||||
var uid = User.GetUserId();
|
||||
var user = dbContext.Users.Single(
|
||||
u => u.Id == uid
|
||||
);
|
||||
int i=0;
|
||||
logger.LogInformation($"Receiving {Request.Form.Files.Count} files.");
|
||||
|
||||
foreach (var f in Request.Form.Files)
|
||||
{
|
||||
|
||||
var item = user.ReceiveUserFile(destDir, f);
|
||||
dbContext.SaveChanges(User.GetUserId());
|
||||
received.Add(item);
|
||||
logger.LogInformation($"Received '{item.FileName}'.");
|
||||
if (item.QuotaOffensed)
|
||||
break;
|
||||
i++;
|
||||
};
|
||||
return Ok(received);
|
||||
}
|
||||
|
||||
[HttpDelete]
|
||||
public async Task <IActionResult> Delete (string id)
|
||||
{
|
||||
var user = dbContext.Users.Single(
|
||||
u => u.Id == User.GetUserId()
|
||||
);
|
||||
InvalidPathException pathex = null;
|
||||
string root = null;
|
||||
try {
|
||||
root = User.InitPostToFileSystem(id);
|
||||
} catch (InvalidPathException ex) {
|
||||
pathex = ex;
|
||||
}
|
||||
if (pathex!=null)
|
||||
return new BadRequestObjectResult(pathex);
|
||||
user.DeleteUserFile(id);
|
||||
await dbContext.SaveChangesAsync(User.GetUserId());
|
||||
return Ok(new { deleted=id });
|
||||
}
|
||||
}
|
||||
}
|
||||
42
src/Yavsc/ApiControllers/FrontOfficeApiController.cs
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Yavsc.Helpers;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Services;
|
||||
using Yavsc.ViewModels.FrontOffice;
|
||||
|
||||
namespace Yavsc.ApiControllers
|
||||
{
|
||||
[Route("api/front")]
|
||||
public class FrontOfficeApiController: Controller
|
||||
{
|
||||
ApplicationDbContext dbContext;
|
||||
private IBillingService billing;
|
||||
|
||||
public FrontOfficeApiController(ApplicationDbContext context, IBillingService billing)
|
||||
{
|
||||
dbContext = context;
|
||||
this.billing = billing;
|
||||
}
|
||||
|
||||
[HttpGet("profiles/{actCode}")]
|
||||
IEnumerable<PerformerProfileViewModel> Profiles (string actCode)
|
||||
{
|
||||
return dbContext.ListPerformers(billing, actCode);
|
||||
}
|
||||
|
||||
[HttpPost("query/reject")]
|
||||
public IActionResult RejectQuery (string billingCode, long queryId)
|
||||
{
|
||||
if (billingCode==null) return HttpBadRequest("billingCode");
|
||||
if (queryId==0) return HttpBadRequest("queryId");
|
||||
var billing = BillingService.GetBillable(dbContext, billingCode, queryId);
|
||||
if (billing==null) return HttpBadRequest();
|
||||
billing.Rejected = true;
|
||||
billing.RejectedAt = DateTime.Now;
|
||||
dbContext.SaveChanges();
|
||||
return Ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
70
src/Yavsc/ApiControllers/GCMController.cs
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNet.Authorization;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Models.Identity;
|
||||
|
||||
[Authorize, Route("~/api/gcm")]
|
||||
public class GCMController : Controller
|
||||
{
|
||||
ILogger _logger;
|
||||
ApplicationDbContext _context;
|
||||
|
||||
public GCMController(ApplicationDbContext context,
|
||||
ILoggerFactory loggerFactory)
|
||||
{
|
||||
_logger = loggerFactory.CreateLogger<GCMController>();
|
||||
_context = context;
|
||||
}
|
||||
/// <summary>
|
||||
/// This is not a method supporting user creation.
|
||||
/// It only registers Google Clood Messaging id.
|
||||
/// </summary>
|
||||
/// <param name="declaration"></param>
|
||||
/// <returns></returns>
|
||||
[Authorize, HttpPost("register")]
|
||||
public IActionResult Register(
|
||||
[FromBody] GoogleCloudMobileDeclaration declaration)
|
||||
{
|
||||
var uid = User.GetUserId();
|
||||
|
||||
_logger.LogInformation($"Registering device with id:{declaration.DeviceId} for {uid}");
|
||||
if (ModelState.IsValid)
|
||||
{
|
||||
var alreadyRegisteredDevice = _context.GCMDevices.FirstOrDefault(d => d.DeviceId == declaration.DeviceId);
|
||||
var deviceAlreadyRegistered = (alreadyRegisteredDevice!=null);
|
||||
if (deviceAlreadyRegistered)
|
||||
{
|
||||
_logger.LogInformation($"deviceAlreadyRegistered");
|
||||
// Override an exiting owner
|
||||
alreadyRegisteredDevice.DeclarationDate = DateTime.Now;
|
||||
alreadyRegisteredDevice.DeviceOwnerId = uid;
|
||||
alreadyRegisteredDevice.GCMRegistrationId = declaration.GCMRegistrationId;
|
||||
alreadyRegisteredDevice.Model = declaration.Model;
|
||||
alreadyRegisteredDevice.Platform = declaration.Platform;
|
||||
alreadyRegisteredDevice.Version = declaration.Version;
|
||||
_context.Update(alreadyRegisteredDevice);
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogInformation($"new device");
|
||||
declaration.DeclarationDate = DateTime.Now;
|
||||
declaration.DeviceOwnerId = uid;
|
||||
_context.GCMDevices.Add(declaration as GoogleCloudMobileDeclaration);
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
}
|
||||
var latestActivityUpdate = _context.Activities.Max(a=>a.DateModified);
|
||||
return Json(new {
|
||||
IsAnUpdate = deviceAlreadyRegistered,
|
||||
UpdateActivities = (latestActivityUpdate != declaration.LatestActivityUpdate)
|
||||
});
|
||||
}
|
||||
return new BadRequestObjectResult(ModelState);
|
||||
}
|
||||
|
||||
}
|
||||
153
src/Yavsc/ApiControllers/HairCut/BursherProfilesApiController.cs
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNet.Http;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Data.Entity;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Models.Haircut;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[Produces("application/json")]
|
||||
[Route("api/bursherprofiles")]
|
||||
public class BursherProfilesApiController : Controller
|
||||
{
|
||||
private ApplicationDbContext _context;
|
||||
|
||||
public BursherProfilesApiController(ApplicationDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
// GET: api/BursherProfilesApi
|
||||
[HttpGet]
|
||||
public IEnumerable<BrusherProfile> GetBrusherProfile()
|
||||
{
|
||||
return _context.BrusherProfile.Include(p=>p.BaseProfile).Where(p => p.BaseProfile.Active);
|
||||
}
|
||||
|
||||
// GET: api/BursherProfilesApi/5
|
||||
[HttpGet("{id}", Name = "GetBrusherProfile")]
|
||||
public async Task<IActionResult> GetBrusherProfile([FromRoute] string id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
BrusherProfile brusherProfile = await _context.BrusherProfile.SingleAsync(m => m.UserId == id);
|
||||
|
||||
if (brusherProfile == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
return Ok(brusherProfile);
|
||||
}
|
||||
|
||||
// PUT: api/BursherProfilesApi/5
|
||||
[HttpPut("{id}")]
|
||||
public async Task<IActionResult> PutBrusherProfile([FromRoute] string id, [FromBody] BrusherProfile brusherProfile)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
if (id != brusherProfile.UserId)
|
||||
{
|
||||
return HttpBadRequest();
|
||||
}
|
||||
|
||||
if (id != User.GetUserId())
|
||||
{
|
||||
return HttpBadRequest();
|
||||
}
|
||||
_context.Entry(brusherProfile).State = EntityState.Modified;
|
||||
|
||||
try
|
||||
{
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
if (!BrusherProfileExists(id))
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return new HttpStatusCodeResult(StatusCodes.Status204NoContent);
|
||||
}
|
||||
|
||||
// POST: api/BursherProfilesApi
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> PostBrusherProfile([FromBody] BrusherProfile brusherProfile)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
_context.BrusherProfile.Add(brusherProfile);
|
||||
try
|
||||
{
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
catch (DbUpdateException)
|
||||
{
|
||||
if (BrusherProfileExists(brusherProfile.UserId))
|
||||
{
|
||||
return new HttpStatusCodeResult(StatusCodes.Status409Conflict);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return CreatedAtRoute("GetBrusherProfile", new { id = brusherProfile.UserId }, brusherProfile);
|
||||
}
|
||||
|
||||
// DELETE: api/BursherProfilesApi/5
|
||||
[HttpDelete("{id}")]
|
||||
public async Task<IActionResult> DeleteBrusherProfile([FromRoute] string id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
BrusherProfile brusherProfile = await _context.BrusherProfile.SingleAsync(m => m.UserId == id);
|
||||
if (brusherProfile == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
_context.BrusherProfile.Remove(brusherProfile);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
return Ok(brusherProfile);
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_context.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
private bool BrusherProfileExists(string id)
|
||||
{
|
||||
return _context.BrusherProfile.Count(e => e.UserId == id) > 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
252
src/Yavsc/ApiControllers/HairCut/HairCutController.cs
Normal file
|
|
@ -0,0 +1,252 @@
|
|||
using Microsoft.AspNet.Identity;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Extensions.OptionsModel;
|
||||
using Microsoft.Extensions.Localization;
|
||||
|
||||
|
||||
namespace Yavsc.ApiControllers
|
||||
{
|
||||
using Yavsc;
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Models;
|
||||
using Services;
|
||||
using Models.Haircut;
|
||||
using Resources;
|
||||
using System.Threading.Tasks;
|
||||
using Helpers;
|
||||
using Microsoft.Data.Entity;
|
||||
using Models.Payment;
|
||||
using Newtonsoft.Json;
|
||||
using PayPal.PayPalAPIInterfaceService.Model;
|
||||
using Yavsc.Models.Haircut.Views;
|
||||
using Microsoft.AspNet.Http;
|
||||
|
||||
[Route("api/haircut")]
|
||||
public class HairCutController : Controller
|
||||
{
|
||||
private ApplicationDbContext _context;
|
||||
private IEmailSender _emailSender;
|
||||
private IGoogleCloudMessageSender _GCMSender;
|
||||
private GoogleAuthSettings _googleSettings;
|
||||
private IStringLocalizer<YavscLocalisation> _localizer;
|
||||
private ILogger _logger;
|
||||
private SiteSettings _siteSettings;
|
||||
private SmtpSettings _smtpSettings;
|
||||
private UserManager<ApplicationUser> _userManager;
|
||||
|
||||
PayPalSettings _paymentSettings;
|
||||
public HairCutController(ApplicationDbContext context,
|
||||
IOptions<GoogleAuthSettings> googleSettings,
|
||||
IGoogleCloudMessageSender GCMSender,
|
||||
UserManager<ApplicationUser> userManager,
|
||||
IStringLocalizer<Yavsc.Resources.YavscLocalisation> localizer,
|
||||
IEmailSender emailSender,
|
||||
IOptions<SmtpSettings> smtpSettings,
|
||||
IOptions<SiteSettings> siteSettings,
|
||||
IOptions<PayPalSettings> payPalSettings,
|
||||
ILoggerFactory loggerFactory)
|
||||
{
|
||||
_context = context;
|
||||
_GCMSender = GCMSender;
|
||||
_emailSender = emailSender;
|
||||
_googleSettings = googleSettings.Value;
|
||||
_userManager = userManager;
|
||||
_smtpSettings = smtpSettings.Value;
|
||||
_siteSettings = siteSettings.Value;
|
||||
_paymentSettings = payPalSettings.Value;
|
||||
_localizer = localizer;
|
||||
_logger = loggerFactory.CreateLogger<HairCutController>();
|
||||
}
|
||||
|
||||
// GET: api/HairCutQueriesApi
|
||||
// Get the active queries for current
|
||||
// user, as a client
|
||||
public IActionResult Index()
|
||||
{
|
||||
var uid = User.GetUserId();
|
||||
var now = DateTime.Now;
|
||||
var result = _context.HairCutQueries
|
||||
.Include(q => q.Prestation)
|
||||
.Include(q => q.Client)
|
||||
.Include(q => q.PerformerProfile)
|
||||
.Include(q => q.Location)
|
||||
.Where(
|
||||
q => q.ClientId == uid
|
||||
&& ( q.EventDate > now || q.EventDate == null )
|
||||
&& q.Status == QueryStatus.Inserted
|
||||
).Select(q => new HaircutQueryClientInfo(q));
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
// GET: api/HairCutQueriesApi/5
|
||||
[HttpGet("{id}", Name = "GetHairCutQuery")]
|
||||
public async Task<IActionResult> GetHairCutQuery([FromRoute] long id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
HairCutQuery hairCutQuery = await _context.HairCutQueries.SingleAsync(m => m.Id == id);
|
||||
|
||||
if (hairCutQuery == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
return Ok(hairCutQuery);
|
||||
}
|
||||
|
||||
// PUT: api/HairCutQueriesApi/5
|
||||
[HttpPut("{id}")]
|
||||
public async Task<IActionResult> PutHairCutQuery([FromRoute] long id, [FromBody] HairCutQuery hairCutQuery)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
if (id != hairCutQuery.Id)
|
||||
{
|
||||
return HttpBadRequest();
|
||||
}
|
||||
|
||||
_context.Entry(hairCutQuery).State = EntityState.Modified;
|
||||
|
||||
try
|
||||
{
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
if (!HairCutQueryExists(id))
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return new HttpStatusCodeResult(StatusCodes.Status204NoContent);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> PostQuery(HairCutQuery hairCutQuery)
|
||||
{
|
||||
var uid = User.GetUserId();
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return new BadRequestObjectResult(ModelState);
|
||||
}
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
_context.HairCutQueries.Add(hairCutQuery);
|
||||
try
|
||||
{
|
||||
await _context.SaveChangesAsync(uid);
|
||||
}
|
||||
catch (DbUpdateException)
|
||||
{
|
||||
if (HairCutQueryExists(hairCutQuery.Id))
|
||||
{
|
||||
return new HttpStatusCodeResult(StatusCodes.Status409Conflict);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return CreatedAtRoute("GetHairCutQuery", new { id = hairCutQuery.Id }, hairCutQuery);
|
||||
|
||||
}
|
||||
|
||||
[HttpPost("createpayment/{id}")]
|
||||
public async Task<IActionResult> CreatePayment(long id)
|
||||
{
|
||||
|
||||
HairCutQuery query = await _context.HairCutQueries.Include(q => q.Client).
|
||||
Include(q => q.Client.PostalAddress).Include(q => q.Prestation).Include(q=>q.Regularisation)
|
||||
.SingleAsync(q => q.Id == id);
|
||||
if (query.PaymentId!=null)
|
||||
return new BadRequestObjectResult(new { error = "An existing payment process already exists" });
|
||||
query.SelectedProfile = _context.BrusherProfile.Single(p => p.UserId == query.PerformerId);
|
||||
SetExpressCheckoutResponseType payment = null;
|
||||
try {
|
||||
payment = Request.CreatePayment("HairCutCommand", query, "sale", _logger);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
_logger.LogError(ex.Message);
|
||||
return new HttpStatusCodeResult(500);
|
||||
}
|
||||
|
||||
if (payment==null) {
|
||||
_logger.LogError("Error doing SetExpressCheckout, aborting.");
|
||||
_logger.LogError(JsonConvert.SerializeObject(Startup.PayPalSettings));
|
||||
return new HttpStatusCodeResult(500);
|
||||
}
|
||||
switch (payment.Ack)
|
||||
{
|
||||
case AckCodeType.SUCCESS:
|
||||
case AckCodeType.SUCCESSWITHWARNING:
|
||||
{
|
||||
var dbinfo = new PayPalPayment
|
||||
{
|
||||
ExecutorId = User.GetUserId(),
|
||||
CreationToken = payment.Token,
|
||||
State = payment.Ack.ToString()
|
||||
};
|
||||
await _context.SaveChangesAsync(User.GetUserId());
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
_logger.LogError(JsonConvert.SerializeObject(payment));
|
||||
return new BadRequestObjectResult(payment);
|
||||
}
|
||||
|
||||
return Json(new { token = payment.Token });
|
||||
}
|
||||
|
||||
[HttpDelete("{id}")]
|
||||
public async Task<IActionResult> DeleteHairCutQuery([FromRoute] long id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
HairCutQuery hairCutQuery = await _context.HairCutQueries.SingleAsync(m => m.Id == id);
|
||||
if (hairCutQuery == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
_context.HairCutQueries.Remove(hairCutQuery);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
return Ok(hairCutQuery);
|
||||
}
|
||||
|
||||
private bool HairCutQueryExists(long id)
|
||||
{
|
||||
return _context.HairCutQueries.Count(e => e.Id == id) > 0;
|
||||
}
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_context.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
}
|
||||
}
|
||||
148
src/Yavsc/ApiControllers/HyperLinkApiController.cs
Normal file
|
|
@ -0,0 +1,148 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNet.Http;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Data.Entity;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Models.Relationship;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[Produces("application/json")]
|
||||
[Route("api/hyperlink")]
|
||||
public class HyperLinkApiController : Controller
|
||||
{
|
||||
private ApplicationDbContext _context;
|
||||
|
||||
public HyperLinkApiController(ApplicationDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
// GET: api/HyperLinkApi
|
||||
[HttpGet]
|
||||
public IEnumerable<HyperLink> GetLinks()
|
||||
{
|
||||
return _context.Links;
|
||||
}
|
||||
|
||||
// GET: api/HyperLinkApi/5
|
||||
[HttpGet("{id}", Name = "GetHyperLink")]
|
||||
public async Task<IActionResult> GetHyperLink([FromRoute] string id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
HyperLink hyperLink = await _context.Links.SingleAsync(m => m.HRef == id);
|
||||
|
||||
if (hyperLink == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
return Ok(hyperLink);
|
||||
}
|
||||
|
||||
// PUT: api/HyperLinkApi/5
|
||||
[HttpPut("{id}")]
|
||||
public async Task<IActionResult> PutHyperLink([FromRoute] string id, [FromBody] HyperLink hyperLink)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
if (id != hyperLink.HRef)
|
||||
{
|
||||
return HttpBadRequest();
|
||||
}
|
||||
|
||||
_context.Entry(hyperLink).State = EntityState.Modified;
|
||||
|
||||
try
|
||||
{
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
if (!HyperLinkExists(id))
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return new HttpStatusCodeResult(StatusCodes.Status204NoContent);
|
||||
}
|
||||
|
||||
// POST: api/HyperLinkApi
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> PostHyperLink([FromBody] HyperLink hyperLink)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
_context.Links.Add(hyperLink);
|
||||
try
|
||||
{
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
catch (DbUpdateException)
|
||||
{
|
||||
if (HyperLinkExists(hyperLink.HRef))
|
||||
{
|
||||
return new HttpStatusCodeResult(StatusCodes.Status409Conflict);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return CreatedAtRoute("GetHyperLink", new { id = hyperLink.HRef }, hyperLink);
|
||||
}
|
||||
|
||||
// DELETE: api/HyperLinkApi/5
|
||||
[HttpDelete("{id}")]
|
||||
public async Task<IActionResult> DeleteHyperLink([FromRoute] string id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
HyperLink hyperLink = await _context.Links.SingleAsync(m => m.HRef == id);
|
||||
if (hyperLink == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
_context.Links.Remove(hyperLink);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
return Ok(hyperLink);
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_context.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
private bool HyperLinkExists(string id)
|
||||
{
|
||||
return _context.Links.Count(e => e.HRef == id) > 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
145
src/Yavsc/ApiControllers/IT/GitRefsApiController.cs
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNet.Authorization;
|
||||
using Microsoft.AspNet.Http;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Data.Entity;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Server.Models.IT.SourceCode;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[Produces("application/json")]
|
||||
[Route("api/GitRefsApi")]
|
||||
[Authorize("AdministratorOnly")]
|
||||
public class GitRefsApiController : Controller
|
||||
{
|
||||
private ApplicationDbContext _context;
|
||||
|
||||
public GitRefsApiController(ApplicationDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
// GET: api/GitRefsApi
|
||||
[HttpGet]
|
||||
public IEnumerable<GitRepositoryReference> GetGitRepositoryReference()
|
||||
{
|
||||
return _context.GitRepositoryReference;
|
||||
}
|
||||
|
||||
// GET: api/GitRefsApi/5
|
||||
[HttpGet("{id}", Name = "GetGitRepositoryReference")]
|
||||
public async Task<IActionResult> GetGitRepositoryReference([FromRoute] long id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
GitRepositoryReference gitRepositoryReference = await _context.GitRepositoryReference.SingleAsync(m => m.Id == id);
|
||||
|
||||
if (gitRepositoryReference == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
return Ok(gitRepositoryReference);
|
||||
}
|
||||
|
||||
// PUT: api/GitRefsApi/5
|
||||
[HttpPut("{id}")]
|
||||
public async Task<IActionResult> PutGitRepositoryReference([FromRoute] long id, [FromBody] GitRepositoryReference gitRepositoryReference)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
_context.Entry(gitRepositoryReference).State = EntityState.Modified;
|
||||
|
||||
try
|
||||
{
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
if (!GitRepositoryReferenceExists(id))
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return new HttpStatusCodeResult(StatusCodes.Status204NoContent);
|
||||
}
|
||||
|
||||
// POST: api/GitRefsApi
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> PostGitRepositoryReference([FromBody] GitRepositoryReference gitRepositoryReference)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
_context.GitRepositoryReference.Add(gitRepositoryReference);
|
||||
try
|
||||
{
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
catch (DbUpdateException)
|
||||
{
|
||||
if (GitRepositoryReferenceExists(gitRepositoryReference.Id))
|
||||
{
|
||||
return new HttpStatusCodeResult(StatusCodes.Status409Conflict);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return CreatedAtRoute("GetGitRepositoryReference", new { id = gitRepositoryReference.Path }, gitRepositoryReference);
|
||||
}
|
||||
|
||||
// DELETE: api/GitRefsApi/5
|
||||
[HttpDelete("{id}")]
|
||||
public async Task<IActionResult> DeleteGitRepositoryReference([FromRoute] long id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
GitRepositoryReference gitRepositoryReference = await _context.GitRepositoryReference.SingleAsync(m => m.Id == id);
|
||||
if (gitRepositoryReference == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
_context.GitRepositoryReference.Remove(gitRepositoryReference);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
return Ok(gitRepositoryReference);
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_context.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
private bool GitRepositoryReferenceExists(long id)
|
||||
{
|
||||
return _context.GitRepositoryReference.Count(e => e.Id == id) > 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
10
src/Yavsc/ApiControllers/MailTemplatingApiController.cs
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
using Microsoft.AspNet.Mvc;
|
||||
|
||||
namespace Yavsc.ApiControllers
|
||||
{
|
||||
[Route("api/mailtemplate")]
|
||||
public class MailTemplatingApiController: Controller
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
153
src/Yavsc/ApiControllers/MailingTemplateApiController.cs
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNet.Http;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Data.Entity;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Server.Models.EMailing;
|
||||
using Microsoft.AspNet.Authorization;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[Produces("application/json")]
|
||||
[Route("api/mailing")]
|
||||
[Authorize("AdministratorOnly")]
|
||||
public class MailingTemplateApiController : Controller
|
||||
{
|
||||
private ApplicationDbContext _context;
|
||||
|
||||
public MailingTemplateApiController(ApplicationDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
// GET: api/MailingTemplateApi
|
||||
[HttpGet]
|
||||
public IEnumerable<MailingTemplate> GetMailingTemplate()
|
||||
{
|
||||
return _context.MailingTemplate;
|
||||
}
|
||||
|
||||
// GET: api/MailingTemplateApi/5
|
||||
[HttpGet("{id}", Name = "GetMailingTemplate")]
|
||||
public async Task<IActionResult> GetMailingTemplate([FromRoute] long id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
MailingTemplate mailingTemplate = await _context.MailingTemplate.SingleAsync(m => m.Id == id);
|
||||
|
||||
if (mailingTemplate == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
return Ok(mailingTemplate);
|
||||
}
|
||||
|
||||
// PUT: api/MailingTemplateApi/5
|
||||
[HttpPut("{id}")]
|
||||
public async Task<IActionResult> PutMailingTemplate([FromRoute] long id, [FromBody] MailingTemplate mailingTemplate)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
if (id != mailingTemplate.Id)
|
||||
{
|
||||
return HttpBadRequest();
|
||||
}
|
||||
|
||||
_context.Entry(mailingTemplate).State = EntityState.Modified;
|
||||
|
||||
try
|
||||
{
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
if (!MailingTemplateExists(id))
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return new HttpStatusCodeResult(StatusCodes.Status204NoContent);
|
||||
}
|
||||
|
||||
// POST: api/MailingTemplateApi
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> PostMailingTemplate([FromBody] MailingTemplate mailingTemplate)
|
||||
{
|
||||
mailingTemplate.ManagerId = User.GetUserId();
|
||||
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
_context.MailingTemplate.Add(mailingTemplate);
|
||||
try
|
||||
{
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
catch (DbUpdateException)
|
||||
{
|
||||
if (MailingTemplateExists(mailingTemplate.Id))
|
||||
{
|
||||
return new HttpStatusCodeResult(StatusCodes.Status409Conflict);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return CreatedAtRoute("GetMailingTemplate", new { id = mailingTemplate.Id }, mailingTemplate);
|
||||
}
|
||||
|
||||
// DELETE: api/MailingTemplateApi/5
|
||||
[HttpDelete("{id}")]
|
||||
public async Task<IActionResult> DeleteMailingTemplate([FromRoute] long id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
MailingTemplate mailingTemplate = await _context.MailingTemplate.SingleAsync(m => m.Id == id);
|
||||
if (mailingTemplate == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
_context.MailingTemplate.Remove(mailingTemplate);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
return Ok(mailingTemplate);
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_context.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
private bool MailingTemplateExists(long id)
|
||||
{
|
||||
return _context.MailingTemplate.Count(e => e.Id == id) > 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
13
src/Yavsc/ApiControllers/Musical/DjProfileApiController.cs
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
namespace Yavsc.ApiControllers
|
||||
{
|
||||
using Models;
|
||||
using Models.Musical.Profiles;
|
||||
|
||||
public class DjProfileApiController : ProfileApiController<DjSettings>
|
||||
{
|
||||
public DjProfileApiController(ApplicationDbContext context) : base(context)
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,147 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNet.Http;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Data.Entity;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Models.Musical;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[Produces("application/json")]
|
||||
[Route("api/museprefs")]
|
||||
public class MusicalPreferencesApiController : Controller
|
||||
{
|
||||
private ApplicationDbContext _context;
|
||||
|
||||
public MusicalPreferencesApiController(ApplicationDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
// GET: api/MusicalPreferencesApi
|
||||
[HttpGet]
|
||||
public IEnumerable<MusicalPreference> GetMusicalPreferences()
|
||||
{
|
||||
return _context.MusicalPreferences;
|
||||
}
|
||||
|
||||
// GET: api/MusicalPreferencesApi/5
|
||||
[HttpGet("{id}", Name = "GetMusicalPreference")]
|
||||
public IActionResult GetMusicalPreference([FromRoute] string id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
MusicalPreference musicalPreference = _context.MusicalPreferences.Single(m => m.OwnerProfileId == id);
|
||||
|
||||
if (musicalPreference == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
return Ok(musicalPreference);
|
||||
}
|
||||
|
||||
// PUT: api/MusicalPreferencesApi/5
|
||||
public IActionResult PutMusicalPreference(string id, [FromBody] MusicalPreference musicalPreference)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
if (id != musicalPreference.OwnerProfileId)
|
||||
{
|
||||
return HttpBadRequest();
|
||||
}
|
||||
|
||||
_context.Entry(musicalPreference).State = EntityState.Modified;
|
||||
|
||||
try
|
||||
{
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
if (!MusicalPreferenceExists(id))
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return new HttpStatusCodeResult(StatusCodes.Status204NoContent);
|
||||
}
|
||||
|
||||
// POST: api/MusicalPreferencesApi
|
||||
[HttpPost]
|
||||
public IActionResult PostMusicalPreference([FromBody] MusicalPreference musicalPreference)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
_context.MusicalPreferences.Add(musicalPreference);
|
||||
try
|
||||
{
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
}
|
||||
catch (DbUpdateException)
|
||||
{
|
||||
if (MusicalPreferenceExists(musicalPreference.OwnerProfileId))
|
||||
{
|
||||
return new HttpStatusCodeResult(StatusCodes.Status409Conflict);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return CreatedAtRoute("GetMusicalPreference", new { id = musicalPreference.OwnerProfileId }, musicalPreference);
|
||||
}
|
||||
|
||||
// DELETE: api/MusicalPreferencesApi/5
|
||||
[HttpDelete("{id}")]
|
||||
public IActionResult DeleteMusicalPreference(string id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
MusicalPreference musicalPreference = _context.MusicalPreferences.Single(m => m.OwnerProfileId == id);
|
||||
if (musicalPreference == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
_context.MusicalPreferences.Remove(musicalPreference);
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
|
||||
return Ok(musicalPreference);
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_context.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
private bool MusicalPreferenceExists(string id)
|
||||
{
|
||||
return _context.MusicalPreferences.Count(e => e.OwnerProfileId == id) > 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,148 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNet.Http;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Data.Entity;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Models.Musical;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[Produces("application/json")]
|
||||
[Route("api/MusicalTendenciesApi")]
|
||||
public class MusicalTendenciesApiController : Controller
|
||||
{
|
||||
private ApplicationDbContext _context;
|
||||
|
||||
public MusicalTendenciesApiController(ApplicationDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
// GET: api/MusicalTendenciesApi
|
||||
[HttpGet]
|
||||
public IEnumerable<MusicalTendency> GetMusicalTendency()
|
||||
{
|
||||
return _context.MusicalTendency;
|
||||
}
|
||||
|
||||
// GET: api/MusicalTendenciesApi/5
|
||||
[HttpGet("{id}", Name = "GetMusicalTendency")]
|
||||
public IActionResult GetMusicalTendency([FromRoute] long id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
MusicalTendency musicalTendency = _context.MusicalTendency.Single(m => m.Id == id);
|
||||
|
||||
if (musicalTendency == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
return Ok(musicalTendency);
|
||||
}
|
||||
|
||||
// PUT: api/MusicalTendenciesApi/5
|
||||
[HttpPut("{id}")]
|
||||
public IActionResult PutMusicalTendency(long id, [FromBody] MusicalTendency musicalTendency)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
if (id != musicalTendency.Id)
|
||||
{
|
||||
return HttpBadRequest();
|
||||
}
|
||||
|
||||
_context.Entry(musicalTendency).State = EntityState.Modified;
|
||||
|
||||
try
|
||||
{
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
if (!MusicalTendencyExists(id))
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return new HttpStatusCodeResult(StatusCodes.Status204NoContent);
|
||||
}
|
||||
|
||||
// POST: api/MusicalTendenciesApi
|
||||
[HttpPost]
|
||||
public IActionResult PostMusicalTendency([FromBody] MusicalTendency musicalTendency)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
_context.MusicalTendency.Add(musicalTendency);
|
||||
try
|
||||
{
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
}
|
||||
catch (DbUpdateException)
|
||||
{
|
||||
if (MusicalTendencyExists(musicalTendency.Id))
|
||||
{
|
||||
return new HttpStatusCodeResult(StatusCodes.Status409Conflict);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return CreatedAtRoute("GetMusicalTendency", new { id = musicalTendency.Id }, musicalTendency);
|
||||
}
|
||||
|
||||
// DELETE: api/MusicalTendenciesApi/5
|
||||
[HttpDelete("{id}")]
|
||||
public IActionResult DeleteMusicalTendency(long id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
MusicalTendency musicalTendency = _context.MusicalTendency.Single(m => m.Id == id);
|
||||
if (musicalTendency == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
_context.MusicalTendency.Remove(musicalTendency);
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
|
||||
return Ok(musicalTendency);
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_context.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
private bool MusicalTendencyExists(long id)
|
||||
{
|
||||
return _context.MusicalTendency.Count(e => e.Id == id) > 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
8
src/Yavsc/ApiControllers/Musical/PodcastController.cs
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
using Microsoft.AspNet.Mvc;
|
||||
|
||||
namespace Yavsc.ApiControllers
|
||||
{
|
||||
public class PodcastController : Controller
|
||||
{
|
||||
}
|
||||
}
|
||||
35
src/Yavsc/ApiControllers/PaymentApiController.cs
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.OptionsModel;
|
||||
using Newtonsoft.Json;
|
||||
using Yavsc.Helpers;
|
||||
using Yavsc.Models;
|
||||
|
||||
namespace Yavsc.ApiControllers
|
||||
{
|
||||
[Route("api/payment")]
|
||||
public class PaymentApiController : Controller
|
||||
{
|
||||
private ApplicationDbContext dbContext;
|
||||
private SiteSettings siteSettings;
|
||||
private readonly ILogger _logger;
|
||||
public PaymentApiController(
|
||||
ApplicationDbContext dbContext,
|
||||
IOptions<SiteSettings> siteSettingsReceiver,
|
||||
ILoggerFactory loggerFactory)
|
||||
{
|
||||
this.dbContext = dbContext;
|
||||
siteSettings = siteSettingsReceiver.Value;
|
||||
_logger = loggerFactory.CreateLogger<PaymentApiController>();
|
||||
}
|
||||
|
||||
public async Task<IActionResult> Info(string paymentId, string token)
|
||||
{
|
||||
var details = await dbContext.GetCheckoutInfo(token);
|
||||
_logger.LogInformation(JsonConvert.SerializeObject(details));
|
||||
return Ok(details);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
66
src/Yavsc/ApiControllers/PerformersApiController.cs
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNet.Authorization;
|
||||
using Microsoft.Data.Entity;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
using Models;
|
||||
using Yavsc.Helpers;
|
||||
using Yavsc.Services;
|
||||
|
||||
[Produces("application/json")]
|
||||
[Route("api/performers")]
|
||||
public class PerformersApiController : Controller
|
||||
{
|
||||
ApplicationDbContext dbContext;
|
||||
private IBillingService billing;
|
||||
|
||||
public PerformersApiController(ApplicationDbContext context, IBillingService billing)
|
||||
{
|
||||
dbContext = context;
|
||||
this.billing = billing;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Lists profiles on an activity code
|
||||
/// </summary>
|
||||
/// <param name="id"></param>
|
||||
/// <returns></returns>
|
||||
[Authorize(Roles="Performer"),HttpGet("{id}")]
|
||||
public IActionResult Get(string id)
|
||||
{
|
||||
var pfr = dbContext.Performers.Include(
|
||||
p=>p.OrganizationAddress
|
||||
).Include(
|
||||
p=>p.Performer
|
||||
).Include(
|
||||
p=>p.Performer.Posts
|
||||
).SingleOrDefault(p=> p.PerformerId == id);
|
||||
if (id==null)
|
||||
{
|
||||
ModelState.AddModelError("id","Specifier un identifiant de prestataire valide");
|
||||
}
|
||||
else {
|
||||
var uid = User.GetUserId();
|
||||
if (!User.IsInRole("Administrator"))
|
||||
if (uid != id) return new ChallengeResult();
|
||||
|
||||
if (!pfr.Active)
|
||||
{
|
||||
ModelState.AddModelError("id","Prestataire désactivé.");
|
||||
}
|
||||
}
|
||||
if (ModelState.IsValid) return Ok(pfr);
|
||||
return new BadRequestObjectResult(ModelState);
|
||||
}
|
||||
|
||||
[HttpGet("doing/{id}"),AllowAnonymous]
|
||||
public IActionResult ListPerformers(string id)
|
||||
{
|
||||
return Ok(dbContext.ListPerformers(billing, id));
|
||||
}
|
||||
}
|
||||
}
|
||||
47
src/Yavsc/ApiControllers/PostRateApiController.cs
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNet.Authorization;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Yavsc.Models;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[Produces("application/json")]
|
||||
[Route("~/api/PostRateApi")]
|
||||
public class PostRateApiController : Controller
|
||||
{
|
||||
private ApplicationDbContext _context;
|
||||
|
||||
public PostRateApiController(ApplicationDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
// GET: api/PostRateApi/5
|
||||
[HttpPut("{id}"),Authorize]
|
||||
public IActionResult PutPostRate([FromRoute] long id, [FromBody] int rate)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
Models.Blog.BlogPost blogpost = _context.Blogspot.Single(x=>x.Id == id);
|
||||
|
||||
if (blogpost == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
var uid = User.GetUserId();
|
||||
if (blogpost.AuthorId!=uid)
|
||||
if (!User.IsInRole(Constants.AdminGroupName))
|
||||
return HttpBadRequest();
|
||||
|
||||
blogpost.Rate = rate;
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
|
||||
return Ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
149
src/Yavsc/ApiControllers/PostTagsApiController.cs
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Microsoft.AspNet.Http;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Data.Entity;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
using System.Security.Claims;
|
||||
using Models;
|
||||
using Yavsc.Models.Blog;
|
||||
|
||||
[Produces("application/json")]
|
||||
[Route("~/api/PostTagsApi")]
|
||||
public class PostTagsApiController : Controller
|
||||
{
|
||||
private ApplicationDbContext _context;
|
||||
|
||||
public PostTagsApiController(ApplicationDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
// GET: api/PostTagsApi
|
||||
[HttpGet]
|
||||
public IEnumerable<BlogTag> GetTagsDomain()
|
||||
{
|
||||
return _context.TagsDomain;
|
||||
}
|
||||
|
||||
// GET: api/PostTagsApi/5
|
||||
[HttpGet("{id}", Name = "GetPostTag")]
|
||||
public IActionResult GetPostTag([FromRoute] long id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
BlogTag postTag = _context.TagsDomain.Single(m => m.PostId == id);
|
||||
|
||||
if (postTag == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
return Ok(postTag);
|
||||
}
|
||||
|
||||
// PUT: api/PostTagsApi/5
|
||||
[HttpPut("{id}")]
|
||||
public IActionResult PutPostTag(long id, [FromBody] BlogTag postTag)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
if (id != postTag.PostId)
|
||||
{
|
||||
return HttpBadRequest();
|
||||
}
|
||||
|
||||
_context.Entry(postTag).State = EntityState.Modified;
|
||||
|
||||
try
|
||||
{
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
if (!PostTagExists(id))
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return new HttpStatusCodeResult(StatusCodes.Status204NoContent);
|
||||
}
|
||||
|
||||
// POST: api/PostTagsApi
|
||||
[HttpPost]
|
||||
public IActionResult PostPostTag([FromBody] BlogTag postTag)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
_context.TagsDomain.Add(postTag);
|
||||
try
|
||||
{
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
}
|
||||
catch (DbUpdateException)
|
||||
{
|
||||
if (PostTagExists(postTag.PostId))
|
||||
{
|
||||
return new HttpStatusCodeResult(StatusCodes.Status409Conflict);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return CreatedAtRoute("GetPostTag", new { id = postTag.PostId }, postTag);
|
||||
}
|
||||
|
||||
// DELETE: api/PostTagsApi/5
|
||||
[HttpDelete("{id}")]
|
||||
public IActionResult DeletePostTag(long id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
BlogTag postTag = _context.TagsDomain.Single(m => m.PostId == id);
|
||||
if (postTag == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
_context.TagsDomain.Remove(postTag);
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
|
||||
return Ok(postTag);
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_context.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
private bool PostTagExists(long id)
|
||||
{
|
||||
return _context.TagsDomain.Count(e => e.PostId == id) > 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
149
src/Yavsc/ApiControllers/ProductApiController.cs
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNet.Authorization;
|
||||
using Microsoft.AspNet.Http;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Data.Entity;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Models.Market;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[Produces("application/json")]
|
||||
[Route("api/ProductApi")]
|
||||
public class ProductApiController : Controller
|
||||
{
|
||||
private ApplicationDbContext _context;
|
||||
|
||||
public ProductApiController(ApplicationDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
// GET: api/ProductApi
|
||||
[HttpGet]
|
||||
public IEnumerable<Product> GetProducts()
|
||||
{
|
||||
return _context.Products;
|
||||
}
|
||||
|
||||
// GET: api/ProductApi/5
|
||||
[HttpGet("{id}", Name = "GetProduct")]
|
||||
public IActionResult GetProduct([FromRoute] long id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
Product product = _context.Products.Single(m => m.Id == id);
|
||||
|
||||
if (product == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
return Ok(product);
|
||||
}
|
||||
|
||||
// PUT: api/ProductApi/5
|
||||
[HttpPut("{id}"),Authorize(Constants.FrontOfficeGroupName)]
|
||||
public IActionResult PutProduct(long id, [FromBody] Product product)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
if (id != product.Id)
|
||||
{
|
||||
return HttpBadRequest();
|
||||
}
|
||||
|
||||
_context.Entry(product).State = EntityState.Modified;
|
||||
|
||||
try
|
||||
{
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
if (!ProductExists(id))
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return new HttpStatusCodeResult(StatusCodes.Status204NoContent);
|
||||
}
|
||||
|
||||
// POST: api/ProductApi
|
||||
[HttpPost,Authorize(Constants.FrontOfficeGroupName)]
|
||||
public IActionResult PostProduct([FromBody] Product product)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
_context.Products.Add(product);
|
||||
try
|
||||
{
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
}
|
||||
catch (DbUpdateException)
|
||||
{
|
||||
if (ProductExists(product.Id))
|
||||
{
|
||||
return new HttpStatusCodeResult(StatusCodes.Status409Conflict);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return CreatedAtRoute("GetProduct", new { id = product.Id }, product);
|
||||
}
|
||||
|
||||
// DELETE: api/ProductApi/5
|
||||
[HttpDelete("{id}"),Authorize(Constants.FrontOfficeGroupName)]
|
||||
public IActionResult DeleteProduct(long id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
Product product = _context.Products.Single(m => m.Id == id);
|
||||
if (product == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
_context.Products.Remove(product);
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
|
||||
return Ok(product);
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_context.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
private bool ProductExists(long id)
|
||||
{
|
||||
return _context.Products.Count(e => e.Id == id) > 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
20
src/Yavsc/ApiControllers/ProfileApiController.cs
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
using Microsoft.AspNet.Mvc;
|
||||
|
||||
namespace Yavsc.ApiControllers
|
||||
{
|
||||
using Models;
|
||||
|
||||
/// <summary>
|
||||
/// Base class for managing performers profiles
|
||||
/// </summary>
|
||||
[Produces("application/json"),Route("api/profile")]
|
||||
public abstract class ProfileApiController<T> : Controller
|
||||
{
|
||||
ApplicationDbContext dbContext;
|
||||
public ProfileApiController(ApplicationDbContext context)
|
||||
{
|
||||
dbContext = context;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
149
src/Yavsc/ApiControllers/ServiceApiController.cs
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNet.Authorization;
|
||||
using Microsoft.AspNet.Http;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Data.Entity;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Models.Market;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[Produces("application/json")]
|
||||
[Route("api/ServiceApi")]
|
||||
public class ServiceApiController : Controller
|
||||
{
|
||||
private ApplicationDbContext _context;
|
||||
|
||||
public ServiceApiController(ApplicationDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
// GET: api/ServiceApi
|
||||
[HttpGet]
|
||||
public IEnumerable<Service> GetServices()
|
||||
{
|
||||
return _context.Services;
|
||||
}
|
||||
|
||||
// GET: api/ServiceApi/5
|
||||
[HttpGet("{id}", Name = "GetService")]
|
||||
public IActionResult GetService([FromRoute] long id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
Service service = _context.Services.Single(m => m.Id == id);
|
||||
|
||||
if (service == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
return Ok(service);
|
||||
}
|
||||
|
||||
// PUT: api/ServiceApi/5
|
||||
[HttpPut("{id}"),Authorize(Constants.FrontOfficeGroupName)]
|
||||
public IActionResult PutService(long id, [FromBody] Service service)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
if (id != service.Id)
|
||||
{
|
||||
return HttpBadRequest();
|
||||
}
|
||||
|
||||
_context.Entry(service).State = EntityState.Modified;
|
||||
|
||||
try
|
||||
{
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
if (!ServiceExists(id))
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return new HttpStatusCodeResult(StatusCodes.Status204NoContent);
|
||||
}
|
||||
|
||||
// POST: api/ServiceApi
|
||||
[HttpPost,Authorize(Constants.FrontOfficeGroupName)]
|
||||
public IActionResult PostService([FromBody] Service service)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
_context.Services.Add(service);
|
||||
try
|
||||
{
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
}
|
||||
catch (DbUpdateException)
|
||||
{
|
||||
if (ServiceExists(service.Id))
|
||||
{
|
||||
return new HttpStatusCodeResult(StatusCodes.Status409Conflict);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return CreatedAtRoute("GetService", new { id = service.Id }, service);
|
||||
}
|
||||
|
||||
// DELETE: api/ServiceApi/5
|
||||
[HttpDelete("{id}"),Authorize(Constants.FrontOfficeGroupName)]
|
||||
public IActionResult DeleteService(long id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
Service service = _context.Services.Single(m => m.Id == id);
|
||||
if (service == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
_context.Services.Remove(service);
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
|
||||
return Ok(service);
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_context.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
private bool ServiceExists(long id)
|
||||
{
|
||||
return _context.Services.Count(e => e.Id == id) > 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
34
src/Yavsc/ApiControllers/Streaming/StreamingApiController.cs
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
|
||||
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Yavsc {
|
||||
|
||||
public class StreamingApiController {
|
||||
|
||||
ILogger _logger;
|
||||
|
||||
public StreamingApiController (LoggerFactory loggerFactory)
|
||||
{
|
||||
_logger = loggerFactory.CreateLogger<StreamingApiController>();
|
||||
_logger.LogInformation
|
||||
("created logger");
|
||||
}
|
||||
|
||||
public async Task<IActionResult> GetStreamingToken()
|
||||
{
|
||||
_logger.LogInformation("Token asked");
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
public async Task<IActionResult> GetLiveStreamingIndex()
|
||||
{
|
||||
_logger.LogInformation("GetLiveStreamingIndex");
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
153
src/Yavsc/ApiControllers/TagsApiController.cs
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Microsoft.AspNet.Http;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Data.Entity;
|
||||
using Yavsc.Models;
|
||||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
using System.Security.Claims;
|
||||
using Models.Relationship;
|
||||
[Produces("application/json")]
|
||||
[Route("api/TagsApi")]
|
||||
public class TagsApiController : Controller
|
||||
{
|
||||
private ApplicationDbContext _context;
|
||||
ILogger _logger;
|
||||
|
||||
public TagsApiController(ApplicationDbContext context,
|
||||
ILoggerFactory loggerFactory)
|
||||
{
|
||||
_context = context;
|
||||
_logger = loggerFactory.CreateLogger<TagsApiController>();
|
||||
}
|
||||
|
||||
// GET: api/TagsApi
|
||||
[HttpGet]
|
||||
public IEnumerable<Tag> GetTag()
|
||||
{
|
||||
return _context.Tags;
|
||||
}
|
||||
|
||||
// GET: api/TagsApi/5
|
||||
[HttpGet("{id}", Name = "GetTag")]
|
||||
public IActionResult GetTag([FromRoute] long id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
Tag tag = _context.Tags.Single(m => m.Id == id);
|
||||
|
||||
if (tag == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
return Ok(tag);
|
||||
}
|
||||
|
||||
// PUT: api/TagsApi/5
|
||||
[HttpPut("{id}")]
|
||||
public IActionResult PutTag(long id, [FromBody] Tag tag)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
if (id != tag.Id)
|
||||
{
|
||||
return HttpBadRequest();
|
||||
}
|
||||
|
||||
_context.Entry(tag).State = EntityState.Modified;
|
||||
|
||||
try
|
||||
{
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
_logger.LogInformation("Tag created");
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
if (!TagExists(id))
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return new HttpStatusCodeResult(StatusCodes.Status204NoContent);
|
||||
}
|
||||
|
||||
// POST: api/TagsApi
|
||||
[HttpPost]
|
||||
public IActionResult PostTag([FromBody] Tag tag)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
_context.Tags.Add(tag);
|
||||
try
|
||||
{
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
}
|
||||
catch (DbUpdateException)
|
||||
{
|
||||
if (TagExists(tag.Id))
|
||||
{
|
||||
return new HttpStatusCodeResult(StatusCodes.Status409Conflict);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
return CreatedAtRoute("GetTag", new { id = tag.Id }, tag);
|
||||
}
|
||||
|
||||
// DELETE: api/TagsApi/5
|
||||
[HttpDelete("{id}")]
|
||||
public IActionResult DeleteTag(long id)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return HttpBadRequest(ModelState);
|
||||
}
|
||||
|
||||
Tag tag = _context.Tags.Single(m => m.Id == id);
|
||||
if (tag == null)
|
||||
{
|
||||
return HttpNotFound();
|
||||
}
|
||||
|
||||
_context.Tags.Remove(tag);
|
||||
_context.SaveChanges(User.GetUserId());
|
||||
|
||||
return Ok(tag);
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_context.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
private bool TagExists(long id)
|
||||
{
|
||||
return _context.Tags.Count(e => e.Id == id) > 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
39
src/Yavsc/ApiControllers/accounting/ProfileApiController.cs
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
using Microsoft.AspNet.Identity;
|
||||
using Microsoft.AspNet.Mvc;
|
||||
using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
using System.Linq;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Abstract.Identity;
|
||||
|
||||
namespace Yavsc.ApiControllers.accounting
|
||||
{
|
||||
[Route("~/api/profile")]
|
||||
public class ProfileApiController: Controller
|
||||
{
|
||||
UserManager<ApplicationUser> _userManager;
|
||||
ApplicationDbContext _dbContext;
|
||||
public ProfileApiController(ApplicationDbContext dbContext, UserManager<ApplicationUser> userManager)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
_userManager = userManager;
|
||||
}
|
||||
|
||||
[HttpGet("{allow}",Name ="setmonthlyemail")]
|
||||
public async Task<object> SetMonthlyEmail(bool allow)
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(User.GetUserId());
|
||||
user.AllowMonthlyEmail = allow;
|
||||
_dbContext.SaveChanges(User.GetUserId());
|
||||
return Ok(new { monthlyEmailPrefSaved = allow });
|
||||
}
|
||||
|
||||
[HttpGet("userhint/{name}")]
|
||||
public UserInfo[] GetUserHint(string name)
|
||||
{
|
||||
return _dbContext.Users.Where(u=>u.UserName.IndexOf(name)>0)
|
||||
.Select(u=>new UserInfo(u.Id, u.UserName, u.Avatar))
|
||||
.Take(10).ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
{"access_token":"ya29.GlvvBZDxTWkcmBPRjURZuGUAazw-2Z3-zDpnuTKZOzMJjITyECpEOS2Bf5KCbWTXXjFC9O03RBexpZUWsRdyitGcKbLtllH3o1ePTsRMSTUfU7UqoTlMh8MQzR7N","token_type":"Bearer","expires_in":3599,"Issued":"2018-07-05T13:38:01.927+02:00","IssuedUtc":"2018-07-05T13:38:01.927+02:00"}
|
||||
|
|
@ -0,0 +1 @@
|
|||
{"access_token":"ya29.GlwOBkSbdjTq29DrVz5sqJPGUj1mWF04gCubQH5C3QSvqiZbnMrIL5DbufC1EnsBw2ECit1V5haDl9EsiQ5BH8YN0N08ecidobZaSMk2L-9su8TzdRPy_JEH5rKTkA","token_type":"Bearer","expires_in":3599,"Issued":"2018-08-05T14:58:33.571+02:00","IssuedUtc":"2018-08-05T14:58:33.571+02:00"}
|
||||
22
src/Yavsc/AuthorizationHandlers/AnnouceEditHandler.cs
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
|
||||
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNet.Authorization;
|
||||
using Yavsc.Interfaces;
|
||||
|
||||
namespace Yavsc.ViewModels.Auth.Handlers
|
||||
{
|
||||
public class AnnouceEditHandler : AuthorizationHandler<EditRequirement, IOwned>
|
||||
{
|
||||
protected override void Handle(AuthorizationContext context, EditRequirement requirement,
|
||||
IOwned resource)
|
||||
{
|
||||
if (context.User.IsInRole(Constants.BlogModeratorGroupName)
|
||||
|| context.User.IsInRole(Constants.AdminGroupName))
|
||||
context.Succeed(requirement);
|
||||
if (resource.OwnerId == context.User.GetUserId())
|
||||
context.Succeed(requirement);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
20
src/Yavsc/AuthorizationHandlers/BillEditHandler.cs
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
using System.Security.Claims;
|
||||
using Microsoft.AspNet.Authorization;
|
||||
|
||||
namespace Yavsc.ViewModels.Auth.Handlers
|
||||
{
|
||||
using Billing;
|
||||
public class BillEditHandler : AuthorizationHandler<EditRequirement, IBillable>
|
||||
{
|
||||
protected override void Handle(AuthorizationContext context, EditRequirement requirement, IBillable resource)
|
||||
{
|
||||
|
||||
if (context.User.IsInRole("FrontOffice"))
|
||||
context.Succeed(requirement);
|
||||
else if (context.User.Identity.IsAuthenticated)
|
||||
if (resource.ClientId == context.User.GetUserId())
|
||||
context.Succeed(requirement);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
22
src/Yavsc/AuthorizationHandlers/BillViewHandlers.cs
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
using System.Security.Claims;
|
||||
using Microsoft.AspNet.Authorization;
|
||||
|
||||
namespace Yavsc.ViewModels.Auth.Handlers
|
||||
{
|
||||
using Billing;
|
||||
|
||||
public class BillViewHandler : AuthorizationHandler<ViewRequirement, IBillable>
|
||||
{
|
||||
protected override void Handle(AuthorizationContext context, ViewRequirement requirement, IBillable resource)
|
||||
{
|
||||
if (context.User.IsInRole("FrontOffice"))
|
||||
context.Succeed(requirement);
|
||||
else if (context.User.Identity.IsAuthenticated)
|
||||
if (resource.ClientId == context.User.GetUserId())
|
||||
context.Succeed(requirement);
|
||||
else if (resource.PerformerId == context.User.GetUserId())
|
||||
context.Succeed(requirement);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
19
src/Yavsc/AuthorizationHandlers/BlogEditHandler.cs
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
using Microsoft.AspNet.Authorization;
|
||||
using System.Security.Claims;
|
||||
using Yavsc.Models.Blog;
|
||||
|
||||
namespace Yavsc.ViewModels.Auth.Handlers
|
||||
{
|
||||
public class BlogEditHandler : AuthorizationHandler<EditRequirement, BlogPost>
|
||||
{
|
||||
protected override void Handle(AuthorizationContext context, EditRequirement requirement, BlogPost resource)
|
||||
{
|
||||
if (context.User.IsInRole(Constants.BlogModeratorGroupName))
|
||||
context.Succeed(requirement);
|
||||
else if (context.User.Identity.IsAuthenticated)
|
||||
if (resource.AuthorId == context.User.GetUserId())
|
||||
context.Succeed(requirement);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
34
src/Yavsc/AuthorizationHandlers/BlogViewHandler.cs
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNet.Authorization;
|
||||
using Yavsc.Models.Blog;
|
||||
|
||||
namespace Yavsc.ViewModels.Auth.Handlers
|
||||
{
|
||||
public class BlogViewHandler : AuthorizationHandler<ViewRequirement, BlogPost>
|
||||
{
|
||||
protected override void Handle(AuthorizationContext context, ViewRequirement requirement, BlogPost resource)
|
||||
{
|
||||
bool ok=false;
|
||||
if (resource.Visible) {
|
||||
if (resource.ACL==null)
|
||||
ok=true;
|
||||
else if (resource.ACL.Count==0) ok=true;
|
||||
else {
|
||||
if (context.User.IsSignedIn()) {
|
||||
var uid = context.User.GetUserId();
|
||||
if (resource.ACL.Any(a=>a.Allowed!=null && a.Allowed.Members.Any(m=>m.MemberId == uid )))
|
||||
ok=true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (ok) context.Succeed(requirement);
|
||||
else {
|
||||
if (context.User.IsInRole(Constants.AdminGroupName) ||
|
||||
context.User.IsInRole(Constants.BlogModeratorGroupName))
|
||||
context.Succeed(requirement);
|
||||
else context.Fail();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
17
src/Yavsc/AuthorizationHandlers/HasBadgeHandler.cs
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
using Microsoft.AspNet.Authorization;
|
||||
|
||||
namespace Yavsc.ViewModels.Auth.Handlers
|
||||
{
|
||||
public class HasBadgeHandler : AuthorizationHandler<PrivateChatEntryRequirement>
|
||||
{
|
||||
protected override void Handle(AuthorizationContext context, PrivateChatEntryRequirement requirement)
|
||||
{
|
||||
if (!context.User.HasClaim(c => c.Type == "BadgeNumber" &&
|
||||
c.Issuer == Startup.Authority))
|
||||
{
|
||||
return;
|
||||
}
|
||||
context.Succeed(requirement);
|
||||
}
|
||||
}
|
||||
}
|
||||
27
src/Yavsc/AuthorizationHandlers/HasTemporaryPassHandler.cs
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
using System;
|
||||
using Microsoft.AspNet.Authorization;
|
||||
|
||||
namespace Yavsc.ViewModels.Auth.Handlers
|
||||
{
|
||||
public class HasTemporaryPassHandler : AuthorizationHandler<PrivateChatEntryRequirement>
|
||||
{
|
||||
protected override void Handle(AuthorizationContext context, PrivateChatEntryRequirement requirement)
|
||||
{
|
||||
if (!context.User.HasClaim(c => c.Type == "TemporaryBadgeExpiry" &&
|
||||
c.Issuer == Startup.Authority))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var temporaryBadgeExpiry =
|
||||
Convert.ToDateTime(context.User.FindFirst(
|
||||
c => c.Type == "TemporaryBadgeExpiry" &&
|
||||
c.Issuer == Startup.Authority).Value);
|
||||
|
||||
if (temporaryBadgeExpiry > DateTime.Now)
|
||||
{
|
||||
context.Succeed(requirement);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
18
src/Yavsc/AuthorizationHandlers/ManageGitHookHandler.cs
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
using Microsoft.AspNet.Authorization;
|
||||
using Yavsc.Server.Models.IT.SourceCode;
|
||||
using Yavsc.ViewModels.Auth;
|
||||
|
||||
namespace Yavsc.AuthorizationHandlers
|
||||
{
|
||||
public class ManageGitHookHandler: AuthorizationHandler<EditRequirement, GitRepositoryReference>
|
||||
{
|
||||
protected override void Handle(AuthorizationContext context, EditRequirement requirement, GitRepositoryReference resource)
|
||||
{
|
||||
if (context.User.IsInRole("FrontOffice"))
|
||||
context.Succeed(requirement);
|
||||
else if (context.User.Identity.IsAuthenticated)
|
||||
context.Succeed(requirement);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
22
src/Yavsc/AuthorizationHandlers/PostUserFileHandler.cs
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
using System.Security.Claims;
|
||||
using Microsoft.AspNet.Authorization;
|
||||
using Yavsc.ViewModel.Auth;
|
||||
|
||||
namespace Yavsc.ViewModels.Auth.Handlers
|
||||
{
|
||||
public class PostUserFileHandler : AuthorizationHandler<EditRequirement, FileSpotInfo>
|
||||
{
|
||||
protected override void Handle(AuthorizationContext context, EditRequirement requirement, FileSpotInfo resource)
|
||||
{
|
||||
if (context.User.IsInRole(Constants.BlogModeratorGroupName)
|
||||
|| context.User.IsInRole(Constants.AdminGroupName))
|
||||
context.Succeed(requirement);
|
||||
if (!context.User.Identity.IsAuthenticated)
|
||||
context.Fail();
|
||||
if (resource.AuthorId == context.User.GetUserId())
|
||||
context.Succeed(requirement);
|
||||
else context.Fail();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
18
src/Yavsc/AuthorizationHandlers/ViewFileHandler.cs
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
using Microsoft.AspNet.Authorization;
|
||||
|
||||
namespace Yavsc.ViewModels.Auth.Handlers
|
||||
{
|
||||
public class ViewFileHandler : AuthorizationHandler<ViewRequirement, ViewFileContext>
|
||||
{
|
||||
protected override void Handle(AuthorizationContext context, ViewRequirement requirement, ViewFileContext fileContext)
|
||||
{
|
||||
// TODO file access rules
|
||||
if (fileContext.Path.StartsWith("/pub/"))
|
||||
context.Succeed(requirement);
|
||||
else {
|
||||
// TODO use "/blog/{num}/" path to link to blog access list
|
||||
context.Succeed(requirement);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
47
src/Yavsc/AuthorizationServer/GoogleExtensions.cs
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
|
||||
using System;
|
||||
using Microsoft.AspNet.Builder;
|
||||
|
||||
namespace Yavsc.Auth
|
||||
{
|
||||
/// <summary>
|
||||
/// Extension methods to add Google authentication capabilities to an HTTP application pipeline.
|
||||
/// </summary>
|
||||
public static class GoogleAppBuilderExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Adds the <see cref="GoogleMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables Google authentication capabilities.
|
||||
/// </summary>
|
||||
/// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param>
|
||||
/// <returns>A reference to this instance after the operation has completed.</returns>
|
||||
public static IApplicationBuilder UseGoogleAuthentication(this IApplicationBuilder app)
|
||||
{
|
||||
if (app == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(app));
|
||||
}
|
||||
|
||||
return app.UseMiddleware<GoogleMiddleware>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the <see cref="GoogleMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables Google authentication capabilities.
|
||||
/// </summary>
|
||||
/// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param>
|
||||
/// <param name="options">A <see cref="YavscGoogleOptions"/> that specifies options for the middleware.</param>
|
||||
/// <returns>A reference to this instance after the operation has completed.</returns>
|
||||
public static IApplicationBuilder UseGoogleAuthentication(this IApplicationBuilder app, YavscGoogleOptions options)
|
||||
{
|
||||
if (app == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(app));
|
||||
}
|
||||
if (options == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(options));
|
||||
}
|
||||
|
||||
return app.UseMiddleware<GoogleMiddleware>(options);
|
||||
}
|
||||
}
|
||||
}
|
||||
139
src/Yavsc/AuthorizationServer/GoogleHandler.cs
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNet.Authentication;
|
||||
using Microsoft.AspNet.Authentication.OAuth;
|
||||
using Microsoft.AspNet.Http.Authentication;
|
||||
using Microsoft.AspNet.WebUtilities;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Yavsc.Auth
|
||||
{
|
||||
internal class GoogleHandler : OAuthHandler<YavscGoogleOptions>
|
||||
{
|
||||
private ILogger _logger;
|
||||
public GoogleHandler(HttpClient httpClient,ILogger logger)
|
||||
: base(httpClient)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
protected override async Task<AuthenticationTicket> CreateTicketAsync(ClaimsIdentity identity,
|
||||
AuthenticationProperties properties, OAuthTokenResponse tokens
|
||||
)
|
||||
{
|
||||
_logger.LogInformation("Getting user info from Google ...");
|
||||
// Get the Google user
|
||||
var request = new HttpRequestMessage(HttpMethod.Get, Options.UserInformationEndpoint);
|
||||
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokens.AccessToken);
|
||||
|
||||
var response = await Backchannel.SendAsync(request, Context.RequestAborted);
|
||||
response.EnsureSuccessStatusCode();
|
||||
|
||||
var payload = JObject.Parse(await response.Content.ReadAsStringAsync());
|
||||
|
||||
var identifier = GoogleHelper.GetId(payload);
|
||||
|
||||
|
||||
var ticket = new AuthenticationTicket(new ClaimsPrincipal(identity), properties, Options.AuthenticationScheme);
|
||||
var context = new GoogleOAuthCreatingTicketContext(Context, Options, Backchannel, tokens, ticket, identifier);
|
||||
|
||||
if (!string.IsNullOrEmpty(identifier))
|
||||
{
|
||||
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, identifier, ClaimValueTypes.String, Options.ClaimsIssuer));
|
||||
}
|
||||
|
||||
var givenName = GoogleHelper.GetGivenName(payload);
|
||||
if (!string.IsNullOrEmpty(givenName))
|
||||
{
|
||||
identity.AddClaim(new Claim(ClaimTypes.GivenName, givenName, ClaimValueTypes.String, Options.ClaimsIssuer));
|
||||
}
|
||||
|
||||
var familyName = GoogleHelper.GetFamilyName(payload);
|
||||
if (!string.IsNullOrEmpty(familyName))
|
||||
{
|
||||
identity.AddClaim(new Claim(ClaimTypes.Surname, familyName, ClaimValueTypes.String, Options.ClaimsIssuer));
|
||||
}
|
||||
|
||||
var name = GoogleHelper.GetName(payload);
|
||||
if (!string.IsNullOrEmpty(name))
|
||||
{
|
||||
identity.AddClaim(new Claim(ClaimTypes.Name, name, ClaimValueTypes.String, Options.ClaimsIssuer));
|
||||
}
|
||||
|
||||
var email = GoogleHelper.GetEmail(payload);
|
||||
if (!string.IsNullOrEmpty(email))
|
||||
{
|
||||
identity.AddClaim(new Claim(ClaimTypes.Email, email, ClaimValueTypes.String, Options.ClaimsIssuer));
|
||||
}
|
||||
|
||||
var profile = GoogleHelper.GetProfile(payload);
|
||||
if (!string.IsNullOrEmpty(profile))
|
||||
{
|
||||
identity.AddClaim(new Claim("urn:google:profile", profile, ClaimValueTypes.String, Options.ClaimsIssuer));
|
||||
}
|
||||
|
||||
await Options.Events.CreatingTicket(context);
|
||||
|
||||
return ticket;
|
||||
}
|
||||
protected override Task<OAuthTokenResponse> ExchangeCodeAsync(string code, string ruri)
|
||||
{
|
||||
var redirectUri = $"https://{Startup.Authority}{Options.CallbackPath}";
|
||||
return base.ExchangeCodeAsync(code,redirectUri);
|
||||
}
|
||||
|
||||
// TODO: Abstract this properties override pattern into the base class?
|
||||
protected override string BuildChallengeUrl(AuthenticationProperties properties, string redirectUri)
|
||||
{
|
||||
|
||||
var scope = FormatScope();
|
||||
var queryStrings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
queryStrings.Add("response_type", "code");
|
||||
queryStrings.Add("client_id", Options.ClientId);
|
||||
// this runtime may not known this value,
|
||||
// it should be get from config,
|
||||
// And always be using a secure sheme ... since Google won't support anymore insecure ones.
|
||||
_logger.LogInformation ($"Redirect uri was : {redirectUri}");
|
||||
|
||||
redirectUri = $"https://{Startup.Authority}{Options.CallbackPath}";
|
||||
queryStrings.Add("redirect_uri", redirectUri);
|
||||
|
||||
_logger.LogInformation ($"Using redirect uri {redirectUri}");
|
||||
|
||||
AddQueryString(queryStrings, properties, "scope", scope);
|
||||
|
||||
AddQueryString(queryStrings, properties, "access_type", Options.AccessType);
|
||||
AddQueryString(queryStrings, properties, "approval_prompt");
|
||||
AddQueryString(queryStrings, properties, "login_hint");
|
||||
|
||||
var state = Options.StateDataFormat.Protect(properties);
|
||||
queryStrings.Add("state", state);
|
||||
|
||||
var authorizationEndpoint = QueryHelpers.AddQueryString(Options.AuthorizationEndpoint, queryStrings);
|
||||
return authorizationEndpoint;
|
||||
}
|
||||
|
||||
|
||||
|
||||
private static void AddQueryString(IDictionary<string, string> queryStrings, AuthenticationProperties properties,
|
||||
string name, string defaultValue = null)
|
||||
{
|
||||
string value;
|
||||
if (!properties.Items.TryGetValue(name, out value))
|
||||
{
|
||||
value = defaultValue;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Remove the parameter from AuthenticationProperties so it won't be serialized to state parameter
|
||||
properties.Items.Remove(name);
|
||||
}
|
||||
queryStrings[name] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
144
src/Yavsc/AuthorizationServer/GoogleHelper.cs
Normal file
|
|
@ -0,0 +1,144 @@
|
|||
|
||||
|
||||
using System;
|
||||
using Newtonsoft.Json.Linq;
|
||||
/// <summary>
|
||||
/// Contains static methods that allow to extract user's information from a <see cref="JObject"/>
|
||||
/// instance retrieved from Google after a successful authentication process.
|
||||
/// </summary>
|
||||
public static class GoogleHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the Google user ID.
|
||||
/// </summary>
|
||||
public static string GetId(JObject user)
|
||||
{
|
||||
if (user == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(user));
|
||||
}
|
||||
|
||||
return user.Value<string>("id");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the user's name.
|
||||
/// </summary>
|
||||
public static string GetName(JObject user)
|
||||
{
|
||||
if (user == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(user));
|
||||
}
|
||||
|
||||
return user.Value<string>("displayName");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the user's given name.
|
||||
/// </summary>
|
||||
public static string GetGivenName(JObject user)
|
||||
{
|
||||
if (user == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(user));
|
||||
}
|
||||
|
||||
return TryGetValue(user, "name", "givenName");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the user's family name.
|
||||
/// </summary>
|
||||
public static string GetFamilyName(JObject user)
|
||||
{
|
||||
if (user == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(user));
|
||||
}
|
||||
|
||||
return TryGetValue(user, "name", "familyName");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the user's profile link.
|
||||
/// </summary>
|
||||
public static string GetProfile(JObject user)
|
||||
{
|
||||
if (user == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(user));
|
||||
}
|
||||
|
||||
return user.Value<string>("url");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the user's email.
|
||||
/// </summary>
|
||||
public static string GetEmail(JObject user)
|
||||
{
|
||||
if (user == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(user));
|
||||
}
|
||||
|
||||
return TryGetFirstValue(user, "emails", "value");
|
||||
}
|
||||
|
||||
// Get the given subProperty from a property.
|
||||
private static string TryGetValue(JObject user, string propertyName, string subProperty)
|
||||
{
|
||||
JToken value;
|
||||
if (user.TryGetValue(propertyName, out value))
|
||||
{
|
||||
var subObject = JObject.Parse(value.ToString());
|
||||
if (subObject != null && subObject.TryGetValue(subProperty, out value))
|
||||
{
|
||||
return value.ToString();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
#if GoogleApisAuthOAuth2
|
||||
public static ServiceAccountCredential GetGoogleApiCredentials (string[] scopes)
|
||||
{
|
||||
String serviceAccountEmail = "SERVICE_ACCOUNT_EMAIL_HERE";
|
||||
|
||||
string private_key = Startup.GoogleSettings.Account.private_key;
|
||||
|
||||
string secret = Startup.GoogleSettings.ClientSecret;
|
||||
|
||||
|
||||
var certificate = new X509Certificate2(@"key.p12", secret, X509KeyStorageFlags.Exportable);
|
||||
|
||||
return new ServiceAccountCredential(
|
||||
new ServiceAccountCredential.Initializer(serviceAccountEmail)
|
||||
{
|
||||
Scopes = scopes
|
||||
}.FromCertificate(certificate));
|
||||
}
|
||||
#endif
|
||||
// Get the given subProperty from a list property.
|
||||
private static string TryGetFirstValue(JObject user, string propertyName, string subProperty)
|
||||
{
|
||||
JToken value;
|
||||
if (user.TryGetValue(propertyName, out value))
|
||||
{
|
||||
var array = JArray.Parse(value.ToString());
|
||||
if (array != null && array.Count > 0)
|
||||
{
|
||||
var subObject = JObject.Parse(array.First.ToString());
|
||||
if (subObject != null)
|
||||
{
|
||||
if (subObject.TryGetValue(subProperty, out value))
|
||||
{
|
||||
return value.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
80
src/Yavsc/AuthorizationServer/GoogleMiddleWare.cs
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
// Copyright (c) .NET Foundation. All rights reserved.
|
||||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
|
||||
|
||||
using System;
|
||||
using Microsoft.AspNet.Authentication;
|
||||
using Microsoft.AspNet.Authentication.OAuth;
|
||||
using Microsoft.AspNet.Builder;
|
||||
using Microsoft.AspNet.DataProtection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.OptionsModel;
|
||||
using Microsoft.Extensions.WebEncoders;
|
||||
namespace Yavsc.Auth
|
||||
{
|
||||
/// <summary>
|
||||
/// An ASP.NET Core middleware for authenticating users using Google OAuth 2.0.
|
||||
/// </summary>
|
||||
public class GoogleMiddleware : OAuthMiddleware<YavscGoogleOptions>
|
||||
{
|
||||
private RequestDelegate _next;
|
||||
private ILogger _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new <see cref="GoogleMiddleware"/>.
|
||||
/// </summary>
|
||||
/// <param name="next">The next middleware in the HTTP pipeline to invoke.</param>
|
||||
/// <param name="dataProtectionProvider"></param>
|
||||
/// <param name="loggerFactory"></param>
|
||||
/// <param name="encoder"></param>
|
||||
/// <param name="sharedOptions"></param>
|
||||
/// <param name="options">Configuration options for the middleware.</param>
|
||||
public GoogleMiddleware(
|
||||
RequestDelegate next,
|
||||
IDataProtectionProvider dataProtectionProvider,
|
||||
ILoggerFactory loggerFactory,
|
||||
UrlEncoder encoder,
|
||||
IOptions<SharedAuthenticationOptions> sharedOptions,
|
||||
YavscGoogleOptions options)
|
||||
: base(next, dataProtectionProvider, loggerFactory, encoder, sharedOptions, options)
|
||||
{
|
||||
if (next == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(next));
|
||||
}
|
||||
_next = next;
|
||||
|
||||
if (dataProtectionProvider == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(dataProtectionProvider));
|
||||
}
|
||||
|
||||
if (loggerFactory == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(loggerFactory));
|
||||
}
|
||||
_logger = loggerFactory.CreateLogger<GoogleMiddleware>();
|
||||
|
||||
if (encoder == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(encoder));
|
||||
}
|
||||
|
||||
if (sharedOptions == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(sharedOptions));
|
||||
}
|
||||
|
||||
if (options == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(options));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
protected override AuthenticationHandler<YavscGoogleOptions> CreateHandler()
|
||||
{
|
||||
return new GoogleHandler(Backchannel,_logger);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
27
src/Yavsc/AuthorizationServer/GoogleOAuthCreatingTicket.cs
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
using System.Net.Http;
|
||||
using Microsoft.AspNet.Authentication;
|
||||
using Microsoft.AspNet.Authentication.OAuth;
|
||||
using Microsoft.AspNet.Http;
|
||||
|
||||
namespace Yavsc.Auth {
|
||||
|
||||
|
||||
public class GoogleOAuthCreatingTicketContext : OAuthCreatingTicketContext {
|
||||
public GoogleOAuthCreatingTicketContext(HttpContext context, OAuthOptions options,
|
||||
HttpClient backchannel, OAuthTokenResponse tokens, AuthenticationTicket ticket, string googleUserId )
|
||||
: base( context, options, backchannel, tokens )
|
||||
{
|
||||
_ticket = ticket;
|
||||
_googleUserId = googleUserId;
|
||||
Principal = ticket.Principal;
|
||||
}
|
||||
AuthenticationTicket _ticket;
|
||||
string _googleUserId;
|
||||
|
||||
public AuthenticationTicket Ticket { get { return _ticket; } }
|
||||
|
||||
public string GoogleUserId { get { return _googleUserId; } }
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
46
src/Yavsc/AuthorizationServer/GoogleOptions.cs
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
using Microsoft.AspNet.Authentication.OAuth;
|
||||
using Microsoft.AspNet.Http;
|
||||
|
||||
namespace Yavsc.Auth
|
||||
{
|
||||
public static class YavscGoogleDefaults
|
||||
{
|
||||
public const string AuthenticationScheme = "Google";
|
||||
|
||||
public static readonly string AuthorizationEndpoint = "https://accounts.google.com/o/oauth2/auth";
|
||||
|
||||
public static readonly string TokenEndpoint = "https://www.googleapis.com/oauth2/v3/token";
|
||||
|
||||
public static readonly string UserInformationEndpoint = "https://www.googleapis.com/plus/v1/people/me";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configuration options for <see cref="GoogleMiddleware"/>.
|
||||
/// </summary>
|
||||
public class YavscGoogleOptions : OAuthOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new <see cref="YavscGoogleOptions"/>.
|
||||
/// </summary>
|
||||
public YavscGoogleOptions()
|
||||
{
|
||||
AuthenticationScheme = YavscGoogleDefaults.AuthenticationScheme;
|
||||
DisplayName = AuthenticationScheme;
|
||||
CallbackPath = new PathString("/signin-google");
|
||||
AuthorizationEndpoint = YavscGoogleDefaults.AuthorizationEndpoint;
|
||||
TokenEndpoint = YavscGoogleDefaults.TokenEndpoint;
|
||||
UserInformationEndpoint = YavscGoogleDefaults.UserInformationEndpoint;
|
||||
Scope.Add("openid");
|
||||
Scope.Add("profile");
|
||||
Scope.Add("email");
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// access_type. Set to 'offline' to request a refresh token.
|
||||
/// </summary>
|
||||
public string AccessType { get; set; }
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
42
src/Yavsc/AuthorizationServer/MonoJwtSecurityTokenHandler.cs
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
|
||||
|
||||
|
||||
using System;
|
||||
using System.IdentityModel.Tokens;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace Yavsc.Auth
|
||||
{
|
||||
|
||||
public class MonoJwtSecurityTokenHandler : JwtSecurityTokenHandler
|
||||
{
|
||||
|
||||
MonoDataProtectionProvider protectionProvider;
|
||||
public MonoJwtSecurityTokenHandler(MonoDataProtectionProvider prpro)
|
||||
{
|
||||
protectionProvider = prpro;
|
||||
}
|
||||
public override JwtSecurityToken CreateToken(
|
||||
string issuer,
|
||||
string audience, ClaimsIdentity subject,
|
||||
DateTime? notBefore, DateTime? expires, DateTime? issuedAt,
|
||||
SigningCredentials signingCredentials
|
||||
)
|
||||
{
|
||||
SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
|
||||
{
|
||||
Audience = audience,
|
||||
Claims = subject.Claims,
|
||||
Expires = expires,
|
||||
IssuedAt = issuedAt,
|
||||
Issuer = issuer,
|
||||
NotBefore = notBefore,
|
||||
SigningCredentials = signingCredentials
|
||||
};
|
||||
var token = base.CreateToken(tokenDescriptor);
|
||||
return token as JwtSecurityToken;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
101
src/Yavsc/AuthorizationServer/RSAKeyUtils.cs
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace Yavsc
|
||||
{
|
||||
public class RSAKeyUtils
|
||||
{
|
||||
public static RSAParameters GetRandomKey()
|
||||
{
|
||||
using (var rsa = new RSACryptoServiceProvider(2048))
|
||||
{
|
||||
try
|
||||
{
|
||||
return rsa.ExportParameters(true);
|
||||
}
|
||||
finally
|
||||
{
|
||||
rsa.PersistKeyInCsp = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static RSAParameters GenerateKeyAndSave(string file)
|
||||
{
|
||||
var p = GetRandomKey();
|
||||
RSAParametersWithPrivate t = new RSAParametersWithPrivate();
|
||||
t.SetParameters(p);
|
||||
File.WriteAllText(file, JsonConvert.SerializeObject(t));
|
||||
return p;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This expects a file in the format:
|
||||
/// {
|
||||
/// "Modulus": "z7eXmrs9z3Xm7VXwYIdziDYzXGfi3XQiozIRa58m3ApeLVDcsDeq6Iv8C5zJ2DHydDyc0x6o5dtTRIb23r5/ZRj4I/UwbgrwMk5iHA0bVsXVPBDSWsrVcPDGafr6YbUNQnNWIF8xOqgpeTwxrqGiCJMUjuKyUx01PBzpBxjpnQ++Ryz6Y7MLqKHxBkDiOw5wk9cxO8/IMspSNJJosOtRXFTR74+bj+pvNBa8IJ+5Jf/UfJEEjk+qC+pohCAryRk0ziXcPdxXEv5KGT4zf3LdtHy1YwsaGLnTb62vgbdqqCJaVyHWOoXsDTQBLjxNl9o9CzP6CrfBGK6JV8pA/xfQlw==",
|
||||
/// "Exponent": "AQAB",
|
||||
/// "P": "+VsETS2exORYlg2CxaRMzyG60dTfHSuv0CsfmO3PFv8mcYxglGa6bUV5VGtB6Pd1HdtV/iau1WR/hYXQphCP99Pu803NZvFvVi34alTFbh0LMfZ+2iQ9toGzVfO8Qdbj7go4TWoHNzCpG4UCx/9wicVIWJsNzkppSEcXYigADMM=",
|
||||
/// "Q": "1UCJ2WAHasiCdwJtV2Ep0VCK3Z4rVFLWg3q1v5OoOU1CkX5/QAcrr6bX6zOdHR1bDCPsH1n1E9cCMvwakgi9M4Ch0dYF5CxDKtlx+IGsZJL0gB6HhcEsHat+yXUtOAlS4YB82G1hZqiDw+Q0O8LGyu/gLDPB+bn0HmbkUC2kP50=",
|
||||
/// "DP": "CBqvLxr2eAu73VSfFXFblbfQ7JTwk3AiDK/6HOxNuL+eLj6TvP8BvB9v7BB4WewBAHFqgBIdyI21n09UErGjHDjlIT88F8ZtCe4AjuQmboe/H2aVhN18q/vXKkn7qmAjlE78uXdiuKZ6OIzAJGPm8nNZAJg5gKTmexTka6pFJiU=",
|
||||
/// "DQ": "ND6zhwX3yzmEfROjJh0v2ZAZ9WGiy+3fkCaoEF9kf2VmQa70DgOzuDzv+TeT7mYawEasuqGXYVzztPn+qHhrogqJmpcMqnINopnTSka6rYkzTZAtM5+35yz0yvZiNbBTFdwcuglSK4xte7iU828stNs/2JR1mXDtVeVvWhVUgCE=",
|
||||
/// "InverseQ": "Heo0BHv685rvWreFcI5MXSy3AN0Zs0YbwAYtZZd1K/OzFdYVdOnqw+Dg3wGU9yFD7h4icJFwZUBGOZ0ww/gZX/5ZgJK35/YY/DeV+qfZmywKauUzC6+DPsrDdW1uf1eAety6/huRZTduBFTwIOlPdZ+PY49j6S38DjPFNImn0cU=",
|
||||
/// "D": "IvjMI5cGzxkQqkDf2cC0aOiHOTWccqCM/GD/odkH1+A+/u4wWdLliYWYB/R731R5d6yE0t7EnP6SRGVcxx/XnxPXI2ayorRgwHeF+ScTxUZFonlKkVK5IOzI2ysQYMb01o1IoOamCTQq12iVDMvV1g+9VFlCoM+4GMjdSv6cxn6ELabuD4nWt8tCskPjECThO+WdrknbUTppb2rRgMvNKfsPuF0H7+g+WisbzVS+UVRvJe3U5O5X5j7Z82Uq6hw2NCwv2YhQZRo/XisFZI7yZe0OU2JkXyNG3NCk8CgsM9yqX8Sk5esXMZdJzjwXtEpbR7FiKZXiz9LhPSmzxz/VsQ=="
|
||||
/// }
|
||||
///
|
||||
/// Generate
|
||||
/// </summary>
|
||||
/// <param name="file"></param>
|
||||
/// <returns></returns>
|
||||
public static RSAParameters GetKeyParameters(string file)
|
||||
{
|
||||
if (!File.Exists(file)) throw new FileNotFoundException("Check configuration - cannot find auth key file: " + file);
|
||||
var keyParams = JsonConvert.DeserializeObject<RSAParametersWithPrivate>(File.ReadAllText(file));
|
||||
return keyParams.ToRSAParameters();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Util class to allow restoring RSA parameters from JSON as the normal
|
||||
/// RSA parameters class won't restore private key info.
|
||||
/// </summary>
|
||||
private class RSAParametersWithPrivate
|
||||
{
|
||||
public byte[] D { get; set; }
|
||||
public byte[] DP { get; set; }
|
||||
public byte[] DQ { get; set; }
|
||||
public byte[] Exponent { get; set; }
|
||||
public byte[] InverseQ { get; set; }
|
||||
public byte[] Modulus { get; set; }
|
||||
public byte[] P { get; set; }
|
||||
public byte[] Q { get; set; }
|
||||
|
||||
public void SetParameters(RSAParameters p)
|
||||
{
|
||||
D = p.D;
|
||||
DP = p.DP;
|
||||
DQ = p.DQ;
|
||||
Exponent = p.Exponent;
|
||||
InverseQ = p.InverseQ;
|
||||
Modulus = p.Modulus;
|
||||
P = p.P;
|
||||
Q = p.Q;
|
||||
}
|
||||
public RSAParameters ToRSAParameters()
|
||||
{
|
||||
return new RSAParameters()
|
||||
{
|
||||
D = this.D,
|
||||
DP = this.DP,
|
||||
DQ = this.DQ,
|
||||
Exponent = this.Exponent,
|
||||
InverseQ = this.InverseQ,
|
||||
Modulus = this.Modulus,
|
||||
P = this.P,
|
||||
Q = this.Q
|
||||
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
57
src/Yavsc/AuthorizationServer/RequiredScopesMiddleware.cs
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
using Microsoft.AspNet.Builder;
|
||||
using Microsoft.AspNet.Http;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Api
|
||||
{
|
||||
public class RequiredScopesMiddleware
|
||||
{
|
||||
private readonly RequestDelegate _next;
|
||||
private readonly IEnumerable<string> _requiredScopes;
|
||||
|
||||
public RequiredScopesMiddleware(RequestDelegate next, IList<string> requiredScopes)
|
||||
{
|
||||
_next = next;
|
||||
_requiredScopes = requiredScopes;
|
||||
}
|
||||
|
||||
public async Task Invoke(HttpContext context)
|
||||
{
|
||||
if (context.User.Identity.IsAuthenticated)
|
||||
{
|
||||
if (!ScopePresent(context.User))
|
||||
{
|
||||
context.Response.OnCompleted(Send403, context);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
await _next(context);
|
||||
}
|
||||
|
||||
private bool ScopePresent(ClaimsPrincipal principal)
|
||||
{
|
||||
foreach (var scope in principal.FindAll("scope"))
|
||||
{
|
||||
if (_requiredScopes.Contains(scope.Value))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private Task Send403(object contextObject)
|
||||
{
|
||||
var context = contextObject as HttpContext;
|
||||
context.Response.StatusCode = 403;
|
||||
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
26
src/Yavsc/AuthorizationServer/TokenAuthOptions.cs
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
using System;
|
||||
using System.IdentityModel.Tokens;
|
||||
|
||||
namespace Yavsc
|
||||
{
|
||||
[Obsolete("Use OAuth2AppSettings instead")]
|
||||
public class TokenAuthOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Public's identification
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public string Audience { get; set; }
|
||||
/// <summary>
|
||||
/// Identity authority
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public string Issuer { get; set; }
|
||||
/// <summary>
|
||||
/// Signin key and signature algotythm
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public SigningCredentials SigningCredentials { get; set; }
|
||||
public int ExpiresIn { get; set; }
|
||||
}
|
||||
}
|
||||
43
src/Yavsc/AuthorizationServer/UserTokenProvider.cs
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNet.DataProtection;
|
||||
using Microsoft.AspNet.Identity;
|
||||
using Yavsc.Models;
|
||||
|
||||
namespace Yavsc.Auth {
|
||||
|
||||
public class UserTokenProvider : Microsoft.AspNet.Identity.IUserTokenProvider<ApplicationUser>
|
||||
{
|
||||
private MonoDataProtector protector=null;
|
||||
public MonoDataProtector Protector {
|
||||
get { return protector; }
|
||||
}
|
||||
|
||||
public Task<bool> CanGenerateTwoFactorTokenAsync(UserManager<ApplicationUser> manager, ApplicationUser user)
|
||||
{
|
||||
return Task.FromResult(true);
|
||||
}
|
||||
|
||||
public Task<string> GenerateAsync(string purpose, UserManager<ApplicationUser> manager, ApplicationUser user)
|
||||
{
|
||||
if ( user==null ) throw new InvalidOperationException("no user");
|
||||
var por = new MonoDataProtector(Constants.ApplicationName,new string[] { purpose } );
|
||||
|
||||
return Task.FromResult(por.Protect(UserStamp(user)));
|
||||
}
|
||||
|
||||
public Task<bool> ValidateAsync(string purpose, string token, UserManager<ApplicationUser> manager, ApplicationUser user)
|
||||
{
|
||||
var por = new MonoDataProtector(Constants.ApplicationName,new string[] { purpose } );
|
||||
var userStamp = por.Unprotect(token);
|
||||
Console.WriteLine ("Unprotected: "+userStamp);
|
||||
string [] values = userStamp.Split(';');
|
||||
return Task.FromResult ( user.Id == values[0] && user.Email == values[1] && user.UserName == values[2]);
|
||||
}
|
||||
|
||||
public static string UserStamp(ApplicationUser user) {
|
||||
return $"{user.Id};{user.Email};{user.UserName}";
|
||||
}
|
||||
}
|
||||
}
|
||||
23
src/Yavsc/AuthorizationServer/XmlEncryptor.cs
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
|
||||
|
||||
|
||||
using System;
|
||||
using System.Xml.Linq;
|
||||
using Microsoft.AspNet.DataProtection.XmlEncryption;
|
||||
|
||||
namespace Yavsc.Auth {
|
||||
|
||||
public class MonoXmlEncryptor : IXmlEncryptor
|
||||
{
|
||||
public MonoXmlEncryptor (IServiceProvider serviceProvider)
|
||||
{
|
||||
}
|
||||
public EncryptedXmlInfo Encrypt(XElement plaintextElement)
|
||||
{
|
||||
var result = new EncryptedXmlInfo(plaintextElement,
|
||||
typeof(MonoDataProtector));
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
BIN
src/Yavsc/Avatars-Dev/Paul Schneider.png
Normal file
|
After Width: | Height: | Size: 38 KiB |
BIN
src/Yavsc/Avatars-Dev/Paul Schneider.s.png
Normal file
|
After Width: | Height: | Size: 11 KiB |
BIN
src/Yavsc/Avatars-Dev/Paul Schneider.xs.png
Normal file
|
After Width: | Height: | Size: 3.1 KiB |
BIN
src/Yavsc/Avatars-Dev/Paul.png
Normal file
|
After Width: | Height: | Size: 40 KiB |
BIN
src/Yavsc/Avatars-Dev/Paul.s.png
Normal file
|
After Width: | Height: | Size: 11 KiB |
BIN
src/Yavsc/Avatars-Dev/Paul.xs.png
Normal file
|
After Width: | Height: | Size: 3.1 KiB |
BIN
src/Yavsc/Avatars-Dev/Soraya Boudjouraf.png
Normal file
|
After Width: | Height: | Size: 32 KiB |
BIN
src/Yavsc/Avatars-Dev/Soraya Boudjouraf.s.png
Normal file
|
After Width: | Height: | Size: 9.5 KiB |
BIN
src/Yavsc/Avatars-Dev/Soraya Boudjouraf.xs.png
Normal file
|
After Width: | Height: | Size: 2.9 KiB |
BIN
src/Yavsc/Avatars-Dev/notazof.png
Normal file
|
After Width: | Height: | Size: 38 KiB |
BIN
src/Yavsc/Avatars-Dev/notazof.s.png
Normal file
|
After Width: | Height: | Size: 11 KiB |
BIN
src/Yavsc/Avatars-Dev/notazof.xs.png
Normal file
|
After Width: | Height: | Size: 3.1 KiB |