-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
improved my api backend for LCP (pt 2)
- Loading branch information
1 parent
fe3aae5
commit 50d93c5
Showing
30 changed files
with
1,588 additions
and
67 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -28,7 +28,7 @@ public void Seed(Boolean isSeedData) | |
int seedval = 1000; | ||
|
||
List<Employee> listEmp = [ | ||
new Employee { EmployeeId = 1001, EmployeeFirstName = "Luis", EmployeeLastName = "Carvalho", EmployeeCity = "Braga", EmployeeCountry = "Portugal", EmployeeStateProvince = "", EmployeeName = "luigicardev96", EmployeeEmail = "[email protected]", EmployeeDateBirthday = DateTime.Parse("1996-06-04T00:00:00"), EmployeeDateRegistered = DateTime.Now, EmployeePassword = BC.HashPassword("luigi1234"), EmployeePin = 1234, EmployeeJob = "Programmer", EmployeePhoneNumber = "0123456789", EmployeePostalAddress = "1234-567", EmployeeZipCode = "1234-567", EmployeeRole = ENRoles.Administrator.ToString(), Products = null } | ||
new Employee { EmployeeId = 1001, EmployeeFirstName = "Luis", EmployeeLastName = "Carvalho", EmployeeCity = "Braga", EmployeeCountry = "Portugal", EmployeeStateProvince = "", EmployeeName = "admin", EmployeeEmail = "[email protected]", EmployeeDateBirthday = DateTime.Parse("1996-06-04T00:00:00"), EmployeeDateRegistered = DateTime.Now, EmployeePassword = BC.HashPassword("Kw@?7t3z704M6-6B92XG"), EmployeePin = BC.HashPassword("1234"), EmployeeJob = "Programmer", EmployeePhoneNumber = "0123456789", EmployeePostalAddress = "1234-567", EmployeeZipCode = "1234-567", EmployeeRole = ENRoles.Administrator.ToString(), Products = null } | ||
]; | ||
|
||
_mb.Entity<Employee>(b => { | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
using Microsoft.AspNetCore.Mvc; | ||
using LCPApi.Models; | ||
using BC = BCrypt.Net.BCrypt; | ||
using Microsoft.AspNetCore.Authorization; | ||
using LCPApi.Functions; | ||
using LCPApi.Context; | ||
using Microsoft.EntityFrameworkCore; | ||
|
||
namespace LCPApi.Controllers | ||
{ | ||
[Route("api/auth/login")] | ||
[ApiController] | ||
[AllowAnonymous] | ||
public class AuthController : ControllerBase | ||
{ | ||
private readonly IConfiguration _config; | ||
private readonly DBContext _dbc; | ||
public AuthController(IConfiguration config, DBContext dbc) | ||
{ | ||
_config = config; | ||
_dbc = dbc; | ||
} | ||
|
||
/// <summary> | ||
/// Login authentication for LCP Api | ||
/// </summary> | ||
/// <param name="userauth"></param> | ||
/// <returns></returns> | ||
[HttpPost] | ||
public async Task<IActionResult> DoAuth(UserAuth userauth) | ||
{ | ||
var users = await _dbc.Employees.SingleOrDefaultAsync(x => x.EmployeeName == userauth.UserAuthName); | ||
|
||
if(users == null || !CheckIfPassOrPinIsValid(userauth.UserAuthPassword, users.EmployeePassword)) { | ||
return Problem($"The authentication of this user {userauth.UserAuthName} is invalid!"); | ||
} | ||
|
||
return Ok(AuthFunctions.GenToken(_config, userauth)); | ||
} | ||
|
||
private bool CheckIfPassOrPinIsValid(string originalPass, string hashedPass) { | ||
return BC.Verify(originalPass, hashedPass, false, BCrypt.Net.HashType.SHA512); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,128 @@ | ||
using System.Text; | ||
using System.Security.Cryptography; | ||
|
||
namespace LCPApi.Functions; | ||
|
||
public class ProductKeyClass { | ||
public Guid? Id { get; set; } = Guid.NewGuid(); | ||
public string? SecretKey { get; set; } | ||
public string? PrivateKey { get; set; } | ||
public string? LicenseKey { get; set; } | ||
public string? Msg { get; set; } | ||
public bool? IsValid { get; set; } | ||
public DateTime? DateExp { get; set; } | ||
public DateTime? DateNow { get; set; } | ||
} | ||
|
||
public static class ProductKeyFunctions | ||
{ | ||
public async static Task<List<ProductKeyClass>> GetProductKey() { | ||
//src: https://dotnetfiddle.net/srGTKN | ||
//var secretKey = CreatePrivateKey(); | ||
var secretKey = "+bCzRidhVxwx5TKpkz14nf5cL+BMH+ahZIOCy4bPVzdXWhysq+tZfOtrHsw9vdg5vKes/lVwzHIyquvmz9taDg=="; | ||
var privateKey = CreatePrivateKey(); | ||
var licenseKey = CreateLicense(secretKey); | ||
var isValid = ValidateLicense(licenseKey, secretKey); | ||
var validStatus = isValid ? "valid" : "invalid"; | ||
Random rnd = new Random(); | ||
|
||
return await Task.FromResult(new List<ProductKeyClass>() { | ||
new ProductKeyClass() { | ||
Id = Guid.NewGuid(), | ||
SecretKey = secretKey, | ||
PrivateKey = privateKey, | ||
LicenseKey = licenseKey, | ||
Msg = $"This product license key is {validStatus}", | ||
IsValid = isValid, | ||
DateExp = DateTime.UtcNow.AddMonths(rnd.Next(1, 13)), | ||
DateNow = DateTime.UtcNow | ||
} | ||
}); | ||
} | ||
|
||
static string CreatePrivateKey() | ||
{ | ||
// Step 01: Create your private hashkey and store it on the database | ||
byte[] hashKey = GenerateRandomCryptographicBytes(64); | ||
|
||
// Convert the key to base64 so you can easily store it on the database. | ||
// This should be kept private and never leaves your control. | ||
var base64Secret = Convert.ToBase64String(hashKey); | ||
|
||
Console.WriteLine($"Private Key = {base64Secret}"); | ||
|
||
return base64Secret; | ||
} | ||
|
||
static string CreateLicense(string secretKey) | ||
{ | ||
// Generate a license key of 10 chars (split into groups of 5) | ||
var licenseKey = Guid.NewGuid().ToString().ToUpper().Replace("-", "").Substring(0, 15); | ||
|
||
Console.WriteLine($"licenseKey = {licenseKey}"); | ||
|
||
// Generate a Hmac license using secretkey | ||
var storedHmacOnDB = CalculateHmac(licenseKey, secretKey).ToUpper(); | ||
var HMACTruncated = storedHmacOnDB.Substring(0, 15); | ||
|
||
Console.WriteLine($"HMAC = {HMACTruncated}"); | ||
|
||
var licenseAndHMAC = InsertHyphen($"{licenseKey}{HMACTruncated}"); | ||
|
||
Console.WriteLine($"Final User License = {licenseAndHMAC}"); | ||
|
||
return licenseAndHMAC; | ||
} | ||
|
||
static bool ValidateLicense(string licenseKey, string secretKey) | ||
{ | ||
var tmp = licenseKey.Split('-'); | ||
|
||
var license = $"{tmp[0]}{tmp[1]}{tmp[2]}"; | ||
var licenseHmac = $"{tmp[3]}{tmp[4]}{tmp[5]}"; | ||
|
||
string calculatedHmac = CalculateHmac(license, secretKey); | ||
var HMACTruncated = calculatedHmac.ToUpper().Substring(0, 15); | ||
|
||
bool isValid = licenseHmac.Equals(HMACTruncated, StringComparison.OrdinalIgnoreCase); | ||
|
||
return isValid; | ||
} | ||
|
||
static string InsertHyphen(string input, int everyNthChar = 5) | ||
{ | ||
var sb = new StringBuilder(); | ||
for (int i = 0; i < input.Length; i++) | ||
{ | ||
sb.Append(input[i]); | ||
if ((i + 1) % everyNthChar == 0 && i != input.Length - 1) | ||
{ | ||
sb.Append("-"); | ||
} | ||
} | ||
return sb.ToString(); | ||
} | ||
|
||
static byte[] GenerateRandomCryptographicBytes(int keyLength) | ||
{ | ||
byte[] key = new byte[64]; | ||
using (RandomNumberGenerator rng = RandomNumberGenerator.Create()) | ||
{ | ||
rng.GetBytes(key); | ||
} | ||
return key; | ||
} | ||
|
||
static string CalculateHmac(string data, string hashKeyBase64) | ||
{ | ||
var byteArray = Convert.FromBase64String(hashKeyBase64); | ||
return CalculateHmac(data, byteArray); | ||
} | ||
|
||
static string CalculateHmac(string data, byte[] hashKey) | ||
{ | ||
var hmac = new HMACMD5(hashKey); | ||
byte[] hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(data)); | ||
return BitConverter.ToString(hashBytes).Replace("-", "").ToLower(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
using Microsoft.AspNetCore.SignalR; | ||
|
||
namespace LCPApi.Hubs; | ||
|
||
public class DataHub : Hub { | ||
public async Task SendData(string user, string data) { | ||
await Clients.All.SendAsync("ReceiveData", user, data); | ||
} | ||
} |
Oops, something went wrong.