Compare commits

..

No commits in common. "c5fb04b44a48ae9383f2fe4d3a7aec264b9db6fa" and "065086bfa22bb16436d2d0ccf772f4ee094a0473" have entirely different histories.

3 changed files with 36 additions and 118 deletions

View File

@ -9,27 +9,22 @@ public static partial class APIHandler
{ {
App App
//============MISC================= //============MISC=================
.Map("/updatecache", cache => .Map("/updatecache",cache=>{
{ cache.Run(async runner=>{
cache.Run(async runner =>
{
await UpdateCache(); await UpdateCache();
await runner.WriteJsonResponse(StatusCodes.Status200OK,"Cache Updated."); await runner.WriteJsonResponse(StatusCodes.Status200OK,"Cache Updated.");
}); });
}) })
//===========UNITS================= //===========UNITS=================
.Map("/getunits", units => .Map("/getunits", units =>{
{
units.Run(async runner=> units.Run(async runner=>
{ {
if (!await runner.RequestValidated(2)) return; if (!await runner.RequestValidated(2)) return;
await runner.WriteJsonResponse( StatusCodes.Status200OK, "Success", Deployments); await runner.WriteJsonResponse( StatusCodes.Status200OK, "Success", Deployments);
}); });
}) })
.Map("/chunit", unit => .Map("/chunit", unit =>{
{ unit.Run(async runner=>{
unit.Run(async runner =>
{
if (!await runner.RequestValidated(2, "POST", true)) return; if (!await runner.RequestValidated(2, "POST", true)) return;
if(await runner.TryGetBodyJsonAsync(["deplid", "unitkerja"], CTS.Token) is Dictionary<string, JsonElement> InElement) if(await runner.TryGetBodyJsonAsync(["deplid", "unitkerja"], CTS.Token) is Dictionary<string, JsonElement> InElement)
{ {
@ -48,8 +43,7 @@ public static partial class APIHandler
await runner.WriteJsonResponse(StatusCodes.Status404NotFound,"Deployment ID not found."); await runner.WriteJsonResponse(StatusCodes.Status404NotFound,"Deployment ID not found.");
return; return;
} }
_ = await RunNonQueryAsync(CS, "UPDATE deployment SET unitkerja = @uk WHERE deplid = @id", Comm => _ = await RunNonQueryAsync(CS,"UPDATE deployment SET unitkerja = @uk WHERE deplid = @id",Comm=>{
{
Comm.Parameters.AddWithValue("@id", CorrectDeployment.DeplID); Comm.Parameters.AddWithValue("@id", CorrectDeployment.DeplID);
Comm.Parameters.AddWithValue("@uk", CorrectDeployment.UnitKerja); Comm.Parameters.AddWithValue("@uk", CorrectDeployment.UnitKerja);
},CTS.Token); },CTS.Token);
@ -58,10 +52,8 @@ public static partial class APIHandler
} }
}); });
}) })
.Map("/addunit", unit => .Map("/addunit", unit =>{
{ unit.Run(async runner=>{
unit.Run(async runner =>
{
if (!await runner.RequestValidated(2, "POST", true)) return; if (!await runner.RequestValidated(2, "POST", true)) return;
if(await runner.TryGetBodyJsonAsync(["unitkerja"], CTS.Token) is Dictionary<string, JsonElement> InElement) if(await runner.TryGetBodyJsonAsync(["unitkerja"], CTS.Token) is Dictionary<string, JsonElement> InElement)
{ {
@ -71,8 +63,7 @@ public static partial class APIHandler
await runner.WriteJsonResponse(StatusCodes.Status400BadRequest, "Unit Kerja can't be empty string."); await runner.WriteJsonResponse(StatusCodes.Status400BadRequest, "Unit Kerja can't be empty string.");
return; return;
} }
short DeplID = (short)await RunScalarAsync(CS, "INSERT INTO deployment OUTPUT INSERTED.deplid VALUES (@uk)", Comm => short DeplID = (short)await RunScalarAsync(CS,"INSERT INTO deployment OUTPUT INSERTED.deplid VALUES (@uk)",Comm=>{
{
Comm.Parameters.AddWithValue("@uk", UnitKerja); Comm.Parameters.AddWithValue("@uk", UnitKerja);
},CTS.Token); },CTS.Token);
Deployment Inserted = new(DeplID,UnitKerja); Deployment Inserted = new(DeplID,UnitKerja);
@ -83,18 +74,14 @@ public static partial class APIHandler
}); });
}) })
//============AGENTS============== //============AGENTS==============
.Map("/getagents", agents => .Map("/getagents", agents=>{
{ agents.Run(async runner=>{
agents.Run(async runner =>
{
if (!await runner.RequestValidated(2)) return; if (!await runner.RequestValidated(2)) return;
await runner.WriteJsonResponse(StatusCodes.Status200OK,"Success",Agents); await runner.WriteJsonResponse(StatusCodes.Status200OK,"Success",Agents);
}); });
}) })
.Map("/addagent", agent => .Map("/addagent", agent=>{
{ agent.Run(async runner=>{
agent.Run(async runner =>
{
if (!await runner.RequestValidated(1, "POST", true)) return; if (!await runner.RequestValidated(1, "POST", true)) return;
if (await runner.TryGetBodyJsonAsync(["agentid", "name", "jabatan", "deplid", "skangkat", "tmt", "skper", "tgper", "vision", "mission", "photo", "createuser", "uname", "pass", "level"], CTS.Token) is Dictionary<string, JsonElement> InElement) if (await runner.TryGetBodyJsonAsync(["agentid", "name", "jabatan", "deplid", "skangkat", "tmt", "skper", "tgper", "vision", "mission", "photo", "createuser", "uname", "pass", "level"], CTS.Token) is Dictionary<string, JsonElement> InElement)
{ {
@ -118,7 +105,7 @@ public static partial class APIHandler
if (AgentID.Equals(string.Empty) || if (AgentID.Equals(string.Empty) ||
Name.Equals(string.Empty) || Name.Equals(string.Empty) ||
Jabatan.Equals(string.Empty) || Jabatan.Equals(string.Empty) ||
//DeploymentID.Equals(0) || DeploymentID.Equals(0) ||
SKAngkat.Equals(string.Empty) || SKAngkat.Equals(string.Empty) ||
TMT.Equals(DateOnly.Parse("1970-01-01")) || TMT.Equals(DateOnly.Parse("1970-01-01")) ||
(!SKPer.Equals(string.Empty) && TGPer is null) || (!SKPer.Equals(string.Empty) && TGPer is null) ||
@ -180,53 +167,10 @@ public static partial class APIHandler
); );
string OutMessage = CreateUser ? "New Agent and respective User Account created" : "New Agent created. User account creation is possible."; string OutMessage = CreateUser ? "New Agent and respective User Account created" : "New Agent created. User account creation is possible.";
await runner.WriteJsonResponse(StatusCodes.Status201Created, OutMessage, CreateUser?new SafeUser(UName,AgentID,Level,true):NewAgent); await runner.WriteJsonResponse(StatusCodes.Status201Created, OutMessage, CreateUser?new SafeUser(UName,AgentID,Level,true):NewAgent);
// await runner.WriteJsonResponse(200, "OK", NewAgent);
} }
}); });
}) })
.Map("/chagent", agent =>
{
agent.Run(async runner =>
{
if (!await runner.RequestValidated(0, "POST", true)) return;
if (await runner.TryGetBodyJsonAsync(["agentid", "updates"], CTS.Token) is Dictionary<string, JsonElement> InElement)
{
if (InElement["updates"].ValueKind != JsonValueKind.Object) return;
string AgentID = InElement["agentid"].GetString() ?? string.Empty;
JsonElement UpdateFields = InElement["updates"];
using SqlDataReader Updated = await RunReaderAsync(CS, "", Comm =>
{
StringBuilder CommandBuilder = new();
CommandBuilder.Append("UPDATE agents SET");
foreach (JsonProperty Prop in UpdateFields.EnumerateObject())
{
Comm.Parameters.AddWithValue($"@p{Prop.Name}", Prop.Value.ValueKind == JsonValueKind.String ? Prop.Value.GetString() == "DBNull" ? DBNull.Value : Prop.Value.GetString() : Prop.Value.GetInt16());
CommandBuilder.Append($" [{Prop.Name}] = @p{Prop.Name},");
}
Comm.Parameters.AddWithValue("@pagentid", AgentID);
CommandBuilder.Remove(CommandBuilder.Length - 1, 1);
CommandBuilder.Append(" OUTPUT INSERTED.* WHERE agentid = @pagentid");
Comm.CommandText = CommandBuilder.ToString();
}, CTS.Token);
Agent UpAgent = (await Updated.ToListAsync<Agent>(a => new
(
AgentID,
(string)a["name"],
(string)a["jabatan"],
(short)a["deplid"],
(string)a["skangkat"],
DateOnly.FromDateTime((DateTime)a["tmt"]),
a["skperubahan"] == DBNull.Value ? null : (string)a["skperubahan"],
a["tgperubahan"] == DBNull.Value ? null : DateOnly.FromDateTime((DateTime)a["tgperubahan"]),
a["vision"] == DBNull.Value ? null : (string)a["vision"],
a["mission"] == DBNull.Value ? null : (string)a["mission"],
a["photourl"] == DBNull.Value ? null : (string)a["photourl"]
), CTS.Token))[0];
await runner.WriteJsonResponse(StatusCodes.Status202Accepted, "Data updated.", UpAgent);
}
});
})
//=========ACTIVITIES=============
; ;
} }

View File

@ -21,10 +21,6 @@ public static class Auth
{ {
return TryGetUser(context, out SafeUser user) && user.Level <= requiredLevel; return TryGetUser(context, out SafeUser user) && user.Level <= requiredLevel;
} }
internal static bool IsAuthorized(HttpContext context, string Username)
{
return TryGetUser(context, out SafeUser user) && user.Username == Username;
}
internal static Task RejectUnauthorized(HttpContext context) internal static Task RejectUnauthorized(HttpContext context)
{ {

View File

@ -248,16 +248,13 @@ internal static class HttpContextExtensions
{ {
internal static async Task<bool> RequestValidated(this HttpContext Context, int RequiredLevel = 0, string ValidMethod = "GET", bool CheckJson = false) internal static async Task<bool> RequestValidated(this HttpContext Context, int RequiredLevel = 0, string ValidMethod = "GET", bool CheckJson = false)
{ {
if (!ValidMethod.Equals(Context.Request.Method, StringComparison.OrdinalIgnoreCase)) if (!ValidMethod.Equals(Context.Request.Method, StringComparison.OrdinalIgnoreCase) ||
(CheckJson && !Context.Request.HasJsonContentType()))
{ {
await Context.WriteJsonResponse(StatusCodes.Status405MethodNotAllowed, "Method Not Allowed."); await Context.WriteJsonResponse(StatusCodes.Status405MethodNotAllowed, "Method Not Allowed.");
return false; return false;
} }
if (CheckJson && !Context.Request.HasJsonContentType())
{
await Context.WriteJsonResponse(StatusCodes.Status415UnsupportedMediaType, $"Supports only explicitly set application/json content-type, but received {Context.Request.ContentType ?? "request with no content-type set"} instead.");
return false;
}
if (!Auth.IsAuthorized(Context, RequiredLevel)) if (!Auth.IsAuthorized(Context, RequiredLevel))
{ {
await Context.WriteJsonResponse(StatusCodes.Status401Unauthorized, "Unauthorized."); await Context.WriteJsonResponse(StatusCodes.Status401Unauthorized, "Unauthorized.");
@ -265,25 +262,6 @@ internal static class HttpContextExtensions
} }
return true; return true;
} }
internal static async Task<bool> RequestValidated(this HttpContext Context, string RequiredUserName, string ValidMethod = "GET", bool CheckJson = false)
{
if (!ValidMethod.Equals(Context.Request.Method, StringComparison.OrdinalIgnoreCase))
{
await Context.WriteJsonResponse(StatusCodes.Status405MethodNotAllowed, "Method Not Allowed.");
return false;
}
if (CheckJson && !Context.Request.HasJsonContentType())
{
await Context.WriteJsonResponse(StatusCodes.Status415UnsupportedMediaType, $"Supports only explicitly set application/json content-type, but received {Context.Request.ContentType ?? "request with no content-type set"} instead.");
return false;
}
if (!Auth.IsAuthorized(Context, RequiredUserName))
{
await Context.WriteJsonResponse(StatusCodes.Status401Unauthorized, "Unauthorized.");
return false;
}
return true;
}
internal static async Task WriteJsonResponse(this HttpContext Context, int Status, string Message, object Data) internal static async Task WriteJsonResponse(this HttpContext Context, int Status, string Message, object Data)
{ {
Context.Response.StatusCode = Status; Context.Response.StatusCode = Status;