Compare commits
3 Commits
f86fda4a6d
...
1a809acbfb
Author | SHA1 | Date | |
---|---|---|---|
1a809acbfb | |||
5e99d68d1e | |||
9bd04d6fdd |
102
APIHandler.cs
102
APIHandler.cs
@ -1,12 +1,21 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace perubahan;
|
||||
|
||||
public static class APIHandler
|
||||
public static partial class APIHandler
|
||||
{
|
||||
public static void Handle(IApplicationBuilder App)
|
||||
{
|
||||
App
|
||||
//============MISC=================
|
||||
.Map("/updatecache",cache=>{
|
||||
cache.Run(async runner=>{
|
||||
_ = await UpdateCache();
|
||||
await WriteJsonResponse(runner,StatusCodes.Status200OK,"Cache Updated.");
|
||||
});
|
||||
})
|
||||
//===========UNITS=================
|
||||
.Map("/getunits", units =>{
|
||||
units.Run(async runner=>{
|
||||
if (!await RequestValidated(runner,2)) return;
|
||||
@ -63,13 +72,102 @@ public static class APIHandler
|
||||
}
|
||||
});
|
||||
})
|
||||
|
||||
//============AGENTS==============
|
||||
.Map("/getagents", agents=>{
|
||||
agents.Run(async runner=>{
|
||||
if (!await RequestValidated(runner,2)) return;
|
||||
await WriteJsonResponse(runner,StatusCodes.Status200OK,"Success",Agents);
|
||||
});
|
||||
})
|
||||
.Map("/addagent", agent=>{
|
||||
agent.Run(async runner=>{
|
||||
if (!await RequestValidated(runner, 1, "POST", true)) return;
|
||||
if (await TryGetBodyJsonAsync(runner, ["agentid", "name", "jabatan", "deplid", "skangkat", "tmt", "skper", "tgper", "vision", "mission", "photo", "createuser", "uname", "pass", "level"], CTS.Token) is Dictionary<string, JsonElement> InElement)
|
||||
{
|
||||
string AgentID = InElement["agentid"].GetString() ?? string.Empty;
|
||||
string Name = InElement["nama"].GetString() ?? string.Empty;
|
||||
string Jabatan = InElement["jabatan"].GetString() ?? string.Empty;
|
||||
short DeploymentID = InElement["deplid"].GetInt16();
|
||||
string SKAngkat = InElement["skangkat"].GetString() ?? string.Empty;
|
||||
DateTime TMT = DateTime.Parse(InElement["tmt"].GetString() ?? "1970-01-01");
|
||||
string SKPer = InElement["skper"].GetString() ?? string.Empty;
|
||||
DateTime? TGPer = InElement["tgper"].GetString()?.Length > 0 ? DateTime.Parse(InElement["tgper"].GetString()!) : null;
|
||||
string Vision = InElement["vision"].GetString() ?? "-";
|
||||
string Mission = InElement["mission"].GetString() ?? "-";
|
||||
string Photo = InElement["photo"].GetString() ?? string.Empty;
|
||||
string PhotoURL = string.Empty;
|
||||
bool CreateUser = InElement["createuser"].GetBoolean();
|
||||
string UName = InElement["uname"].GetString() ?? string.Empty;
|
||||
string PlainPass = InElement["pass"].GetString() ?? string.Empty;
|
||||
byte Level = InElement["level"].GetByte();
|
||||
Match PhotoMatch = Base64Regex().Match(Photo.ToLower());
|
||||
if (AgentID.Equals(string.Empty) ||
|
||||
Name.Equals(string.Empty) ||
|
||||
Jabatan.Equals(string.Empty) ||
|
||||
DeploymentID.Equals(0) ||
|
||||
SKAngkat.Equals(string.Empty) ||
|
||||
TMT.Equals(DateOnly.Parse("1970-01-01")) ||
|
||||
(!SKPer.Equals(string.Empty) && TGPer is null) ||
|
||||
(CreateUser && UName.Equals(string.Empty)) ||
|
||||
(CreateUser && PlainPass.Equals(string.Empty)) ||
|
||||
(!Photo.Equals(string.Empty) && !PhotoMatch.Success) ||
|
||||
(await RequestValidated(runner, Level, "POST")))
|
||||
{
|
||||
await WriteJsonResponse(runner, StatusCodes.Status400BadRequest, "One or more input(s) are not acceptable, in an unsupported format, or an attempt to create user account of a higher level than the creator is made.");
|
||||
return;
|
||||
}
|
||||
if (!Photo.Equals(string.Empty))
|
||||
{
|
||||
string Format = PhotoMatch.Groups["format"].Value.ToLowerInvariant();
|
||||
string Data = PhotoMatch.Groups["data"].Value;
|
||||
byte[] ImageBytes = Convert.FromBase64String(Data);
|
||||
uint CRC32Hash = Crc32.Compute(ImageBytes);
|
||||
string PhotoFileName = $"{CRC32Hash:X8}.{(Format == "jpeg" ? "jpg" : Format)}";
|
||||
string PhotoPath = Path.Combine(AppContext.BaseDirectory, "/wwwroot/assets/images/uploads", PhotoFileName);
|
||||
if (!File.Exists(PhotoPath)) await File.WriteAllBytesAsync(PhotoPath, ImageBytes, CTS.Token);
|
||||
PhotoURL = Path.Combine("/assets/images/uploads", PhotoFileName);
|
||||
}
|
||||
await RunTransactionAsync(CS, async (Conn, Trans) =>
|
||||
{
|
||||
using (SqlCommand CreateAgent = Conn.CreateCommand())
|
||||
{
|
||||
CreateAgent.Transaction = Trans;
|
||||
CreateAgent.CommandText = "INSERT INTO agents VALUE(@agid, @nama, @jabt, @deid, @skng, @tmt, @skpr, @tmpr, @visi, @misi, @poto)";
|
||||
CreateAgent.Parameters.AddWithValue("@agid", AgentID);
|
||||
CreateAgent.Parameters.AddWithValue("@nama", Name);
|
||||
CreateAgent.Parameters.AddWithValue("@jabt", Jabatan);
|
||||
CreateAgent.Parameters.AddWithValue("@deid", DeploymentID);
|
||||
CreateAgent.Parameters.AddWithValue("@skng", SKAngkat);
|
||||
CreateAgent.Parameters.AddWithValue("@tmt", TMT);
|
||||
CreateAgent.Parameters.AddWithValue("@skpr", SKPer.Equals(string.Empty) ? DBNull.Value : SKPer);
|
||||
CreateAgent.Parameters.AddWithValue("@tmpr", SKPer.Equals(string.Empty) ? DBNull.Value : TGPer);
|
||||
CreateAgent.Parameters.AddWithValue("@visi", Vision);
|
||||
CreateAgent.Parameters.AddWithValue("@misi", Mission);
|
||||
CreateAgent.Parameters.AddWithValue("@poto", PhotoURL.Equals(string.Empty) ? DBNull.Value : PhotoURL);
|
||||
_ = await CreateAgent.ExecuteNonQueryAsync();
|
||||
}
|
||||
if (CreateUser)
|
||||
{
|
||||
string HashedPass = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(PlainPass)));
|
||||
using (SqlCommand CreateUser = Conn.CreateCommand())
|
||||
{
|
||||
CreateUser.Transaction = Trans;
|
||||
CreateUser.CommandText = "INSERT INTO useraccounts VALUES(@unam, @pass, @agid, @levl, 1)";
|
||||
CreateUser.Parameters.AddWithValue("@unam", UName);
|
||||
CreateUser.Parameters.AddWithValue("@pass", HashedPass);
|
||||
CreateUser.Parameters.AddWithValue("@agid", AgentID);
|
||||
CreateUser.Parameters.AddWithValue("@levl", Level);
|
||||
_ = await CreateUser.ExecuteNonQueryAsync();
|
||||
}
|
||||
}
|
||||
}, CTS.Token
|
||||
);
|
||||
string OutMessage = CreateUser ? "New Agent and respective User Account created" : "New Agent created. User account creation is possible.";
|
||||
await WriteJsonResponse(runner, StatusCodes.Status201Created, OutMessage);
|
||||
}
|
||||
});
|
||||
})
|
||||
;
|
||||
}
|
||||
|
||||
}
|
||||
|
29
Commons.cs
29
Commons.cs
@ -7,6 +7,7 @@ global using System.Text.Json.Nodes;
|
||||
global using static perubahan.Commons;
|
||||
global using static perubahan.Logging;
|
||||
global using static perubahan.Middlewares;
|
||||
global using static perubahan.Regices;
|
||||
global using System.Collections.Concurrent;
|
||||
global using System.Security.Cryptography;
|
||||
using System.Text.Json;
|
||||
@ -15,7 +16,7 @@ namespace perubahan;
|
||||
|
||||
internal static class Commons
|
||||
{
|
||||
internal readonly static string VerNum = "0.1.250509.2301";
|
||||
internal readonly static string VerNum = "0.1.250515.1559";
|
||||
|
||||
internal static ConcurrentDictionary<string,User> UserAccounts = [];
|
||||
internal static List<Deployment> Deployments = [];
|
||||
@ -341,3 +342,29 @@ internal static class DataReaderExtensions
|
||||
return list;
|
||||
}
|
||||
}
|
||||
public static class Crc32
|
||||
{
|
||||
static readonly uint[] Table;
|
||||
|
||||
static Crc32()
|
||||
{
|
||||
Table = new uint[256];
|
||||
const uint poly = 0xEDB88320;
|
||||
for (uint i = 0; i < Table.Length; i++)
|
||||
{
|
||||
uint crc = i;
|
||||
for (int j = 0; j < 8; j++)
|
||||
crc = (crc & 1) != 0 ? (crc >> 1) ^ poly : crc >> 1;
|
||||
Table[i] = crc;
|
||||
}
|
||||
}
|
||||
|
||||
public static uint Compute(byte[] bytes)
|
||||
{
|
||||
uint crc = 0xFFFFFFFF;
|
||||
foreach (byte b in bytes)
|
||||
crc = (crc >> 8) ^ Table[(crc ^ b) & 0xFF];
|
||||
return ~crc;
|
||||
}
|
||||
}
|
||||
|
||||
|
14
Partials.cs
14
Partials.cs
@ -1,13 +1,15 @@
|
||||
using System;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace perubahan;
|
||||
internal partial record Agent(string AgentID, string Name, string Jabatan, short DeplID, string SKAngkat, DateOnly TMT, string? SKPerb, DateOnly? TMUbah, string? Vision, string? Mission, string? PhotoURL);
|
||||
internal partial record ApiResponse(int Status, string Message, object Data);
|
||||
internal partial record Deployment(short DeplID, string UnitKerja);
|
||||
internal partial record LoginUser(string Username, string Password);
|
||||
internal partial record PasswdUser(string Username, string PlainPassword);
|
||||
internal partial record SafeUser(string Username, string Name, byte Level, bool Active){
|
||||
internal partial record SafeUser(string Username, string Name, byte Level, bool Active) {
|
||||
internal static SafeUser FromUser(User Source)
|
||||
{
|
||||
return new(Source.Username, Source.Name, Source.Level, Source.Active);
|
||||
@ -30,5 +32,11 @@ internal partial record User(string Username, string Name, string Password, byte
|
||||
//////////-------------LISTS--------------//////////
|
||||
[JsonSerializable(typeof(List<Agent>))]
|
||||
[JsonSerializable(typeof(List<Deployment>))]
|
||||
[JsonSourceGenerationOptions(GenerationMode =JsonSourceGenerationMode.Default, PropertyNameCaseInsensitive = true, PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
|
||||
internal partial class SGContext : JsonSerializerContext{}
|
||||
[JsonSourceGenerationOptions(GenerationMode = JsonSourceGenerationMode.Default, PropertyNameCaseInsensitive = true, PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
|
||||
internal partial class SGContext : JsonSerializerContext { }
|
||||
|
||||
internal static partial class Regices
|
||||
{
|
||||
[GeneratedRegex(@"data:image/(?<format>.+?);base64,(?<data>.+)")]
|
||||
internal static partial Regex Base64Regex();
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user