WIP separation Web et API
This commit is contained in:
parent
1d6cad7bef
commit
49826eae4a
55 changed files with 68 additions and 95 deletions
195
src/Api/Controllers/accounting/AccountController.cs
Normal file
195
src/Api/Controllers/accounting/AccountController.cs
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
165
src/Api/Controllers/accounting/ApplicationUserApiController.cs
Normal file
165
src/Api/Controllers/accounting/ApplicationUserApiController.cs
Normal 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
40
src/Api/Controllers/accounting/ProfileApiController.cs
Normal file
40
src/Api/Controllers/accounting/ProfileApiController.cs
Normal 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue