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,29 +9,24 @@ public static partial class APIHandler
{
App
//============MISC=================
.Map("/updatecache", cache =>
{
cache.Run(async runner =>
{
.Map("/updatecache",cache=>{
cache.Run(async runner=>{
await UpdateCache();
await runner.WriteJsonResponse(StatusCodes.Status200OK, "Cache Updated.");
await runner.WriteJsonResponse(StatusCodes.Status200OK,"Cache Updated.");
});
})
//===========UNITS=================
.Map("/getunits", units =>
{
units.Run(async runner =>
.Map("/getunits", units =>{
units.Run(async runner=>
{
if (!await runner.RequestValidated(2)) return;
await runner.WriteJsonResponse(StatusCodes.Status200OK, "Success", Deployments);
await runner.WriteJsonResponse( StatusCodes.Status200OK, "Success", Deployments);
});
})
.Map("/chunit", unit =>
{
unit.Run(async runner =>
{
.Map("/chunit", unit =>{
unit.Run(async runner=>{
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)
{
Deployment CorrectDeployment = new(
InElement["deplid"].GetInt16(),
@ -42,28 +37,25 @@ public static partial class APIHandler
await runner.WriteJsonResponse(StatusCodes.Status400BadRequest, "Unit Kerja can't be empty string.");
return;
}
int i = Deployments.FindIndex(depl => depl.DeplID == CorrectDeployment.DeplID);
if (i < 0)
int i = Deployments.FindIndex(depl=>depl.DeplID == CorrectDeployment.DeplID);
if(i<0)
{
await runner.WriteJsonResponse(StatusCodes.Status404NotFound, "Deployment ID not found.");
await runner.WriteJsonResponse(StatusCodes.Status404NotFound,"Deployment ID not found.");
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("@uk", CorrectDeployment.UnitKerja);
}, CTS.Token);
},CTS.Token);
Deployments[i] = CorrectDeployment;
await runner.WriteJsonResponse(StatusCodes.Status202Accepted, "Data updated.", Deployments[i]);
await runner.WriteJsonResponse(StatusCodes.Status202Accepted,"Data updated.",Deployments[i]);
}
});
})
.Map("/addunit", unit =>
{
unit.Run(async runner =>
{
.Map("/addunit", unit =>{
unit.Run(async runner=>{
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)
{
string UnitKerja = InElement["unitkerja"].GetString() ?? "";
if (UnitKerja.Length < 1)
@ -71,30 +63,25 @@ public static partial class APIHandler
await runner.WriteJsonResponse(StatusCodes.Status400BadRequest, "Unit Kerja can't be empty string.");
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);
}, CTS.Token);
Deployment Inserted = new(DeplID, UnitKerja);
},CTS.Token);
Deployment Inserted = new(DeplID,UnitKerja);
Deployments.Add(Inserted);
// EventsMarker.CacheUpdates = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString("X");
await runner.WriteJsonResponse(StatusCodes.Status201Created, "Data Created.", Inserted);
await runner.WriteJsonResponse(StatusCodes.Status201Created,"Data Created.",Inserted);
}
});
})
//============AGENTS==============
.Map("/getagents", agents =>
{
agents.Run(async runner =>
{
.Map("/getagents", agents=>{
agents.Run(async runner=>{
if (!await runner.RequestValidated(2)) return;
await runner.WriteJsonResponse(StatusCodes.Status200OK, "Success", Agents);
await runner.WriteJsonResponse(StatusCodes.Status200OK,"Success",Agents);
});
})
.Map("/addagent", agent =>
{
agent.Run(async runner =>
{
.Map("/addagent", agent=>{
agent.Run(async runner=>{
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)
{
@ -118,7 +105,7 @@ public static partial class APIHandler
if (AgentID.Equals(string.Empty) ||
Name.Equals(string.Empty) ||
Jabatan.Equals(string.Empty) ||
//DeploymentID.Equals(0) ||
DeploymentID.Equals(0) ||
SKAngkat.Equals(string.Empty) ||
TMT.Equals(DateOnly.Parse("1970-01-01")) ||
(!SKPer.Equals(string.Empty) && TGPer is null) ||
@ -128,7 +115,7 @@ public static partial class APIHandler
(!await runner.RequestValidated(Level, "POST"))
)
{
await runner.WriteJsonResponse(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.");
await runner.WriteJsonResponse( 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))
@ -179,54 +166,11 @@ public static partial class APIHandler
}, CTS.Token
);
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;
}
internal static bool IsAuthorized(HttpContext context, string Username)
{
return TryGetUser(context, out SafeUser user) && user.Username == Username;
}
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)
{
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.");
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))
{
await Context.WriteJsonResponse(StatusCodes.Status401Unauthorized, "Unauthorized.");
@ -265,25 +262,6 @@ internal static class HttpContextExtensions
}
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)
{
Context.Response.StatusCode = Status;