Skip to content
Permalink
Browse files

Use roles for API authorisation. Closes #9

Remove ApiUser model (no longer used)
  • Loading branch information...
gariasf committed Mar 9, 2019
1 parent 9cbb548 commit 3507396b9dd3a0c468c8929bfd74b8c08e4e74bb
@@ -5,32 +5,22 @@

namespace VuelingExam.Bussiness.Facade.Controllers
{
[Authorize]
[Route("api/[controller]/[Action]")]
[ApiController]
public class AuthenticationController : ControllerBase
{
private readonly IAuth<ApiUser> AuthenticationBL;
private readonly IAuth<Client> AuthenticationBL;

public AuthenticationController(IAuth<ApiUser> repository)
public AuthenticationController(IAuth<Client> repository)
{
AuthenticationBL = repository;
}

// GET api/authentication/login
[AllowAnonymous]
[HttpPost]
public ActionResult<string> Login(ApiUser credentials)
public ActionResult<string> Login(Client credentials)
{
return Ok(AuthenticationBL.Login(credentials));
}

// GET api/authentication/register
[AllowAnonymous]
[HttpPost]
public ActionResult<bool> Register(ApiUser crendentials)
{
return Ok(AuthenticationBL.Register(crendentials));
}
}
}
@@ -21,27 +21,31 @@ public InsuranceController(IInsurance insuranceBL)
}

[ConnectionFilter]
[Authorize(Roles = "user, admin")]
[HttpGet("{clientId:guid}")]
public ActionResult<Client> GetClientById(Guid clientId)
{
return Ok(InsuranceBL.GetClientData(clientId));
}

[ConnectionFilter]
[Authorize(Roles = "user, admin")]
[HttpGet("{clientName}")]
public ActionResult<Client> GetClientByName(string clientName)
{
return Ok(InsuranceBL.GetClientData(clientName));
}

[ConnectionFilter]
[Authorize(Roles = "admin")]
[HttpGet("{policyId:Guid}")]
public ActionResult<Client> GetClientFromPolicy(Guid policyId)
{
return Ok(InsuranceBL.GetClientFromPolicy(policyId));
}

[ConnectionFilter]
[Authorize(Roles = "admin")]
[HttpGet("{clientId:Guid}")]
public ActionResult<List<Policy>> GetClientPolicies(Guid clientId)
{
@@ -18,7 +18,7 @@ protected override void Load(ContainerBuilder builder)

builder
.RegisterType<AuthenticationBL>()
.As<IAuth<ApiUser>>()
.As<IAuth<Client>>()
.SingleInstance();

builder
@@ -9,18 +9,18 @@

namespace VuelingExam.Bussiness.Logic
{
public class AuthenticationBL : IAuth<ApiUser>
public class AuthenticationBL : IAuth<Client>
{
private readonly IAuthRepository<ApiUser> Repository;
private readonly IAuthRepository<Client> Repository;
private readonly ILogger Logger;

public AuthenticationBL(IAuthRepository<ApiUser> repository, ILogger logger)
public AuthenticationBL(IAuthRepository<Client> repository, ILogger logger)
{
Repository = repository;
Logger = logger;
}

public string Login(ApiUser credentials)
public string Login(Client credentials)
{
Logger.Debug(StringResources.DebugMethod + System.Reflection.MethodBase.GetCurrentMethod().Name +
StringResources.DebugClass + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
@@ -31,15 +31,7 @@ public string Login(ApiUser credentials)
{
using (var transactionScope = new TransactionScope(TransactionScopeOption.RequiresNew))
{
ApiUser user = Repository.GetEntityByUsername(credentials.Username);
var isCredentialsValid = user.Password == credentials.Password;

if (!isCredentialsValid)
{
return null;
}

token = Repository.GenerateToken(user).Token;
token = Repository.GenerateToken(credentials);

transactionScope.Complete();
}
@@ -53,30 +45,5 @@ public string Login(ApiUser credentials)

return token;
}

public bool Register(ApiUser credentials)
{
Logger.Debug(StringResources.DebugMethod + System.Reflection.MethodBase.GetCurrentMethod().Name +
StringResources.DebugClass + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

bool result;

try
{
using (var transactionScope = new TransactionScope(TransactionScopeOption.RequiresNew))
{
result = Repository.Register(credentials);
transactionScope.Complete();
}
}
catch (VuelingDaoException e)
{
Logger.Error(e.Message);
Logger.Information(e.StackTrace);
throw new VuelingBussinessException(e.Message, e.InnerException);
}

return result;
}
}
}
@@ -4,6 +4,7 @@
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Transactions;
using VuelingExam.Bussiness.Logic.Interfaces;
using VuelingExam.Bussiness.Logic.Interfaces.Crud;
using VuelingExam.Bussiness.Logic.Resources;
@@ -71,8 +72,8 @@ public void StoreListToDatabase()

ClientList.ForEach(client =>
{
Logger.Debug(client.ToString());
Repository.Add(client);

Repository.Add(client);
});

Logger.Information("Done!");
@@ -4,6 +4,7 @@
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Transactions;
using VuelingExam.Bussiness.Logic.Interfaces;
using VuelingExam.Bussiness.Logic.Interfaces.Crud;
using VuelingExam.Bussiness.Logic.Resources;
@@ -73,7 +74,8 @@ public void StoreListToDatabase()

PolicyList.ForEach(policy =>
{
Repository.Add(policy);

Repository.Add(policy);
});

Logger.Information("Done!");
@@ -3,6 +3,5 @@
public interface IAuth<in T>
{
string Login(T credentials);
bool Register(T credentials);
}
}
@@ -21,7 +21,7 @@ protected override void Load(ContainerBuilder builder)

builder.
RegisterType<AuthenticationRepository>()
.As<IAuthRepository<ApiUser>>();
.As<IAuthRepository<Client>>();

base.Load(builder);
}

This file was deleted.

Oops, something went wrong.
@@ -1,7 +1,5 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;

namespace VuelingExam.Common.Logic.Utils
{
@@ -2,10 +2,6 @@
{
public interface IAuthRepository<T>
{
T GenerateToken(T credentials);

bool Register(T credentials);

T GetEntityByUsername(string userName);
string GenerateToken(T credentials);
}
}
@@ -14,7 +14,7 @@

namespace VuelingExam.RepositoryLogic
{
public class AuthenticationRepository : IAuthRepository<ApiUser>
public class AuthenticationRepository : IAuthRepository<Client>
{

private readonly static string ConnectionString = ConfigHelper.Config["dbConnectionString"];
@@ -26,7 +26,7 @@ public AuthenticationRepository(ILogger logger)
Logger = logger;
}

public ApiUser GenerateToken(ApiUser credentials)
public string GenerateToken(Client credentials)
{
Logger.Debug(StringResources.DebugMethod + System.Reflection.MethodBase.GetCurrentMethod().Name +
StringResources.DebugClass + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
@@ -37,114 +37,17 @@ public ApiUser GenerateToken(ApiUser credentials)
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, credentials.Id.ToString())
new Claim(ClaimTypes.Name, credentials.Name),
new Claim(ClaimTypes.Role, credentials.Role.ToString())
}),
Expires = DateTime.UtcNow.AddDays(7),
Expires = DateTime.UtcNow.AddMinutes(30),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};

var token = tokenHandler.CreateToken(tokenDescriptor);
var createdToken = tokenHandler.CreateToken(tokenDescriptor);

credentials.Token = tokenHandler.WriteToken(token);

return credentials;
}

public bool Register(ApiUser credentials)
{
Logger.Debug(StringResources.DebugMethod + System.Reflection.MethodBase.GetCurrentMethod().Name +
StringResources.DebugClass + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

var UserId = 0;

try
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
using (var command = new SqlCommand($"INSERT dbo.ApiUser VALUES (@Username, @Password); SELECT SCOPE_IDENTITY()", connection))
{
connection.Open();
command.Parameters.Add("@Username", SqlDbType.VarChar, 150).Value = credentials.Username;
command.Parameters.Add("@Password", SqlDbType.VarChar, 500).Value = credentials.Password;
UserId = Convert.ToInt32(command.ExecuteScalar());
}
}
}
catch (InvalidOperationException e)
{
Logger.Error(e.Message);
Logger.Information(e.StackTrace);
throw new VuelingDaoException(e.Message, e.InnerException);
}
catch (SqlException e)
{
Logger.Error(e.Message);
Logger.Information(e.StackTrace);
throw new VuelingDaoException(e.Message, e.InnerException);
}
catch (InvalidCastException e)
{
Logger.Error(e.Message);
Logger.Information(e.StackTrace);
throw new VuelingDaoException(e.Message, e.InnerException);
}

return UserId != 0;
}

public ApiUser GetEntityByUsername(string userName)
{
Logger.Debug(StringResources.DebugMethod + System.Reflection.MethodBase.GetCurrentMethod().Name +
StringResources.DebugClass + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

ApiUser foundUser = null;

try
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
using (SqlCommand command = new SqlCommand($"SELECT * FROM dbo.ApiUser WHERE Username = @Username;", connection))
{
connection.Open();

command.Parameters.Add("@Username", SqlDbType.VarChar, 150).Value = userName;

using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
var record = (IDataRecord)reader;
foundUser = new ApiUser
{
Id = Convert.ToInt32(record["Id"]),
Username = record["Username"].ToString(),
Password = record["Password"].ToString(),
};
}
}
}
}
}
catch (InvalidOperationException e)
{
Logger.Error(e.Message);
Logger.Information(e.StackTrace);
throw new VuelingDaoException(e.Message, e.InnerException);
}
catch (SqlException e)
{
Logger.Error(e.Message);
Logger.Information(e.StackTrace);
throw new VuelingDaoException(e.Message, e.InnerException);
}
catch (InvalidCastException e)
{
Logger.Error(e.Message);
Logger.Information(e.StackTrace);
throw new VuelingDaoException(e.Message, e.InnerException);
}

return foundUser;
return tokenHandler.WriteToken(createdToken);
}
}
}
Oops, something went wrong.

0 comments on commit 3507396

Please sign in to comment.
You can’t perform that action at this time.