Skip to content

Commit

Permalink
refactoring in progress and migration to new project system
Browse files Browse the repository at this point in the history
  • Loading branch information
clarkis117 committed Mar 12, 2017
1 parent 07b3c0b commit 52f0a0d
Show file tree
Hide file tree
Showing 69 changed files with 1,154 additions and 60,530 deletions.
103 changes: 103 additions & 0 deletions GenericMvc.Auth/Controllers/AuthApi.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
using GenericMvc.Models.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;

namespace GenericMvc.Auth.Controllers
{
/// <summary>
/// In terms of registering users, this is merely designed for registering non-privileged users
/// In general, the use of this class is designed for non-privileged Users or privileged user whom already registered via the account controller class
///
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TUser">The type of the user.</typeparam>
/// <seealso cref="Microsoft.AspNetCore.Mvc.Controller" />
/// <seealso cref="GenericMvcModels.Controllers.IAuthApiController" />
[Route("/api/[controller]/[action]/"), Authorize]
public class AuthApi<TKey, TUser, TRegisterViewModel, TLoginViewModel> : Controller, IAuthApi<TRegisterViewModel, TLoginViewModel>
where TLoginViewModel : LoginViewModel
where TRegisterViewModel : RegisterViewModel
where TKey : IEquatable<TKey>
where TUser : Models.User, new()
{
private readonly SignInManager<TUser> _signInManager;

private readonly UserManager<TUser> _userManager;

private readonly ILogger<TUser> _logger;

public AuthApi(SignInManager<TUser> signInManager, UserManager<TUser> userManager, ILogger<TUser> logger)
{
_signInManager = signInManager ?? throw new ArgumentNullException(nameof(signInManager));

_userManager = userManager ?? throw new ArgumentNullException(nameof(userManager));

_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}

[HttpPost, AllowAnonymous]
public async Task<IActionResult> Login([FromBody] TLoginViewModel viewModel)
{
if (viewModel == null || !ModelState.IsValid)
return BadRequest();

// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(viewModel.UserName, viewModel.Password, viewModel.IsPersistent, lockoutOnFailure: false);

if (result.Succeeded)
return Json(result);

//no way to two factor bots at the moment
if (result.RequiresTwoFactor)
return Unauthorized();

if (result.IsLockedOut)
return new StatusCodeResult(403);

return Unauthorized();
}

[HttpPost]
public async Task<IActionResult> Logout()
{
await _signInManager.SignOutAsync();

return Ok();
}

[HttpPost, AllowAnonymous]
public async Task<IActionResult> Register([FromBody] TRegisterViewModel viewModel)
{
if (viewModel == null && !ModelState.IsValid)
return BadRequest(ModelState);

//todo make this
var user = new TUser()
{
UserName = viewModel.UserName
};

user.FromRegisterViewModel(viewModel);

//if (model.Password != model.ConfirmPassword)
//return BadRequest("Supplied Passwords are not the same");

var result = await _userManager.CreateAsync(user, viewModel.Password);

if (!result.Succeeded)
return new StatusCodeResult(500);

await _signInManager.SignInAsync(user, viewModel.IsPersistent);

_logger.LogInformation($"{user.UserName} create a new account with password.");

return Json(result);
}
}
}
20 changes: 20 additions & 0 deletions GenericMvc.Auth/Controllers/IAuthApi.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using GenericMvc.Models.ViewModels;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace GenericMvc.Auth.Controllers
{
public interface IAuthApi<TRegisterViewModel, TLoginViewModel>
where TLoginViewModel : LoginViewModel
where TRegisterViewModel : RegisterViewModel
{
Task<IActionResult> Register([FromBody] TRegisterViewModel viewModel);

Task<IActionResult> Login([FromBody] TLoginViewModel viewModel);

Task<IActionResult> Logout();
}
}
17 changes: 17 additions & 0 deletions GenericMvc.Auth/GenericMvc.Auth.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard1.6</TargetFramework>
<NetStandardImplicitPackageVersion>1.6.1</NetStandardImplicitPackageVersion>
<PackageTargetFallback Condition=" '$(TargetFramework)' == 'netstandard1.6' ">$(PackageTargetFallback);portable-net451+win8</PackageTargetFallback>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authorization" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Identity" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="1.1.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\GenericMvc.Models\GenericMvc.Models.csproj" />
</ItemGroup>
</Project>
14 changes: 14 additions & 0 deletions GenericMvc.Auth/Models/IUser.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using GenericMvc.Models.ViewModels;
using System;
using System.Collections.Generic;
using System.Text;

namespace GenericMvc.Auth.Models
{
public interface IUser
{
string UserName { get; }

void FromRegisterViewModel<TRegisterViewModel>(TRegisterViewModel viewModel) where TRegisterViewModel : RegisterViewModel;
}
}
23 changes: 23 additions & 0 deletions GenericMvc.Auth/Models/User.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using GenericMvc.Models.ViewModels;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using System;

namespace GenericMvc.Auth.Models
{
/// <summary>
/// Base abstract class to represent non-privileged users
/// These users have no roles or claims external to their identity
/// They should only be allowed to edit data that lives under their data object
/// They should only be allowed to view data that is not access controlled
/// </summary>
/// <seealso cref="Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUser" />
public abstract class User : IdentityUser, IUser
{
public User(): base()
{

}

public abstract void FromRegisterViewModel<TRegisterViewModel>(TRegisterViewModel viewModel) where TRegisterViewModel : RegisterViewModel;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
using System.Text;
using System.Threading.Tasks;

namespace GenericMvc.Client
namespace GenericMvc.Clients
{
public class ApiClient<T, TKey> : IDisposable, IApiClient<T, TKey>
where T : class, IModel<TKey>
Expand Down
25 changes: 13 additions & 12 deletions src/GenericMvc/AuthClient.cs → GenericMvc.Clients/AuthClient.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using GenericMvc.ViewModels.UserManager.Account;

using GenericMvc.Models.ViewModels;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
Expand All @@ -10,7 +11,7 @@
using System.Text;
using System.Threading.Tasks;

namespace GenericMvc.Client
namespace GenericMvc.Clients
{
public class JsonContent : StringContent
{
Expand Down Expand Up @@ -39,9 +40,9 @@ public interface IAuthClient

//param methods
//todo: fix
Task<bool> Register(BaseRegisterViewModel model);
Task<bool> Register(RegisterViewModel model);

Task<string> Login(BaseLoginViewModel model);
Task<string> Login(LoginViewModel model);

Task<bool> Logout();
}
Expand Down Expand Up @@ -87,7 +88,7 @@ public class AuthClient : IAuthClient, IDisposable

private readonly RouteInfo _info;

private BaseLoginViewModel _loginInfo;
private LoginViewModel _loginInfo;

private readonly bool _cacheLoginInfo;

Expand Down Expand Up @@ -141,17 +142,17 @@ public static string ProcessCookies(IEnumerable<string> cookies)
return concatCookies.ToString();
}

public Task<BaseLoginViewModel> GetLoginInfoFromFile(string path)
public Task<LoginViewModel> GetLoginInfoFromFile(string path)
{
if (path != null && System.IO.File.Exists(path))
{
return Task.Run(() =>
{
BaseLoginViewModel loginInfo;
LoginViewModel loginInfo;

using (var reader = new StreamReader(System.IO.File.OpenRead(path)))
{
loginInfo = (BaseLoginViewModel)_serailizer.Deserialize(reader, typeof(BaseLoginViewModel));
loginInfo = (LoginViewModel)_serailizer.Deserialize(reader, typeof(LoginViewModel));
}

return loginInfo;
Expand All @@ -163,11 +164,11 @@ public Task<BaseLoginViewModel> GetLoginInfoFromFile(string path)
}
}

public Task<bool> SaveLoginInfoToFile(string path, BaseLoginViewModel loginInfo)
public Task<bool> SaveLoginInfoToFile(string path, LoginViewModel loginInfo)
{
if (path != null)
{
BaseLoginViewModel login;
LoginViewModel login;

if (_cacheLoginInfo == false && loginInfo != null)
{
Expand Down Expand Up @@ -204,7 +205,7 @@ public Task<bool> SaveLoginInfoToFile(string path, BaseLoginViewModel loginInfo)
}
}

public async Task<string> Login(BaseLoginViewModel model)
public async Task<string> Login(LoginViewModel model)
{
if (model != null)
{
Expand Down Expand Up @@ -248,7 +249,7 @@ public async Task<string> Login()
}

//todo: fix
public async Task<bool> Register(BaseRegisterViewModel registrationInfo)
public async Task<bool> Register(RegisterViewModel registrationInfo)
{
if (registrationInfo != null)
{
Expand Down
9 changes: 9 additions & 0 deletions GenericMvc.Clients/GenericMvc.Clients.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard1.4</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="9.0.1" />
<ProjectReference Include="..\GenericMvc.Models\GenericMvc.Models.csproj" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
using System.Net;
using System.Net.Http;

namespace GenericMvc.Client
namespace GenericMvc.Clients
{
public interface IApiClient<T, TKey>
where T : class
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using GenericMvc.Models;
using GenericMvc.Data.Controllers;
using GenericMvc.Models;
using GenericMvc.Repositories;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
Expand All @@ -11,7 +12,7 @@
namespace GenericMvc.Controllers
{
//todo this could use cleaned up
public abstract class IFileApiController<T, TKey> : BaseApiController<T, TKey>
public abstract class IFileApiController<T, TKey> : Api<T, TKey>
where T : class, IModelFile<TKey>
where TKey : IEquatable<TKey>
{
Expand All @@ -26,7 +27,7 @@ public IFileApiController(IRepository<T> repository, ILogger<T> logger) :base(re
protected bool CheckFileName { get; set; } = true;

//add check to see if it is create or update
public override async Task<bool> IsValid(T Model, ModelStateDictionary ModelState, bool Updating = false)
protected override async Task<bool> IsValid(T Model, ModelStateDictionary ModelState, bool Updating = false)
{
if (await base.IsValid(Model, ModelState))
{
Expand Down Expand Up @@ -81,7 +82,7 @@ public override async Task<bool> IsValid(T Model, ModelStateDictionary ModelStat
}
}

public override async Task<bool> IsValid(T[] Models, ModelStateDictionary ModelState, bool updating = false)
protected override async Task<bool> IsValid(IEnumerable<T> Models, ModelStateDictionary ModelState, bool updating = false)
{
if (ModelState.IsValid)
{
Expand Down Expand Up @@ -229,11 +230,11 @@ public async Task<IActionResult> PairedDelete([FromQuery] TKey id, [FromQuery] T
}
catch (Exception ex)
{
string message = "Deleting Item Failed";
string message = $"Delete:{typeOfT.Name} by Id Failed";

this.Logger.LogError(FormatLogMessage(message, this.Request));
Logger.LogError(0, ex, message);

throw new Exception(FormatExceptionMessage(this, message), ex);
throw new Exception(message, ex);
}
}
}
Expand Down
14 changes: 14 additions & 0 deletions GenericMvc.Files/GenericMvc.Files.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard1.6</TargetFramework>
<NetStandardImplicitPackageVersion>1.6.1</NetStandardImplicitPackageVersion>
<PackageTargetFallback Condition=" '$(TargetFramework)' == 'netstandard1.6' ">$(PackageTargetFallback);portable-net451+win8</PackageTargetFallback>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.Reactive" Version="3.1.1" />
<PackageReference Include="System.Reactive.Linq" Version="3.1.1" />
<PackageReference Include="Mime-Detective" Version="0.0.2" />
<ProjectReference Include="..\GenericMvc.Models\GenericMvc.Models.csproj" />
<ProjectReference Include="..\src\GenericMvc.Data\GenericMvc.Data.csproj" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using MimeDetective;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
Expand Down Expand Up @@ -31,10 +29,8 @@ public enum EncodingType : byte { RawBytes, Base64, NonNewtonsoftBase64 };
/// </summary>
public class DataFile : IModel<string>
{
[JsonIgnore]
public System.IO.FileInfo _fileInfo;

[JsonIgnore]
public MimeDetective.FileType _fileType;

public DataFile()
Expand Down Expand Up @@ -226,7 +222,6 @@ public virtual async Task<DataFile> Initialize(bool loadFile = false, EncodingTy
/// encoding type
/// needed to decode data from over the wire transmissions
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public EncodingType EncodingType { get; set; } = EncodingType.Base64;

/// <summary>
Expand Down
Loading

0 comments on commit 52f0a0d

Please sign in to comment.