Skip to content

Commit

Permalink
#218 - Integrating identity into API project.
Browse files Browse the repository at this point in the history
  • Loading branch information
maraf committed Feb 24, 2019
1 parent 6e7dfb7 commit 03eef81
Show file tree
Hide file tree
Showing 22 changed files with 1,019 additions and 91 deletions.
70 changes: 70 additions & 0 deletions src/Money.Api/Controllers/UserController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Money.Models;
using Neptuo;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Money.Controllers
{
[Route("api/[controller]/[action]")]
public class UserController : ControllerBase
{
private readonly JwtOptions configuration;
private readonly UserManager<ApplicationUser> userManager;
private readonly JwtSecurityTokenHandler tokenHandler;

public UserController(IOptions<JwtOptions> configuration, UserManager<ApplicationUser> userManager, JwtSecurityTokenHandler tokenHandler)
{
Ensure.NotNull(configuration, "configuration");
Ensure.NotNull(userManager, "userManager");
Ensure.NotNull(tokenHandler, "tokenHandler");
this.configuration = configuration.Value;
this.userManager = userManager;
this.tokenHandler = tokenHandler;
}

[HttpPost]
public async Task<IActionResult> Login([FromBody] LoginRequest model)
{
ApplicationUser user = await userManager.FindByNameAsync(model.UserName);
if (user != null)
{
if (await userManager.CheckPasswordAsync(user, model.Password))
{
var claims = new[]
{
new Claim(ClaimTypes.Name, model.UserName)
};

var credentials = new SigningCredentials(configuration.GetSecurityKey(), SecurityAlgorithms.HmacSha256);
var expiry = DateTime.Now.Add(configuration.GetExpiry());

var token = new JwtSecurityToken(
configuration.Issuer,
configuration.Issuer,
claims,
expires: expiry,
signingCredentials: credentials
);

var response = new LoginResponse()
{
Token = tokenHandler.WriteToken(token)
};

return Ok(response);
}
}

return BadRequest();
}
}
}
64 changes: 0 additions & 64 deletions src/Money.Api/Controllers/UserLoginController.cs

This file was deleted.

2 changes: 1 addition & 1 deletion src/Money.Api/Controllers/ValuesController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Money.Api.Controllers
namespace Money.Controllers
{
[Route("api/[controller]")]
[ApiController]
Expand Down
73 changes: 73 additions & 0 deletions src/Money.Api/Data/ApplicationDataSeeder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using Money.Commands;
using Money.Models;
using Neptuo;
using Neptuo.Commands;
using Neptuo.Models.Keys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Money.Data
{
public static class ApplicationDataSeeder
{
public static IWebHost SeedData(this IWebHost host)
{
try
{
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
var userManager = services.GetService<UserManager<ApplicationUser>>();
var db = services.GetService<ApplicationDbContext>();

db.Database.EnsureCreated();

if (!userManager.Users.Any())
userManager.CreateAsync(new ApplicationUser(ClaimsPrincipalExtensions.DemoUserName), ClaimsPrincipalExtensions.DemoUserPassword).Wait();
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}

return host;
}

public static async Task InitializeAsync(UserManager<ApplicationUser> userManager, ICommandDispatcher commands)
{
IdentityResult userResult = await userManager.CreateAsync(
new ApplicationUser(ClaimsPrincipalExtensions.DemoUserName),
ClaimsPrincipalExtensions.DemoUserPassword
);

if (!userResult.Succeeded)
throw Ensure.Exception.InvalidOperation("Unnable to create demo user.");

ApplicationUser user = await userManager.FindByNameAsync(ClaimsPrincipalExtensions.DemoUserName);
if (user == null)
throw Ensure.Exception.InvalidOperation("Unnable find created demo user.");

IKey userKey = StringKey.Create(user.Id, "User");

await commands.HandleAsync(WrapCommand(userKey, new CreateCurrency("USD", "$")));
await commands.HandleAsync(WrapCommand(userKey, new CreateCategory("Car", "Gas etc.", Color.FromArgb(255, 145, 206, 234))));
await commands.HandleAsync(WrapCommand(userKey, new CreateCategory("Home", "DIY", Color.FromArgb(255, 207, 180, 141))));
await commands.HandleAsync(WrapCommand(userKey, new CreateCategory("Food", "Ingredients for home made meals", Color.FromArgb(255, 155, 237, 144))));
}

private static Envelope<T> WrapCommand<T>(IKey userKey, T command)
{
var envelope = Envelope.Create(command);
envelope.Metadata.Add("UserKey", userKey);
return envelope;
}
}
}
27 changes: 27 additions & 0 deletions src/Money.Api/Data/ApplicationDbContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Money.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Money.Data
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}

protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);

// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
}
}
Loading

0 comments on commit 03eef81

Please sign in to comment.