WIP separation Web et API

This commit is contained in:
Paul Schneider
2025-02-12 20:41:14 +00:00
parent 6cd5f1d041
commit c2ae054719
55 changed files with 71 additions and 98 deletions

View File

@ -5,6 +5,7 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.12" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.13" />
<ProjectReference Include="../Yavsc/Yavsc.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,151 @@
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Blog;
namespace Yavsc.Controllers
{
[Produces("application/json")]
[Route("api/blog")]
public class BlogApiController : Controller
{
private readonly 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 BadRequest(ModelState);
}
BlogPost blog = _context.BlogSpot.Single(m => m.Id == id);
if (blog == null)
{
return NotFound();
}
return Ok(blog);
}
// PUT: api/BlogApi/5
[HttpPut("{id}")]
public IActionResult PutBlog(long id, [FromBody] BlogPost blog)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != blog.Id)
{
return BadRequest();
}
_context.Entry(blog).State = EntityState.Modified;
try
{
_context.SaveChanges(User.GetUserId());
}
catch (DbUpdateConcurrencyException)
{
if (!BlogExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return new StatusCodeResult(StatusCodes.Status204NoContent);
}
// POST: api/BlogApi
[HttpPost]
public IActionResult PostBlog([FromBody] Models.Blog.BlogPost blog)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.BlogSpot.Add(blog);
try
{
_context.SaveChanges(User.GetUserId());
}
catch (DbUpdateException)
{
if (BlogExists(blog.Id))
{
return new StatusCodeResult(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 BadRequest(ModelState);
}
BlogPost blog = _context.BlogSpot.Single(m => m.Id == id);
if (blog == null)
{
return NotFound();
}
_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;
}
}
}

View File

@ -0,0 +1,147 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Models;
using Yavsc.Models.Blog;
namespace Yavsc.Controllers
{
[Produces("application/json")]
[Route("api/blogtags")]
public class BlogTagsApiController : Controller
{
private readonly 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 BadRequest(ModelState);
}
BlogTag blogTag = await _context.TagsDomain.SingleAsync(m => m.PostId == id);
if (blogTag == null)
{
return NotFound();
}
return Ok(blogTag);
}
// PUT: api/BlogTagsApi/5
[HttpPut("{id}")]
public async Task<IActionResult> PutBlogTag([FromRoute] long id, [FromBody] BlogTag blogTag)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != blogTag.PostId)
{
return BadRequest();
}
_context.Entry(blogTag).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!BlogTagExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return new StatusCodeResult(StatusCodes.Status204NoContent);
}
// POST: api/BlogTagsApi
[HttpPost]
public async Task<IActionResult> PostBlogTag([FromBody] BlogTag blogTag)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.TagsDomain.Add(blogTag);
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException)
{
if (BlogTagExists(blogTag.PostId))
{
return new StatusCodeResult(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 BadRequest(ModelState);
}
BlogTag blogTag = await _context.TagsDomain.SingleAsync(m => m.PostId == id);
if (blogTag == null)
{
return NotFound();
}
_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;
}
}
}

View File

@ -0,0 +1,135 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Blog;
namespace Yavsc.Controllers
{
[Authorize]
[Produces("application/json")]
[Route("api/blogcomments")]
public class CommentsApiController : Controller
{
private readonly ApplicationDbContext _context;
public CommentsApiController(ApplicationDbContext context)
{
_context = context;
}
[HttpGet("{id}", Name = "GetComment")]
public async Task<IActionResult> GetComment([FromRoute] long id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Comment comment = await _context.Comment.SingleAsync(m => m.Id == id);
if (comment == null)
{
return NotFound();
}
return Ok(comment);
}
[HttpPost]
public async Task<IActionResult> Post([FromBody] CommentPost post)
{
if (!ModelState.IsValid)
{
return new BadRequestObjectResult(ModelState);
}
var article = await _context.BlogSpot.FirstOrDefaultAsync
(p=> p.Id == post.ReceiverId);
if (article==null) {
ModelState.AddModelError("ReceiverId", "not found");
return BadRequest(ModelState);
}
if (post.ParentId!=null)
{
var parentExists = _context.Comment.Any(c => c.Id == post.ParentId);
if (!parentExists)
{
ModelState.AddModelError("ParentId", "not found");
return BadRequest(ModelState);
}
}
string uid = User.GetUserId();
Comment c = new Comment{
ReceiverId = post.ReceiverId,
Content = post.Content,
ParentId = post.ParentId,
AuthorId = uid,
UserModified = uid
};
_context.Comment.Add(c);
try
{
await _context.SaveChangesAsync(uid);
}
catch (DbUpdateException)
{
if (CommentExists(c.Id))
{
return new StatusCodeResult(StatusCodes.Status409Conflict);
}
else
{
throw;
}
}
return CreatedAtRoute("GetComment", new { id = c.Id }, new { id = c.Id, dateCreated = c.DateCreated });
}
// DELETE: api/CommentsApi/5
[HttpDelete("{id}")]
public async Task<IActionResult> Delete([FromRoute] long id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Comment comment = await _context.Comment.SingleAsync(m => m.Id == id);
if (comment == null)
{
return NotFound();
}
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;
}
}
}

View File

@ -0,0 +1,185 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Yavsc.Models;
namespace Yavsc.ApiControllers
{
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Yavsc.Helpers;
using Yavsc.Exceptions;
using Yavsc.Models.FileSystem;
using System.ComponentModel.DataAnnotations;
using Yavsc.Attributes.Validation;
using System.IO;
[Authorize,Route("api/fs")]
public partial class FileSystemApiController : Controller
{
readonly ApplicationDbContext dbContext;
private readonly IAuthorizationService AuthorizationService;
private readonly 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([ValidRemoteUserFilePath] string subdir="")
{
if (!ModelState.IsValid) return new BadRequestObjectResult(ModelState);
// _logger.LogInformation($"listing files from {User.Identity.Name}{subdir}");
var files = AbstractFileSystemHelpers.GetUserFiles(User.GetUserId(), subdir);
return Ok(files);
}
[HttpPost("{*subdir}")]
public IActionResult Post([ValidRemoteUserFilePath] string subdir="")
{
if (!ModelState.IsValid) return new BadRequestObjectResult(ModelState);
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 BadRequest(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);
}
[Route("/api/fsc/addquota/{uname}/{len}")]
[Authorize("AdministratorOnly")]
public IActionResult AddQuota(string uname, int len)
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
var user = dbContext.Users.FirstOrDefault(
u => u.UserName == uname
);
if (user==null) return new BadRequestObjectResult(new { error = "no such use" });
user.AddQuota(len);
dbContext.SaveChanges(uid);
return Ok(len);
}
[HttpPost]
[Route("/api/fsc/mvftd")]
[Authorize()]
public IActionResult MoveFile([FromBody] RenameFileQuery query)
{
if (!ModelState.IsValid) return new BadRequestObjectResult(ModelState);
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
var user = dbContext.Users.Single(
u => u.Id == uid
);
var info = user.MoveUserFileToDir(query.id, query.to);
if (!info.Done) return new BadRequestObjectResult(info);
return Ok(new { moved = query.id });
}
[HttpPost]
[Route("/api/fsc/mvf")]
[Authorize()]
public IActionResult RenameFile([FromBody] RenameFileQuery query)
{
if (!ModelState.IsValid) {
var idvr = new ValidRemoteUserFilePathAttribute();
return this.BadRequest(new { id = idvr.IsValid(query.id), to = idvr.IsValid(query.to), errors = ModelState });
}
_logger.LogInformation($"Valid move query: {query.id} => {query.to}");
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
var user = dbContext.Users.Single(
u => u.Id == uid
);
try {
if (Config.UserFilesOptions.FileProvider.GetFileInfo(Path.Combine(user.UserName, query.id)).Exists)
{
var result = user.MoveUserFile(query.id, query.to);
if (!result.Done) return new BadRequestObjectResult(result);
}
else {
var result = user.MoveUserDir(query.id, query.to);
if (!result.Done) return new BadRequestObjectResult(result);
}
}
catch (Exception ex)
{
return new BadRequestObjectResult(
new FsOperationInfo {
Done = false,
ErrorCode = ErrorCode.InternalError,
ErrorMessage = ex.Message
});
}
return Ok();
}
[HttpDelete("{*id}")]
public IActionResult RemoveDirOrFile ([ValidRemoteUserFilePath] string id)
{
if (!ModelState.IsValid) return new BadRequestObjectResult(ModelState);
var user = dbContext.Users.Single(
u => u.Id == User.GetUserId()
);
try {
var result = user.DeleteUserDirOrFile(id);
if (!result.Done)
return new BadRequestObjectResult(result);
}
catch (Exception ex)
{
return new BadRequestObjectResult(
new FsOperationInfo {
Done = false,
ErrorCode = ErrorCode.InternalError,
ErrorMessage = ex.Message
});
}
return Ok(new { deleted=id });
}
}
}

View File

@ -0,0 +1,72 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Attributes.Validation;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Messaging;
using Yavsc.Services;
using Microsoft.AspNetCore.SignalR;
namespace Yavsc.ApiControllers
{
[Authorize, Route("api/stream")]
public partial class FileSystemStreamController : Controller
{
private readonly ILogger logger;
private readonly ILiveProcessor liveProcessor;
private readonly IHubContext<ChatHub> hubContext;
readonly ApplicationDbContext dbContext;
public FileSystemStreamController(ApplicationDbContext context, ILiveProcessor liveProcessor, ILoggerFactory loggerFactory,
IHubContext<ChatHub> hubContext)
{
this.dbContext = context;
this.logger = loggerFactory.CreateLogger<FileSystemStreamController>();
this.liveProcessor = liveProcessor;
this.hubContext = hubContext;
}
[Authorize, Route("put/{filename}")]
public async Task<IActionResult> Put([ValidRemoteUserFilePath] string filename)
{
logger.LogInformation("Put : " + filename);
if (!HttpContext.WebSockets.IsWebSocketRequest)
return BadRequest("not a web socket");
if (!HttpContext.User.Identity.IsAuthenticated)
return new UnauthorizedResult();
var subdirs = filename.Split('/');
var filePath = subdirs.Length > 1 ? string.Join("/", subdirs.Take(subdirs.Length-1)) : null;
var shortFileName = subdirs[subdirs.Length-1];
if (!shortFileName.IsValidShortFileName())
{
logger.LogInformation("invalid file name : " + filename);
return BadRequest("invalid file name");
}
logger.LogInformation("validated: api/stream/Put: "+filename);
var userName = User.GetUserName();
string url = string.Format(
"{0}/{1}/{2}",
Config.UserFilesOptions.RequestPath.ToUriComponent(),
userName,
filename
);
hubContext.Clients.All.SendAsync("addPublicStream", new PublicStreamInfo
{
sender = userName,
url = url,
}, $"{userName} is starting a stream!");
string destDir = HttpContext.User.InitPostToFileSystem(filePath);
logger.LogInformation($"Saving flow to {destDir}");
var userId = User.GetUserId();
var user = await dbContext.Users.FirstAsync(u => u.Id == userId);
logger.LogInformation("Accepting stream ...");
await liveProcessor.AcceptStream(HttpContext, user, destDir, shortFileName);
return Ok();
}
}
}

View File

@ -0,0 +1,23 @@
using Yavsc.Attributes.Validation;
namespace Yavsc.Models.FileSystem
{
public class RenameFileQuery {
[ValidRemoteUserFilePath]
[YaStringLength(1, 512)]
public string id { get; set; }
[YaStringLength(0, 512)]
[ValidRemoteUserFilePath]
public string to { get; set; }
}
public class MoveFileQuery {
[ValidRemoteUserFilePath]
[YaStringLength(1, 512)]
public string id { get; set; }
[YaStringLength(0, 512)]
[ValidRemoteUserFilePath]
public string to { get; set; }
}
}

View File

@ -0,0 +1,150 @@
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Yavsc.Controllers
{
using System.Security.Claims;
using Microsoft.EntityFrameworkCore;
using Models;
using Yavsc.Helpers;
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 BadRequest(ModelState);
}
BlogTag postTag = _context.TagsDomain.Single(m => m.PostId == id);
if (postTag == null)
{
return NotFound();
}
return Ok(postTag);
}
// PUT: api/PostTagsApi/5
[HttpPut("{id}")]
public IActionResult PutPostTag(long id, [FromBody] BlogTag postTag)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != postTag.PostId)
{
return BadRequest();
}
_context.Entry(postTag).State = EntityState.Modified;
try
{
_context.SaveChanges(User.GetUserId());
}
catch (DbUpdateConcurrencyException)
{
if (!PostTagExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return new StatusCodeResult(StatusCodes.Status204NoContent);
}
// POST: api/PostTagsApi
[HttpPost]
public IActionResult PostPostTag([FromBody] BlogTag postTag)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.TagsDomain.Add(postTag);
try
{
_context.SaveChanges(User.GetUserId());
}
catch (DbUpdateException)
{
if (PostTagExists(postTag.PostId))
{
return new StatusCodeResult(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 BadRequest(ModelState);
}
BlogTag postTag = _context.TagsDomain.Single(m => m.PostId == id);
if (postTag == null)
{
return NotFound();
}
_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;
}
}
}

View File

@ -0,0 +1,152 @@
using Microsoft.AspNetCore.Mvc;
using Yavsc.Models;
namespace Yavsc.Controllers
{
using System.Security.Claims;
using Microsoft.EntityFrameworkCore;
using Models.Relationship;
using Yavsc.Helpers;
[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 BadRequest(ModelState);
}
Tag tag = _context.Tags.Single(m => m.Id == id);
if (tag == null)
{
return NotFound();
}
return Ok(tag);
}
// PUT: api/TagsApi/5
[HttpPut("{id}")]
public IActionResult PutTag(long id, [FromBody] Tag tag)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != tag.Id)
{
return BadRequest();
}
_context.Entry(tag).State = EntityState.Modified;
try
{
_context.SaveChanges(User.GetUserId());
_logger.LogInformation("Tag created");
}
catch (DbUpdateConcurrencyException)
{
if (!TagExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return new StatusCodeResult(StatusCodes.Status204NoContent);
}
// POST: api/TagsApi
[HttpPost]
public IActionResult PostTag([FromBody] Tag tag)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.Tags.Add(tag);
try
{
_context.SaveChanges(User.GetUserId());
}
catch (DbUpdateException)
{
if (TagExists(tag.Id))
{
return new StatusCodeResult(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 BadRequest(ModelState);
}
Tag tag = _context.Tags.Single(m => m.Id == id);
if (tag == null)
{
return NotFound();
}
_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;
}
}
}

View File

@ -0,0 +1,15 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Yavsc.ApiControllers
{
using System.ComponentModel.DataAnnotations;
using Yavsc.Attributes.Validation;
[Authorize,Route("~/api/test")]
public class TestApiController : Controller
{
}
}

View File

@ -0,0 +1,154 @@
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
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 BadRequest(ModelState);
}
Activity activity = await _context.Activities.SingleAsync(m => m.Code == id);
if (activity == null)
{
return NotFound();
}
// 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 BadRequest(ModelState);
}
if (id != activity.Code)
{
return BadRequest();
}
_context.Entry(activity).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync(User.GetUserId());
}
catch (DbUpdateConcurrencyException)
{
if (!ActivityExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return new StatusCodeResult(StatusCodes.Status204NoContent);
}
// POST: api/ActivityApi
[HttpPost,Authorize("AdministratorOnly")]
public async Task<IActionResult> PostActivity([FromBody] Activity activity)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.Activities.Add(activity);
try
{
await _context.SaveChangesAsync(User.GetUserId());
}
catch (DbUpdateException)
{
if (ActivityExists(activity.Code))
{
return new StatusCodeResult(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 BadRequest(ModelState);
}
Activity activity = await _context.Activities.SingleAsync(m => m.Code == id);
if (activity == null)
{
return NotFound();
}
_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;
}
}
}

View File

@ -0,0 +1,184 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization;
using Newtonsoft.Json;
using System.Security.Claims;
using Yavsc.Helpers;
using Yavsc.ViewModels;
namespace Yavsc.ApiControllers
{
using Models;
using Services;
using Models.Messaging;
using ViewModels.Auth;
using Microsoft.Extensions.Options;
using Microsoft.EntityFrameworkCore;
[Route("api/bill"), Authorize]
public class BillingController : Controller
{
readonly ApplicationDbContext dbContext;
private readonly IStringLocalizer _localizer;
private readonly GoogleAuthSettings _googleSettings;
private readonly IYavscMessageSender _GCMSender;
private readonly IAuthorizationService authorizationService;
private readonly ILogger logger;
private readonly IBillingService billingService;
public BillingController(
IAuthorizationService authorizationService,
ILoggerFactory loggerFactory,
IStringLocalizer<Yavsc.YavscLocalization> SR,
ApplicationDbContext context,
IOptions<GoogleAuthSettings> googleSettings,
IYavscMessageSender 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 ( authorizationService.AuthorizeAsync(User, bill, new ViewRequirement()).IsFaulted)
{
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.NotFound();
}
logger.LogTrace(JsonConvert.SerializeObject(bill));
if (!(await authorizationService.AuthorizeAsync(User, bill, new ViewRequirement())).Succeeded)
{
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.NotFound();
}
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.DeviceDeclaration)
.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())).Succeeded)
{
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 = new [] { estimate.Client.Id };
bool gcmSent = false;
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())).Succeeded)
{
return new ChallengeResult();
}
var filename = AbstractFileSystemHelpers.SignFileNameFormat("pro", billingCode, id);
FileInfo fi = new FileInfo(Path.Combine(AbstractFileSystemHelpers.UserBillsDirName, filename));
if (!fi.Exists) return NotFound(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.FindFirstValue(ClaimTypes.NameIdentifier);
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())).Succeeded)
{
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())).Succeeded)
{
return new ChallengeResult();
}
var filename = AbstractFileSystemHelpers.SignFileNameFormat("pro", billingCode, id);
FileInfo fi = new FileInfo(Path.Combine(AbstractFileSystemHelpers.UserBillsDirName, filename));
if (!fi.Exists) return NotFound(new { Error = "Professional signature not found" });
return File(fi.OpenRead(), "application/x-pdf", filename); ;
}
}
}

View File

@ -0,0 +1,196 @@
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace Yavsc.Controllers
{
using System;
using Yavsc.Models;
using Yavsc.Models.Workflow;
using Yavsc.Models.Billing;
using Yavsc.Abstract.Identity;
using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
[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.FindFirstValue(ClaimTypes.NameIdentifier);
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 BadRequest(ModelState);
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
RdvQuery bookQuery = _context.RdvQueries.Where(c => c.ClientId == uid || c.PerformerId == uid).Single(m => m.Id == id);
if (bookQuery == null)
{
return NotFound();
}
return Ok(bookQuery);
}
// PUT: api/BookQueryApi/5
[HttpPut("{id}")]
public IActionResult PutBookQuery(long id, [FromBody] RdvQuery bookQuery)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != bookQuery.Id)
{
return BadRequest();
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (bookQuery.ClientId != uid)
return NotFound();
_context.Entry(bookQuery).State = EntityState.Modified;
try
{
_context.SaveChanges(User.GetUserId());
}
catch (DbUpdateConcurrencyException)
{
if (!BookQueryExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return new StatusCodeResult(StatusCodes.Status204NoContent);
}
// POST: api/BookQueryApi
[HttpPost]
public IActionResult PostBookQuery([FromBody] RdvQuery bookQuery)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
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 StatusCodeResult(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 BadRequest(ModelState);
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
RdvQuery bookQuery = _context.RdvQueries.Single(m => m.Id == id);
if (bookQuery == null)
{
return NotFound();
}
if (bookQuery.ClientId != uid) return NotFound();
_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;
}
}
}

View File

@ -0,0 +1,217 @@
using System;
using System.Linq;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Billing;
namespace Yavsc.Controllers
{
[Produces("application/json")]
[Route("api/estimate"), Authorize]
public class EstimateApiController : Controller
{
private readonly ApplicationDbContext _context;
private readonly 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 StatusCodeResult(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 BadRequest(ModelState);
}
Estimate estimate = _context.Estimates.Include(e => e.Bill).Single(m => m.Id == id);
if (estimate == null)
{
return NotFound();
}
if (UserIsAdminOrInThese(estimate.ClientId, estimate.OwnerId))
return Ok(estimate);
return new StatusCodeResult(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 BadRequest();
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (!User.IsInRole(Constants.AdminGroupName))
{
if (uid != estimate.OwnerId)
{
ModelState.AddModelError("OwnerId", "You can only modify your own estimates");
return BadRequest(ModelState);
}
}
var entry = _context.Attach(estimate);
try
{
_context.SaveChanges(User.GetUserId());
}
catch (DbUpdateConcurrencyException)
{
if (!EstimateExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return Ok(new { estimate.Id });
}
// POST: api/Estimate
[HttpPost, Produces("application/json")]
public IActionResult PostEstimate([FromBody] Estimate estimate)
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
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 BadRequest(ModelState);
}
}
if (estimate.CommandId != null)
{
var query = _context.RdvQueries.FirstOrDefault(q => q.Id == estimate.CommandId);
if (query == null)
{
return BadRequest(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 StatusCodeResult(StatusCodes.Status409Conflict);
}
else
{
throw;
}
}
return Ok(new { estimate.Id, estimate.Bill });
}
// DELETE: api/Estimate/5
[HttpDelete("{id}")]
public IActionResult DeleteEstimate(long id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Estimate estimate = _context.Estimates.Include(e => e.Bill).Single(m => m.Id == id);
if (estimate == null)
{
return NotFound();
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (!User.IsInRole(Constants.AdminGroupName))
{
if (uid != estimate.OwnerId)
{
ModelState.AddModelError("OwnerId", "You can only create your own estimates");
return BadRequest(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;
}
}
}

View File

@ -0,0 +1,157 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
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.FindFirstValue(ClaimTypes.NameIdentifier);
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 BadRequest(ModelState);
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
EstimateTemplate estimateTemplate = _context.EstimateTemplates.Where(x=>x.OwnerId==uid).Single(m => m.Id == id);
if (estimateTemplate == null)
{
return NotFound();
}
return Ok(estimateTemplate);
}
// PUT: api/EstimateTemplatesApi/5
[HttpPut("{id}")]
public IActionResult PutEstimateTemplate(long id, [FromBody] EstimateTemplate estimateTemplate)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != estimateTemplate.Id)
{
return BadRequest();
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (estimateTemplate.OwnerId!=uid)
if (!User.IsInRole(Constants.AdminGroupName))
return new StatusCodeResult(StatusCodes.Status403Forbidden);
_context.Entry(estimateTemplate).State = EntityState.Modified;
try
{
_context.SaveChanges(User.GetUserId());
}
catch (DbUpdateConcurrencyException)
{
if (!EstimateTemplateExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return new StatusCodeResult(StatusCodes.Status204NoContent);
}
// POST: api/EstimateTemplatesApi
[HttpPost]
public IActionResult PostEstimateTemplate([FromBody] EstimateTemplate estimateTemplate)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
estimateTemplate.OwnerId=User.GetUserId();
_context.EstimateTemplates.Add(estimateTemplate);
try
{
_context.SaveChanges(User.GetUserId());
}
catch (DbUpdateException)
{
if (EstimateTemplateExists(estimateTemplate.Id))
{
return new StatusCodeResult(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 BadRequest(ModelState);
}
EstimateTemplate estimateTemplate = _context.EstimateTemplates.Single(m => m.Id == id);
if (estimateTemplate == null)
{
return NotFound();
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (estimateTemplate.OwnerId!=uid)
if (!User.IsInRole(Constants.AdminGroupName))
return new StatusCodeResult(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;
}
}
}

View File

@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.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 BadRequest("billingCode");
if (queryId == 0) return BadRequest("queryId");
var billing = BillingService.GetBillable(dbContext, billingCode, queryId);
if (billing == null) return BadRequest();
billing.Decided = true;
billing.Accepted = false;
dbContext.SaveChanges();
return Ok();
}
[HttpPost("query/reject")]
public IActionResult AcceptQuery(string billingCode, long queryId)
{
if (billingCode == null) return BadRequest("billingCode");
if (queryId == 0) return BadRequest("queryId");
var billing = BillingService.GetBillable(dbContext, billingCode, queryId);
if (billing == null) return BadRequest();
billing.Accepted = true;
billing.Decided = true;
dbContext.SaveChanges();
return Ok();
}
}
}

View File

@ -0,0 +1,33 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Yavsc.Helpers;
using Yavsc.Models;
namespace Yavsc.ApiControllers
{
[Route("api/payment")]
public class PaymentApiController : Controller
{
private readonly ApplicationDbContext dbContext;
private readonly 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);
}
}
}

View File

@ -0,0 +1,65 @@
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
namespace Yavsc.Controllers
{
using Microsoft.EntityFrameworkCore;
using Models;
using Yavsc.Helpers;
using Yavsc.Services;
[Produces("application/json")]
[Route("api/performers")]
public class PerformersApiController : Controller
{
ApplicationDbContext dbContext;
private readonly 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.FindFirstValue(ClaimTypes.NameIdentifier);
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));
}
}
}

View File

@ -0,0 +1,146 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Market;
namespace Yavsc.Controllers
{
[Produces("application/json")]
[Route("api/ProductApi")]
public class ProductApiController : Controller
{
private readonly 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 BadRequest(ModelState);
}
Product product = _context.Products.Single(m => m.Id == id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
// PUT: api/ProductApi/5
[HttpPut("{id}"),Authorize(Constants.FrontOfficeGroupName)]
public IActionResult PutProduct(long id, [FromBody] Product product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != product.Id)
{
return BadRequest();
}
_context.Entry(product).State = EntityState.Modified;
try
{
_context.SaveChanges(User.GetUserId());
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return new StatusCodeResult(StatusCodes.Status204NoContent);
}
// POST: api/ProductApi
[HttpPost,Authorize(Constants.FrontOfficeGroupName)]
public IActionResult PostProduct([FromBody] Product product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.Products.Add(product);
try
{
_context.SaveChanges(User.GetUserId());
}
catch (DbUpdateException)
{
if (ProductExists(product.Id))
{
return new StatusCodeResult(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 BadRequest(ModelState);
}
Product product = _context.Products.Single(m => m.Id == id);
if (product == null)
{
return NotFound();
}
_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;
}
}
}

View File

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

View File

@ -0,0 +1,149 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Haircut;
namespace Yavsc.Controllers
{
[Produces("application/json")]
[Route("api/bursherprofiles")]
public class BursherProfilesApiController : Controller
{
private readonly 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 BadRequest(ModelState);
}
BrusherProfile brusherProfile = await _context.BrusherProfile.SingleAsync(m => m.UserId == id);
if (brusherProfile == null)
{
return NotFound();
}
return Ok(brusherProfile);
}
// PUT: api/BursherProfilesApi/5
[HttpPut("{id}")]
public async Task<IActionResult> PutBrusherProfile([FromRoute] string id, [FromBody] BrusherProfile brusherProfile)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != brusherProfile.UserId)
{
return BadRequest();
}
if (id != User.GetUserId())
{
return BadRequest();
}
_context.Entry(brusherProfile).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!BrusherProfileExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return new StatusCodeResult(StatusCodes.Status204NoContent);
}
// POST: api/BursherProfilesApi
[HttpPost]
public async Task<IActionResult> PostBrusherProfile([FromBody] BrusherProfile brusherProfile)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.BrusherProfile.Add(brusherProfile);
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException)
{
if (BrusherProfileExists(brusherProfile.UserId))
{
return new StatusCodeResult(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 BadRequest(ModelState);
}
BrusherProfile brusherProfile = await _context.BrusherProfile.SingleAsync(m => m.UserId == id);
if (brusherProfile == null)
{
return NotFound();
}
_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;
}
}
}

View File

@ -0,0 +1,228 @@
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
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 System.Threading.Tasks;
using Helpers;
using Models.Payment;
using Newtonsoft.Json;
using PayPal.PayPalAPIInterfaceService.Model;
using Yavsc.Models.Haircut.Views;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authorization;
[Route("api/haircut")][Authorize]
public class HairCutController : Controller
{
private readonly ApplicationDbContext _context;
private readonly ILogger _logger;
public HairCutController(ApplicationDbContext context,
ILoggerFactory loggerFactory)
{
_context = context;
_logger = loggerFactory.CreateLogger<HairCutController>();
}
// GET: api/HairCutQueriesApi
// Get the active queries for current
// user, as a client
public IActionResult Index()
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
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 BadRequest(ModelState);
}
HairCutQuery hairCutQuery = await _context.HairCutQueries.SingleAsync(m => m.Id == id);
if (hairCutQuery == null)
{
return NotFound();
}
return Ok(hairCutQuery);
}
// PUT: api/HairCutQueriesApi/5
[HttpPut("{id}")]
public async Task<IActionResult> PutHairCutQuery([FromRoute] long id, [FromBody] HairCutQuery hairCutQuery)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != hairCutQuery.Id)
{
return BadRequest();
}
_context.Entry(hairCutQuery).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!HairCutQueryExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return new StatusCodeResult(StatusCodes.Status204NoContent);
}
[HttpPost]
public async Task<IActionResult> PostQuery(HairCutQuery hairCutQuery)
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (!ModelState.IsValid)
{
return new BadRequestObjectResult(ModelState);
}
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.HairCutQueries.Add(hairCutQuery);
try
{
await _context.SaveChangesAsync(uid);
}
catch (DbUpdateException)
{
if (HairCutQueryExists(hairCutQuery.Id))
{
return new StatusCodeResult(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 StatusCodeResult(500);
}
if (payment==null) {
_logger.LogError("Error doing SetExpressCheckout, aborting.");
_logger.LogError(JsonConvert.SerializeObject(Config.PayPalSettings));
return new StatusCodeResult(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 BadRequest(ModelState);
}
HairCutQuery hairCutQuery = await _context.HairCutQueries.SingleAsync(m => m.Id == id);
if (hairCutQuery == null)
{
return NotFound();
}
_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);
}
}
}

View File

@ -0,0 +1,144 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
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.HyperLink;
}
// GET: api/HyperLinkApi/5
[HttpGet("{id}", Name = "GetHyperLink")]
public async Task<IActionResult> GetHyperLink([FromRoute] string id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
HyperLink hyperLink = await _context.HyperLink.SingleAsync(m => m.HRef == id);
if (hyperLink == null)
{
return NotFound();
}
return Ok(hyperLink);
}
// PUT: api/HyperLinkApi/5
[HttpPut("{id}")]
public async Task<IActionResult> PutHyperLink([FromRoute] string id, [FromBody] HyperLink hyperLink)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != hyperLink.HRef)
{
return BadRequest();
}
_context.Entry(hyperLink).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!HyperLinkExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return new StatusCodeResult(StatusCodes.Status204NoContent);
}
// POST: api/HyperLinkApi
[HttpPost]
public async Task<IActionResult> PostHyperLink([FromBody] HyperLink hyperLink)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.HyperLink.Add(hyperLink);
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException)
{
if (HyperLinkExists(hyperLink.HRef))
{
return new StatusCodeResult(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 BadRequest(ModelState);
}
HyperLink hyperLink = await _context.HyperLink.SingleAsync(m => m.HRef == id);
if (hyperLink == null)
{
return NotFound();
}
_context.HyperLink.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.HyperLink.Count(e => e.HRef == id) > 0;
}
}
}

View File

@ -0,0 +1,141 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
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 BadRequest(ModelState);
}
GitRepositoryReference gitRepositoryReference = await _context.GitRepositoryReference.SingleAsync(m => m.Id == id);
if (gitRepositoryReference == null)
{
return NotFound();
}
return Ok(gitRepositoryReference);
}
// PUT: api/GitRefsApi/5
[HttpPut("{id}")]
public async Task<IActionResult> PutGitRepositoryReference([FromRoute] long id, [FromBody] GitRepositoryReference gitRepositoryReference)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.Entry(gitRepositoryReference).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!GitRepositoryReferenceExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return new StatusCodeResult(StatusCodes.Status204NoContent);
}
// POST: api/GitRefsApi
[HttpPost]
public async Task<IActionResult> PostGitRepositoryReference([FromBody] GitRepositoryReference gitRepositoryReference)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.GitRepositoryReference.Add(gitRepositoryReference);
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException)
{
if (GitRepositoryReferenceExists(gitRepositoryReference.Id))
{
return new StatusCodeResult(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 BadRequest(ModelState);
}
GitRepositoryReference gitRepositoryReference = await _context.GitRepositoryReference.SingleAsync(m => m.Id == id);
if (gitRepositoryReference == null)
{
return NotFound();
}
_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;
}
}
}

View File

@ -0,0 +1,10 @@
using Microsoft.AspNetCore.Mvc;
namespace Yavsc.ApiControllers
{
[Route("api/mailtemplate")]
public class MailTemplatingApiController: Controller
{
}
}

View File

@ -0,0 +1,146 @@
using Microsoft.AspNetCore.Mvc;
using Yavsc.Models;
using Yavsc.Server.Models.EMailing;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
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] string id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
MailingTemplate mailingTemplate = await _context.MailingTemplate.SingleAsync(m => m.Id == id);
if (mailingTemplate == null)
{
return NotFound();
}
return Ok(mailingTemplate);
}
// PUT: api/MailingTemplateApi/5
[HttpPut("{id}")]
public async Task<IActionResult> PutMailingTemplate([FromRoute] string id, [FromBody] MailingTemplate mailingTemplate)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != mailingTemplate.Id)
{
return BadRequest();
}
_context.Entry(mailingTemplate).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!MailingTemplateExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return new StatusCodeResult(StatusCodes.Status204NoContent);
}
// POST: api/MailingTemplateApi
[HttpPost]
public async Task<IActionResult> PostMailingTemplate([FromBody] MailingTemplate mailingTemplate)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.MailingTemplate.Add(mailingTemplate);
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException)
{
if (MailingTemplateExists(mailingTemplate.Id))
{
return new StatusCodeResult(StatusCodes.Status409Conflict);
}
else
{
throw;
}
}
return CreatedAtRoute("GetMailingTemplate", new { id = mailingTemplate.Id }, mailingTemplate);
}
// DELETE: api/MailingTemplateApi/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteMailingTemplate([FromRoute] string id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
MailingTemplate mailingTemplate = await _context.MailingTemplate.SingleAsync(m => m.Id == id);
if (mailingTemplate == null)
{
return NotFound();
}
_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(string id)
{
return _context.MailingTemplate.Count(e => e.Id == id) > 0;
}
}
}

View File

@ -0,0 +1,12 @@
namespace Yavsc.ApiControllers
{
using Models;
using Yavsc.Models.Musical.Profiles;
public class DjProfileApiController : ProfileApiController<DjSettings>
{
public DjProfileApiController() : base()
{
}
}
}

View File

@ -0,0 +1,144 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Musical;
namespace Yavsc.Controllers
{
[Produces("application/json")]
[Route("api/museprefs")]
public class MusicalPreferencesApiController : Controller
{
private readonly ApplicationDbContext _context;
public MusicalPreferencesApiController(ApplicationDbContext context)
{
_context = context;
}
// GET: api/MusicalPreferencesApi
[HttpGet]
public IEnumerable<MusicalPreference> GetMusicalPreferences()
{
return _context.MusicalPreference;
}
// GET: api/MusicalPreferencesApi/5
[HttpGet("{id}", Name = "GetMusicalPreference")]
public IActionResult GetMusicalPreference([FromRoute] string id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
MusicalPreference musicalPreference = _context.MusicalPreference.Single(m => m.OwnerProfileId == id);
if (musicalPreference == null)
{
return NotFound();
}
return Ok(musicalPreference);
}
// PUT: api/MusicalPreferencesApi/5
public IActionResult PutMusicalPreference(string id, [FromBody] MusicalPreference musicalPreference)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != musicalPreference.OwnerProfileId)
{
return BadRequest();
}
_context.Entry(musicalPreference).State = EntityState.Modified;
try
{
_context.SaveChanges(User.GetUserId());
}
catch (DbUpdateConcurrencyException)
{
if (!MusicalPreferenceExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return new StatusCodeResult(StatusCodes.Status204NoContent);
}
// POST: api/MusicalPreferencesApi
[HttpPost]
public IActionResult PostMusicalPreference([FromBody] MusicalPreference musicalPreference)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.MusicalPreference.Add(musicalPreference);
try
{
_context.SaveChanges(User.GetUserId());
}
catch (DbUpdateException)
{
if (MusicalPreferenceExists(musicalPreference.OwnerProfileId))
{
return new StatusCodeResult(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 BadRequest(ModelState);
}
MusicalPreference musicalPreference = _context.MusicalPreference.Single(m => m.OwnerProfileId == id);
if (musicalPreference == null)
{
return NotFound();
}
_context.MusicalPreference.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.MusicalPreference.Count(e => e.OwnerProfileId == id) > 0;
}
}
}

View File

@ -0,0 +1,145 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Musical;
namespace Yavsc.Controllers
{
[Produces("application/json")]
[Route("api/MusicalTendenciesApi")]
public class MusicalTendenciesApiController : Controller
{
private readonly 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 BadRequest(ModelState);
}
MusicalTendency musicalTendency = _context.MusicalTendency.Single(m => m.Id == id);
if (musicalTendency == null)
{
return NotFound();
}
return Ok(musicalTendency);
}
// PUT: api/MusicalTendenciesApi/5
[HttpPut("{id}")]
public IActionResult PutMusicalTendency(long id, [FromBody] MusicalTendency musicalTendency)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != musicalTendency.Id)
{
return BadRequest();
}
_context.Entry(musicalTendency).State = EntityState.Modified;
try
{
_context.SaveChanges(User.GetUserId());
}
catch (DbUpdateConcurrencyException)
{
if (!MusicalTendencyExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return new StatusCodeResult(StatusCodes.Status204NoContent);
}
// POST: api/MusicalTendenciesApi
[HttpPost]
public IActionResult PostMusicalTendency([FromBody] MusicalTendency musicalTendency)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.MusicalTendency.Add(musicalTendency);
try
{
_context.SaveChanges(User.GetUserId());
}
catch (DbUpdateException)
{
if (MusicalTendencyExists(musicalTendency.Id))
{
return new StatusCodeResult(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 BadRequest(ModelState);
}
MusicalTendency musicalTendency = _context.MusicalTendency.Single(m => m.Id == id);
if (musicalTendency == null)
{
return NotFound();
}
_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;
}
}
}

View File

@ -0,0 +1,8 @@
using Microsoft.AspNetCore.Mvc;
namespace Yavsc.ApiControllers
{
public class PodcastController : Controller
{
}
}

View File

@ -0,0 +1,70 @@

using System;
using System.Linq;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Identity;
[Authorize, Route("~/api/gcm")]
public class NativeConfidentialController : Controller
{
readonly ILogger _logger;
readonly ApplicationDbContext _context;
public NativeConfidentialController(ApplicationDbContext context,
ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<NativeConfidentialController>();
_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] DeviceDeclaration declaration)
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (!ModelState.IsValid)
{
_logger.LogError("Invalid model for GCMD");
return new BadRequestObjectResult(ModelState);
}
declaration.LatestActivityUpdate = DateTime.Now;
_logger.LogInformation($"Registering device with id:{declaration.DeviceId} for {uid}");
DeviceDeclaration? alreadyRegisteredDevice = _context.DeviceDeclaration.FirstOrDefault(d => d.DeviceId == declaration.DeviceId);
var deviceAlreadyRegistered = (alreadyRegisteredDevice!=null);
if (alreadyRegisteredDevice==null)
{
declaration.DeclarationDate = DateTime.Now;
declaration.DeviceOwnerId = uid;
_context.DeviceDeclaration.Add(declaration);
}
else {
alreadyRegisteredDevice.DeviceOwnerId = uid;
alreadyRegisteredDevice.Model = declaration.Model;
alreadyRegisteredDevice.Platform = declaration.Platform;
alreadyRegisteredDevice.Version = declaration.Version;
_context.Update(alreadyRegisteredDevice);
_context.SaveChanges(User.GetUserId());
}
_context.SaveChanges(User.GetUserId());
var latestActivityUpdate = _context.Activities.Max(a=>a.DateModified);
return Json(new {
IsAnUpdate = deviceAlreadyRegistered,
UpdateActivities = latestActivityUpdate != declaration.LatestActivityUpdate
});
}
}

View File

@ -0,0 +1,47 @@
using System.Linq;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Yavsc.Helpers;
using Yavsc.Models;
namespace Yavsc.Controllers
{
[Produces("application/json")]
[Route("~/api/PostRateApi")]
public class PostRateApiController : Controller
{
private readonly 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 BadRequest(ModelState);
}
Models.Blog.BlogPost blogpost = _context.BlogSpot.Single(x=>x.Id == id);
if (blogpost == null)
{
return NotFound();
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (blogpost.AuthorId!=uid)
if (!User.IsInRole(Constants.AdminGroupName))
return BadRequest();
_context.SaveChanges(User.GetUserId());
return Ok();
}
}
}

View File

@ -0,0 +1,17 @@
using Microsoft.AspNetCore.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
{ public ProfileApiController()
{
}
}
}

View File

@ -0,0 +1,163 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Access;
namespace Yavsc.Controllers
{
[Produces("application/json")]
[Route("api/blacklist"), Authorize]
public class BlackListApiController : Controller
{
private readonly 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 BadRequest(ModelState);
}
BlackListed blackListed = _context.BlackListed.Single(m => m.Id == id);
if (blackListed == null)
{
return NotFound();
}
if (!CheckPermission(blackListed))
return BadRequest();
return Ok(blackListed);
}
private bool CheckPermission(BlackListed blackListed)
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
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 BadRequest(ModelState);
}
if (id != blackListed.Id)
{
return BadRequest();
}
if (!CheckPermission(blackListed))
return BadRequest();
_context.Entry(blackListed).State = EntityState.Modified;
try
{
_context.SaveChanges(User.GetUserId());
}
catch (DbUpdateConcurrencyException)
{
if (!BlackListedExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return new StatusCodeResult(StatusCodes.Status204NoContent);
}
// POST: api/BlackListApi
[HttpPost]
public IActionResult PostBlackListed([FromBody] BlackListed blackListed)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (!CheckPermission(blackListed))
return BadRequest();
_context.BlackListed.Add(blackListed);
try
{
_context.SaveChanges(User.GetUserId());
}
catch (DbUpdateException)
{
if (BlackListedExists(blackListed.Id))
{
return new StatusCodeResult(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 BadRequest(ModelState);
}
BlackListed blackListed = _context.BlackListed.Single(m => m.Id == id);
if (blackListed == null)
{
return NotFound();
}
if (!CheckPermission(blackListed))
return BadRequest();
_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;
}
}
}

View File

@ -0,0 +1,164 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Access;
namespace Yavsc.Controllers
{
[Produces("application/json")]
[Route("api/blogacl")]
public class BlogAclApiController : Controller
{
private readonly ApplicationDbContext _context;
public BlogAclApiController(ApplicationDbContext context)
{
_context = context;
}
// GET: api/BlogAclApi
[HttpGet]
public IEnumerable<CircleAuthorizationToBlogPost> GetBlogACL()
{
return _context.CircleAuthorizationToBlogPost;
}
// GET: api/BlogAclApi/5
[HttpGet("{id}", Name = "GetCircleAuthorizationToBlogPost")]
public async Task<IActionResult> GetCircleAuthorizationToBlogPost([FromRoute] long id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
CircleAuthorizationToBlogPost circleAuthorizationToBlogPost = await _context.CircleAuthorizationToBlogPost.SingleAsync(
m => m.CircleId == id && m.Allowed.OwnerId == uid );
if (circleAuthorizationToBlogPost == null)
{
return NotFound();
}
return Ok(circleAuthorizationToBlogPost);
}
// PUT: api/BlogAclApi/5
[HttpPut("{id}")]
public async Task<IActionResult> PutCircleAuthorizationToBlogPost([FromRoute] long id, [FromBody] CircleAuthorizationToBlogPost circleAuthorizationToBlogPost)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != circleAuthorizationToBlogPost.CircleId)
{
return BadRequest();
}
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 NotFound();
}
else
{
throw;
}
}
return new StatusCodeResult(StatusCodes.Status204NoContent);
}
private bool CheckOwner (long circleId)
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
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 BadRequest(ModelState);
}
if (!CheckOwner(circleAuthorizationToBlogPost.CircleId))
{
return new ChallengeResult();
}
_context.CircleAuthorizationToBlogPost.Add(circleAuthorizationToBlogPost);
try
{
await _context.SaveChangesAsync(User.GetUserId());
}
catch (DbUpdateException)
{
if (CircleAuthorizationToBlogPostExists(circleAuthorizationToBlogPost.CircleId))
{
return new StatusCodeResult(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 BadRequest(ModelState);
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
CircleAuthorizationToBlogPost circleAuthorizationToBlogPost = await _context.CircleAuthorizationToBlogPost.Include(
a=>a.Allowed
).SingleAsync(m => m.CircleId == id
&& m.Allowed.OwnerId == uid);
if (circleAuthorizationToBlogPost == null)
{
return NotFound();
}
_context.CircleAuthorizationToBlogPost.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.CircleAuthorizationToBlogPost.Count(e => e.CircleId == id) > 0;
}
}
}

View File

@ -0,0 +1,114 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Identity;
using Yavsc.Models;
using Yavsc.ViewModels.Chat;
using Yavsc.Services;
using Microsoft.EntityFrameworkCore;
namespace Yavsc.Controllers
{
[Route("api/chat")]
public class ChatApiController : Controller
{
readonly ApplicationDbContext dbContext;
readonly UserManager<ApplicationUser> userManager;
private readonly IConnexionManager _cxManager;
public ChatApiController(ApplicationDbContext dbContext,
UserManager<ApplicationUser> userManager,
IConnexionManager cxManager)
{
this.dbContext = dbContext;
this.userManager = userManager;
_cxManager = cxManager;
}
[HttpGet("users")]
public IEnumerable<ChatUserInfo> GetUserList()
{
List<ChatUserInfo> result = new List<ChatUserInfo>();
var cxsQuery = dbContext.ChatConnection?.Include(c => c.Owner)
.Where(cx => cx.Connected).GroupBy(c => c.ApplicationUserId);
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;
}
// GET: api/chat/userName
[HttpGet("user/{userName}", Name = "uinfo")]
public IActionResult GetUserInfo([FromRoute] string userName)
{
if (!ModelState.IsValid)
// Miguel mech profiler
{
return BadRequest(ModelState);
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
var user = dbContext.ApplicationUser.Include(u => u.Connections).FirstOrDefault(u => u.UserName == userName);
if (user == null) return NotFound();
return Ok(new ChatUserInfo
{
UserName = user.UserName,
UserId = user.Id,
Avatar = user.Avatar,
Connections = user.Connections,
Roles = (userManager.GetRolesAsync(user)).Result.ToArray()
});
}
/// <summary>
/// Get firsts 10 biggest channels having
/// a name starting with given prefix.
/// </summary>
/// <param name="chanNamePrefix">chan Name Prefix</param>
/// <returns></returns>
[HttpGet("chanlist/{chanNamePrefix}")]
public IActionResult GetChanList([FromRoute] string chanNamePrefix)
{
var list = _cxManager.ListChannels(chanNamePrefix);
return Ok(list);
}
/// <summary>
/// Get firsts 10 biggest channels
/// </summary>
/// <returns></returns>
[HttpGet("chanlist")]
public IActionResult GetChanList()
{
return Ok(_cxManager.ListChannels(null));
}
}
}

View File

@ -0,0 +1,182 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Models;
using Yavsc.Models.Chat;
namespace Yavsc.Controllers
{
[Produces("application/json")]
[Route("api/ChatRoomAccessApi")]
public class ChatRoomAccessApiController : Controller
{
private readonly ApplicationDbContext _context;
public ChatRoomAccessApiController(ApplicationDbContext context)
{
_context = context;
}
// GET: api/ChatRoomAccessApi
[HttpGet, Authorize("AdministratorOnly")]
public IEnumerable<ChatRoomAccess> GetChatRoomAccess()
{
return _context.ChatRoomAccess;
}
// GET: api/ChatRoomAccessApi/5
[HttpGet("{id}", Name = "GetChatRoomAccess"), Authorize("AdministratorOnly")]
public async Task<IActionResult> GetChatRoomAccess([FromRoute] string id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
ChatRoomAccess chatRoomAccess = await _context.ChatRoomAccess.SingleAsync(m => m.ChannelName == id);
if (chatRoomAccess == null)
{
return NotFound();
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (uid != chatRoomAccess.UserId && uid != chatRoomAccess.Room.OwnerId
&& ! User.IsInRole(Constants.AdminGroupName))
{
ModelState.AddModelError("UserId","get refused");
return BadRequest(ModelState);
}
return Ok(chatRoomAccess);
}
// PUT: api/ChatRoomAccessApi/5
[HttpPut("{id}")]
public async Task<IActionResult> PutChatRoomAccess([FromRoute] string id, [FromBody] ChatRoomAccess chatRoomAccess)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (id != chatRoomAccess.ChannelName)
{
return BadRequest();
}
var room = _context.ChatRoom.First(channel => channel.Name == chatRoomAccess.ChannelName );
if (uid != room.OwnerId && ! User.IsInRole(Constants.AdminGroupName))
{
ModelState.AddModelError("ChannelName", "access put refused");
return BadRequest(ModelState);
}
_context.Entry(chatRoomAccess).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ChatRoomAccessExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return new StatusCodeResult(StatusCodes.Status204NoContent);
}
// POST: api/ChatRoomAccessApi
[HttpPost]
public async Task<IActionResult> PostChatRoomAccess([FromBody] ChatRoomAccess chatRoomAccess)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
var room = _context.ChatRoom.First(channel => channel.Name == chatRoomAccess.ChannelName );
if (room == null || (uid != room.OwnerId && ! User.IsInRole(Constants.AdminGroupName)))
{
ModelState.AddModelError("ChannelName", "access post refused");
return BadRequest(ModelState);
}
_context.ChatRoomAccess.Add(chatRoomAccess);
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException)
{
if (ChatRoomAccessExists(chatRoomAccess.ChannelName))
{
return new StatusCodeResult(StatusCodes.Status409Conflict);
}
else
{
throw;
}
}
return CreatedAtRoute("GetChatRoomAccess", new { id = chatRoomAccess.ChannelName }, chatRoomAccess);
}
// DELETE: api/ChatRoomAccessApi/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteChatRoomAccess([FromRoute] string id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
ChatRoomAccess chatRoomAccess = await _context.ChatRoomAccess.Include(acc => acc.Room).SingleAsync(m => m.ChannelName == id);
if (chatRoomAccess == null)
{
return NotFound();
}
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
var room = _context.ChatRoom.First(channel => channel.Name == chatRoomAccess.ChannelName );
if (room == null || (uid != room.OwnerId && chatRoomAccess.UserId != uid && ! User.IsInRole(Constants.AdminGroupName)))
{
ModelState.AddModelError("UserId", "access drop refused");
return BadRequest(ModelState);
}
_context.ChatRoomAccess.Remove(chatRoomAccess);
await _context.SaveChangesAsync();
return Ok(chatRoomAccess);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_context.Dispose();
}
base.Dispose(disposing);
}
private bool ChatRoomAccessExists(string id)
{
return _context.ChatRoomAccess.Count(e => e.ChannelName == id) > 0;
}
}
}

View File

@ -0,0 +1,163 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Chat;
namespace Yavsc.Controllers
{
[Produces("application/json")]
[Route("api/ChatRoomApi")]
public class ChatRoomApiController : Controller
{
private readonly ApplicationDbContext _context;
public ChatRoomApiController(ApplicationDbContext context)
{
_context = context;
}
// GET: api/ChatRoomApi
[HttpGet]
public IEnumerable<ChatRoom> GetChatRoom()
{
return _context.ChatRoom;
}
// GET: api/ChatRoomApi/5
[HttpGet("{id}", Name = "GetChatRoom")]
public async Task<IActionResult> GetChatRoom([FromRoute] string id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
ChatRoom chatRoom = await _context.ChatRoom.SingleAsync(m => m.Name == id);
if (chatRoom == null)
{
return NotFound();
}
return Ok(chatRoom);
}
// PUT: api/ChatRoomApi/5
[HttpPut("{id}")]
public async Task<IActionResult> PutChatRoom([FromRoute] string id, [FromBody] ChatRoom chatRoom)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != chatRoom.Name)
{
return BadRequest();
}
if (User.GetUserId() != chatRoom.OwnerId )
{
return BadRequest(new {error = "OwnerId"});
}
_context.Entry(chatRoom).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ChatRoomExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return new StatusCodeResult(StatusCodes.Status204NoContent);
}
// POST: api/ChatRoomApi
[HttpPost]
public async Task<IActionResult> PostChatRoom([FromBody] ChatRoom chatRoom)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (User.GetUserId() != chatRoom.OwnerId )
{
return BadRequest(new {error = "OwnerId"});
}
_context.ChatRoom.Add(chatRoom);
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException)
{
if (ChatRoomExists(chatRoom.Name))
{
return new StatusCodeResult(StatusCodes.Status409Conflict);
}
else
{
throw;
}
}
return CreatedAtRoute("GetChatRoom", new { id = chatRoom.Name }, chatRoom);
}
// DELETE: api/ChatRoomApi/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteChatRoom([FromRoute] string id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
ChatRoom chatRoom = await _context.ChatRoom.SingleAsync(m => m.Name == id);
if (chatRoom == null)
{
return NotFound();
}
if (User.GetUserId() != chatRoom.OwnerId )
{
if (!User.IsInRole(Constants.AdminGroupName))
return BadRequest(new {error = "OwnerId"});
}
_context.ChatRoom.Remove(chatRoom);
await _context.SaveChangesAsync();
return Ok(chatRoom);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_context.Dispose();
}
base.Dispose(disposing);
}
private bool ChatRoomExists(string id)
{
return _context.ChatRoom.Count(e => e.Name == id) > 0;
}
}
}

View File

@ -0,0 +1,145 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Relationship;
namespace Yavsc.Controllers
{
[Produces("application/json")]
[Route("api/cirle")]
public class CircleApiController : Controller
{
private readonly 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 BadRequest(ModelState);
}
Circle circle = await _context.Circle.SingleAsync(m => m.Id == id);
if (circle == null)
{
return NotFound();
}
return Ok(circle);
}
// PUT: api/CircleApi/5
[HttpPut("{id}")]
public async Task<IActionResult> PutCircle([FromRoute] long id, [FromBody] Circle circle)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != circle.Id)
{
return BadRequest();
}
_context.Entry(circle).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync(User.GetUserId());
}
catch (DbUpdateConcurrencyException)
{
if (!CircleExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return new StatusCodeResult(StatusCodes.Status204NoContent);
}
// POST: api/CircleApi
[HttpPost]
public async Task<IActionResult> PostCircle([FromBody] Circle circle)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.Circle.Add(circle);
try
{
await _context.SaveChangesAsync(User.GetUserId());
}
catch (DbUpdateException)
{
if (CircleExists(circle.Id))
{
return new StatusCodeResult(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 BadRequest(ModelState);
}
Circle circle = await _context.Circle.SingleAsync(m => m.Id == id);
if (circle == null)
{
return NotFound();
}
_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;
}
}
}

View File

@ -0,0 +1,126 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Abstract.Identity;
using Yavsc.Helpers;
using Yavsc.Models;
namespace Yavsc.Controllers
{
[Produces("application/json")]
[Route("api/ContactsApi")]
public class ContactsApiController : Controller
{
private readonly 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 BadRequest(ModelState);
}
if (id != clientProviderInfo.UserId)
{
return BadRequest();
}
_context.Entry(clientProviderInfo).State = EntityState.Modified;
try
{
_context.SaveChanges(User.GetUserId());
}
catch (DbUpdateConcurrencyException)
{
if (!ClientProviderInfoExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return new StatusCodeResult(StatusCodes.Status204NoContent);
}
// POST: api/ContactsApi
[HttpPost]
public IActionResult PostClientProviderInfo([FromBody] ClientProviderInfo clientProviderInfo)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.ClientProviderInfo.Add(clientProviderInfo);
try
{
_context.SaveChanges(User.GetUserId());
}
catch (DbUpdateException)
{
if (ClientProviderInfoExists(clientProviderInfo.UserId))
{
return new StatusCodeResult(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 BadRequest(ModelState);
}
ClientProviderInfo clientProviderInfo = _context.ClientProviderInfo.Single(m => m.UserId == id);
if (clientProviderInfo == null)
{
return NotFound();
}
_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;
}
}
}

View File

@ -0,0 +1,146 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Market;
namespace Yavsc.Controllers
{
[Produces("application/json")]
[Route("api/ServiceApi")]
public class ServiceApiController : Controller
{
private readonly 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 BadRequest(ModelState);
}
Service service = _context.Services.Single(m => m.Id == id);
if (service == null)
{
return NotFound();
}
return Ok(service);
}
// PUT: api/ServiceApi/5
[HttpPut("{id}"),Authorize(Constants.FrontOfficeGroupName)]
public IActionResult PutService(long id, [FromBody] Service service)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != service.Id)
{
return BadRequest();
}
_context.Entry(service).State = EntityState.Modified;
try
{
_context.SaveChanges(User.GetUserId());
}
catch (DbUpdateConcurrencyException)
{
if (!ServiceExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return new StatusCodeResult(StatusCodes.Status204NoContent);
}
// POST: api/ServiceApi
[HttpPost,Authorize(Constants.FrontOfficeGroupName)]
public IActionResult PostService([FromBody] Service service)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.Services.Add(service);
try
{
_context.SaveChanges(User.GetUserId());
}
catch (DbUpdateException)
{
if (ServiceExists(service.Id))
{
return new StatusCodeResult(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 BadRequest(ModelState);
}
Service service = _context.Services.Single(m => m.Id == id);
if (service == null)
{
return NotFound();
}
_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;
}
}
}

View File

@ -0,0 +1,183 @@
using Newtonsoft.Json;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Yavsc.Models;
using Yavsc.Models.IT.Fixing;
using Microsoft.EntityFrameworkCore;
namespace Yavsc.ApiControllers
{
[Produces("application/json")]
[Route("~/api/bug")]
public class BugApiController : Controller
{
private readonly ApplicationDbContext _context;
readonly ILogger _logger;
public BugApiController(ApplicationDbContext context, ILoggerFactory factory)
{
_logger = factory.CreateLogger<BugApiController>();
_context = context;
}
[HttpPost("signal")]
[Authorize]
public IActionResult Signal([FromBody] BugReport report)
{
_logger.LogWarning("bug reported : "+report.ExceptionObjectJson);
if (report.ExceptionObjectJson!=null)
if (report.ExceptionObjectJson.Length > 10240)
report.ExceptionObjectJson = report.ExceptionObjectJson.Substring(0,10240);
if (!ModelState.IsValid)
{
_logger.LogError("Bag request :");
_logger.LogError(JsonConvert.SerializeObject(ModelState));
return new BadRequestObjectResult(ModelState);
}
var existent = _context.Bug.FirstOrDefault( b =>
b.Description == report.ExceptionObjectJson &&
b.Title == report.Component &&
b.Status != BugStatus.Rejected
);
if (existent != null)
{
_logger.LogInformation("bug already reported");
return Ok(existent);
}
_logger.LogInformation("Filling a new bug report");
var bug = new Bug {
Title = report.Component,
Description = report.ExceptionObjectJson
};
_context.Bug.Add(bug);
_context.SaveChanges();
return CreatedAtRoute("GetBug", new { id = bug.Id }, bug);
}
// GET: api/BugApi
[HttpGet]
public IEnumerable<Bug> GetBug()
{
return _context.Bug;
}
// GET: api/bug/5
[HttpGet("{id}", Name = "GetBug")]
public async Task<IActionResult> GetBug([FromRoute] long id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Bug bug = await _context.Bug.SingleAsync(m => m.Id == id);
if (bug == null)
{
return NotFound();
}
return Ok(bug);
}
// PUT: api/BugApi/5
[HttpPut("{id}")]
public async Task<IActionResult> PutBug([FromRoute] long id, [FromBody] Bug bug)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != bug.Id)
{
return BadRequest();
}
_context.Entry(bug).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!BugExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return new StatusCodeResult(StatusCodes.Status204NoContent);
}
// POST: api/bug
[HttpPost]
public async Task<IActionResult> PostBug([FromBody] Bug bug)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.Bug.Add(bug);
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException)
{
if (BugExists(bug.Id))
{
return new StatusCodeResult(StatusCodes.Status409Conflict);
}
else
{
throw;
}
}
return CreatedAtRoute("GetBug", new { id = bug.Id }, bug);
}
// DELETE: api/BugApi/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteBug([FromRoute] long id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Bug bug = await _context.Bug.SingleAsync(m => m.Id == id);
if (bug == null)
{
return NotFound();
}
_context.Bug.Remove(bug);
await _context.SaveChangesAsync();
return Ok(bug);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_context.Dispose();
}
base.Dispose(disposing);
}
private bool BugExists(long id)
{
return _context.Bug.Count(e => e.Id == id) > 0;
}
}
}

View File

@ -0,0 +1,195 @@
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using Microsoft.EntityFrameworkCore;
using Yavsc.Models;
using Yavsc.Models.Account;
using Yavsc.ViewModels.Account;
using Yavsc.Helpers;
using Yavsc.Abstract.Identity;
using System.Diagnostics;
namespace Yavsc.WebApi.Controllers
{
[Route("~/api/account")]
[Authorize("ApiScope")]
public class ApiAccountController : Controller
{
private UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
readonly ApplicationDbContext _dbContext;
private readonly ILogger _logger;
public ApiAccountController(UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
RoleManager<IdentityRole> roleManager,
ILoggerFactory loggerFactory, ApplicationDbContext dbContext)
{
UserManager = userManager;
this.roleManager = roleManager;
_signInManager = signInManager;
_logger = loggerFactory.CreateLogger(nameof(ApiAccountController));
_dbContext = dbContext;
}
public UserManager<ApplicationUser> UserManager
{
get
{
return _userManager;
}
private set
{
_userManager = value;
}
}
private readonly RoleManager<IdentityRole> roleManager;
// POST api/Account/ChangePassword
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
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(RegisterModel 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("me")]
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)
.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).Select(r => r.RoleId).ToArray();
IdentityRole [] roles = _dbContext.Roles.Where(r=>userRoles.Contains(r.Id)).ToArray();
user.Roles = roles.Select(r=>r.Name).ToArray();
return Ok(user);
}
[HttpGet("myhost")]
public IActionResult MyHost ()
{
return Ok(new { host = Request.ForHost() });
}
/// <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("me")]
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")]
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);
}
}
}

View File

@ -0,0 +1,165 @@
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Abstract.Identity;
using Yavsc.Helpers;
using Yavsc.Models;
namespace Yavsc.Controllers
{
[Produces("application/json"),Authorize(Roles="Administrator")]
[Route("api/users")]
public class ApplicationUserApiController : Controller
{
private readonly ApplicationDbContext _context;
public ApplicationUserApiController(ApplicationDbContext context)
{
_context = context;
}
// GET: api/ApplicationUserApi
[HttpGet]
public IEnumerable<UserInfo> GetApplicationUser(int skip=0, int take = 25)
{
return _context.Users.Skip(skip).Take(take)
.Select(u=> new UserInfo{
UserId = u.Id,
UserName = u.UserName,
Avatar = u.Avatar});
}
[HttpGet("search/{pattern}")]
public IEnumerable<UserInfo> SearchApplicationUser(string pattern, int skip=0, int take = 25)
{
return _context.Users.Where(u => u.UserName.Contains(pattern))
.Skip(skip).Take(take)
.Select(u=> new UserInfo {
UserId = u.Id,
UserName = u.UserName,
Avatar = u.Avatar });
}
// GET: api/ApplicationUserApi/5
[HttpGet("{id}", Name = "GetApplicationUser")]
public IActionResult GetApplicationUser([FromRoute] string id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
ApplicationUser applicationUser = _context.Users.Single(m => m.Id == id);
if (applicationUser == null)
{
return NotFound();
}
return Ok(applicationUser);
}
// PUT: api/ApplicationUserApi/5
[HttpPut("{id}")]
public IActionResult PutApplicationUser(string id, [FromBody] ApplicationUser applicationUser)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != applicationUser.Id)
{
return BadRequest();
}
_context.Entry(applicationUser).State = EntityState.Modified;
try
{
_context.SaveChanges(User.GetUserId());
}
catch (DbUpdateConcurrencyException)
{
if (!ApplicationUserExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return new StatusCodeResult(StatusCodes.Status204NoContent);
}
// POST: api/ApplicationUserApi
[HttpPost]
public IActionResult PostApplicationUser([FromBody] ApplicationUser applicationUser)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.Users.Add(applicationUser);
try
{
_context.SaveChanges(User.GetUserId());
}
catch (DbUpdateException)
{
if (ApplicationUserExists(applicationUser.Id))
{
return new StatusCodeResult(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 BadRequest(ModelState);
}
ApplicationUser applicationUser = _context.Users.Single(m => m.Id == id);
if (applicationUser == null)
{
return NotFound();
}
_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;
}
}
}

View File

@ -0,0 +1,40 @@
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Linq;
using Yavsc.Models;
using Yavsc.Abstract.Identity;
using Yavsc.Helpers;
namespace Yavsc.ApiControllers.accounting
{
[Route("~/api/profile")]
public class ProfileApiController: Controller
{
readonly UserManager<ApplicationUser> _userManager;
readonly 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();
}
}
}

View File

@ -44,7 +44,7 @@ internal class Program
.AllowAnyMethod();
});
})
.AddControllers();
.AddControllersWithViews();
// accepts any access token issued by identity server
var authenticationBuilder = services.AddAuthentication()
@ -64,14 +64,22 @@ internal class Program
app
.UseRouting()
.UseAuthentication()
.UseAuthorization()
.UseCors("default");
.UseAuthorization().UseCors("default")
.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute()
.RequireAuthorization();
});
app.MapGet("/identity", (HttpContext context) =>
new JsonResult(context?.User?.Claims.Select(c => new { c.Type, c.Value }))
).RequireAuthorization("ApiScope");
await app.RunAsync();
}
};
}
}