add duty-time and poi (จาก google maps ไปก่อน)

This commit is contained in:
Suphonchai Phoonsawat 2023-11-09 14:35:08 +07:00
parent 43932f742b
commit 78f8c0813c
30 changed files with 3395 additions and 4 deletions

View file

@ -0,0 +1,61 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>349e3764-b6a4-4dce-969a-e6976cd10d3e</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
<DockerfileContext>.</DockerfileContext>
<RootNamespace>BMA.EHR.Command.Service</RootNamespace>
</PropertyGroup>
<ItemGroup>
<None Include="..\.dockerignore" Link=".dockerignore">
<DependentUpon>$(DockerDefaultDockerfile)</DependentUpon>
</None>
</ItemGroup>
<ItemGroup>
<PackageReference Include="iTextSharp" Version="5.5.13.3" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.9" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="7.0.9" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="5.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer" Version="5.1.0" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.9" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.9">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.IdentityModel.Logging" Version="6.31.0" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.18.1" />
<PackageReference Include="runtime.osx.10.10-x64.CoreCompat.System.Drawing" Version="6.0.5.128" />
<PackageReference Include="Serilog.AspNetCore" Version="7.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="4.1.0" />
<PackageReference Include="Sentry.AspNetCore" Version="3.33.1" />
<PackageReference Include="Serilog.Enrichers.Environment" Version="2.2.0" />
<PackageReference Include="Serilog.Exceptions" Version="8.4.0" />
<PackageReference Include="Serilog.Sinks.Debug" Version="2.0.0" />
<PackageReference Include="Serilog.Sinks.Elasticsearch" Version="9.0.3" />
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="6.5.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BMA.EHR.Infrastructure\BMA.EHR.Infrastructure.csproj" />
</ItemGroup>
<ItemGroup>
<Content Update="wwwroot\index.html">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Update="wwwroot\keycloak.js">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Update="wwwroot\keycloak.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>

View file

@ -0,0 +1,85 @@
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Reflection;
namespace BMA.EHR.Command.Service
{
public class ConfigureSwaggerOptions : IConfigureNamedOptions<SwaggerGenOptions>
{
private readonly IApiVersionDescriptionProvider _provider;
public ConfigureSwaggerOptions(
IApiVersionDescriptionProvider provider)
{
_provider = provider;
}
public void Configure(SwaggerGenOptions options)
{
// add swagger document for every API version discovered
foreach (var description in _provider.ApiVersionDescriptions)
{
options.EnableAnnotations();
options.SwaggerDoc(
description.GroupName,
CreateVersionInfo(description));
}
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
In = ParameterLocation.Header,
Description = "Please enter a valid token",
Name = "Authorization",
Type = SecuritySchemeType.Http,
BearerFormat = "JWT",
Scheme = "Bearer"
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[]{}
}
});
// generate the XML docs that'll drive the swagger docs
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
options.IncludeXmlComments(xmlPath);
}
public void Configure(string name, SwaggerGenOptions options)
{
Configure(options);
}
private OpenApiInfo CreateVersionInfo(
ApiVersionDescription desc)
{
var info = new OpenApiInfo()
{
Title = "BMA EHR Leave Service Document",
Version = desc.ApiVersion.ToString(),
};
if (desc.IsDeprecated)
{
info.Description += " This API version has been deprecated. Please use one of the new APIs available from the explorer.";
}
return info;
}
}
}

View file

@ -0,0 +1,114 @@
using BMA.EHR.Application.Repositories;
using BMA.EHR.Application.Repositories.Leaves;
using BMA.EHR.Command.Service.DTOs.POI;
using BMA.EHR.Domain.Common;
using BMA.EHR.Infrastructure.Persistence;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Swashbuckle.AspNetCore.Annotations;
using System.Security.Claims;
namespace BMA.EHR.Command.Service.Controllers
{
[Route("api/v{version:apiVersion}/leave/check-in")]
[ApiVersion("1.0")]
[ApiController]
[Produces("application/json")]
[Authorize]
[SwaggerTag("API ระบบลงเวลาทำงาน")]
public class CheckInController : BaseController
{
#region " Fields "
private readonly DutyTimeRepository _repository;
private readonly LeaveDbContext _context;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IWebHostEnvironment _hostingEnvironment;
private readonly IConfiguration _configuration;
private readonly UserProfileRepository _userProfileRepository;
#endregion
#region " Constuctor and Destructor "
public CheckInController(DutyTimeRepository repository,
LeaveDbContext context,
IHttpContextAccessor httpContextAccessor,
IWebHostEnvironment hostingEnvironment,
IConfiguration configuration,
UserProfileRepository userProfileRepository)
{
_repository = repository;
_context = context;
_httpContextAccessor = httpContextAccessor;
_hostingEnvironment = hostingEnvironment;
_configuration = configuration;
_userProfileRepository = userProfileRepository;
}
#endregion
#region " Properties "
private string? UserId => _httpContextAccessor?.HttpContext?.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
private string? FullName => _httpContextAccessor?.HttpContext?.User?.FindFirst("name")?.Value;
private bool? PlacementAdmin => _httpContextAccessor?.HttpContext?.User?.IsInRole("placement1");
private Guid OcId
{
get
{
if (UserId != null || UserId != "")
return _userProfileRepository.GetUserOCId(Guid.Parse(UserId!));
else
return Guid.Empty;
}
}
#endregion
#region " Methods "
[HttpPost("locations")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
[AllowAnonymous]
public async Task<ActionResult<ResponseObject>> ListPOIAsync([FromBody] GetPOIDto data)
{
var api_url = $"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={data.Lat},{data.Lon}&types=point_of_interest&radius=50000&sensor=false&language=th&key=AIzaSyDXKvpU4hinlCKGOEJUgLDbx9yCSZe3woc";
using (var client = new HttpClient())
{
var req = new HttpRequestMessage(HttpMethod.Get, api_url);
var res = await client.SendAsync(req);
var result = await res.Content.ReadAsStringAsync();
var poi_result = JsonConvert.DeserializeObject<GetPOIResultDto>(result);
var poi_data = new List<POIResultDto>();
if (poi_result != null)
{
foreach (var r in poi_result.results.Take(5))
{
poi_data.Add(new POIResultDto
{
Id = r.place_id,
Name = r.name,
Latitude = r.geometry.location.lat,
Longitude = r.geometry.location.lng,
});
}
}
return Success(poi_data);
}
}
#endregion
}
}

View file

@ -0,0 +1,269 @@
using BMA.EHR.Application.Repositories;
using BMA.EHR.Application.Repositories.Leaves;
using BMA.EHR.Command.Service.DTOs.DutyTime;
using BMA.EHR.Domain.Common;
using BMA.EHR.Domain.Models.Leave;
using BMA.EHR.Domain.Shared;
using BMA.EHR.Infrastructure.Persistence;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.Annotations;
using System.Security.Claims;
namespace BMA.EHR.Command.Service.Controllers
{
[Route("api/v{version:apiVersion}/leave/duty-time")]
[ApiVersion("1.0")]
[ApiController]
[Produces("application/json")]
[Authorize]
[SwaggerTag("API ระบบจัดการรอบการลงเวลาทำงาน")]
public class DutyTimeController : BaseController
{
#region " Fields "
private readonly DutyTimeRepository _repository;
private readonly LeaveDbContext _context;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IWebHostEnvironment _hostingEnvironment;
private readonly IConfiguration _configuration;
private readonly UserProfileRepository _userProfileRepository;
#endregion
#region " Constuctor and Destructor "
public DutyTimeController(DutyTimeRepository repository,
LeaveDbContext context,
IHttpContextAccessor httpContextAccessor,
IWebHostEnvironment hostingEnvironment,
IConfiguration configuration,
UserProfileRepository userProfileRepository)
{
_repository = repository;
_context = context;
_httpContextAccessor = httpContextAccessor;
_hostingEnvironment = hostingEnvironment;
_configuration = configuration;
_userProfileRepository = userProfileRepository;
}
#endregion
#region " Properties "
private string? UserId => _httpContextAccessor?.HttpContext?.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
private string? FullName => _httpContextAccessor?.HttpContext?.User?.FindFirst("name")?.Value;
private bool? PlacementAdmin => _httpContextAccessor?.HttpContext?.User?.IsInRole("placement1");
private Guid OcId
{
get
{
if (UserId != null || UserId != "")
return _userProfileRepository.GetUserOCId(Guid.Parse(UserId!));
else
return Guid.Empty;
}
}
#endregion
#region " Methods "
/// <summary>
/// LV1_004 - ข้อมูลทั้งหมดของรอบการปฏิบัติงาน (ADMIN)
/// </summary>
/// <returns>
/// </returns>
/// <response code="200">เมื่อทำรายการสำเร็จ</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<ActionResult<ResponseObject>> GetAllAsync()
{
var data = await _repository.GetAllAsync();
return Success(data);
}
/// <summary>
/// ข้อมูลของรอบการปฏิบัติงาน (ADMIN)
/// </summary>
/// <returns>
/// </returns>
/// <response code="200">เมื่อทำรายการสำเร็จ</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpGet("{id:guid}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<ActionResult<ResponseObject>> GetByIdAsync(Guid id)
{
var data = await _repository.GetByIdAsync(id);
return Success(data);
}
/// <summary>
/// LV1_001 - สร้างรอบการปฏิบัติงาน (ADMIN)
/// </summary>
/// <returns>
/// </returns>
/// <response code="200">เมื่อทำรายการสำเร็จ</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpPost]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<ActionResult<ResponseObject>> PostAsync([FromBody] CreateDutyTimeDto data)
{
// validate
var startMorning = TimeOnly.Parse(data.StartTimeMorning);
var endMorning = TimeOnly.Parse(data.EndTimeMorning);
var startAfternoon = TimeOnly.Parse(data.StartTimeAfternoon);
var endAfternoon = TimeOnly.Parse(data.EndTimeAfternoon);
if (startMorning >= endMorning)
{
throw new Exception(GlobalMessages.StartTimeGreaterEnd);
}
if (startAfternoon >= endAfternoon)
{
throw new Exception(GlobalMessages.StartTimeGreaterEnd);
}
var oldData = await _repository.GetAllAsync();
if (oldData == null || oldData.Count == 0)
{
var inserted = new DutyTime
{
Id = Guid.NewGuid(),
Description = data.Description,
StartTimeMorning = data.StartTimeMorning,
EndTimeMorning = data.EndTimeMorning,
StartTimeAfternoon = data.StartTimeAfternoon,
EndTimeAfternoon = data.EndTimeAfternoon,
IsActive = true,
IsDefault = true,
};
var ret = await _repository.AddAsync(inserted);
return Success(ret);
}
else
{
if (data.IsDefault)
{
foreach (var d in oldData)
{
d.IsDefault = false;
await _repository.UpdateAsync(d);
}
}
var inserted = new DutyTime
{
Id = Guid.NewGuid(),
Description = data.Description,
StartTimeMorning = data.StartTimeMorning,
EndTimeMorning = data.EndTimeMorning,
StartTimeAfternoon = data.StartTimeAfternoon,
EndTimeAfternoon = data.EndTimeAfternoon,
IsActive = true,
IsDefault = data.IsDefault,
};
var ret = await _repository.AddAsync(inserted);
return Success(ret);
}
}
/// <summary>
/// LV1_002 - แก้ไขรอบการปฏิบัติงาน (ADMIN)
/// </summary>
/// <returns>
/// </returns>
/// <response code="200">เมื่อทำรายการสำเร็จ</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpPut("{id:guid}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<ActionResult<ResponseObject>> PutAsync(Guid id, [FromBody] UpdateDutyTimeDto data)
{
var oldData = await _repository.GetByIdAsync(id);
if (oldData == null)
{
throw new Exception(GlobalMessages.DataNotFound);
}
else
{
var oldDataList = await _repository.GetAllAsync();
if (data.IsDefault)
{
foreach (var d in oldDataList)
{
d.IsDefault = false;
await _repository.UpdateAsync(d);
}
}
oldData.Description = data.Description;
oldData.IsDefault = data.IsDefault;
oldData.IsActive = data.IsActive;
await _repository.UpdateAsync(oldData);
return Success(oldData);
}
}
/// <summary>
/// LV1_003 - ลบรอบการปฏิบัติงาน (ADMIN)
/// </summary>
/// <returns>
/// </returns>
/// <response code="200">เมื่อทำรายการสำเร็จ</response>
/// <response code="401">ไม่ได้ Login เข้าระบบ</response>
/// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
[HttpDelete("{id:guid}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<ActionResult<ResponseObject>> DeleteAsync(Guid id)
{
var oldData = await _repository.GetByIdAsync(id);
if (oldData == null)
{
throw new Exception(GlobalMessages.DataNotFound);
}
else
{
if (oldData.IsActive || oldData.IsDefault)
{
throw new Exception("ไม่สามารถลบรอบการปฏิบัติงานที่ยังใช้งานอยู่ได้");
}
await _repository.DeleteAsync(oldData);
return Success();
}
}
#endregion
}
}

View file

@ -0,0 +1,27 @@
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
namespace BMA.EHR.Command.Service.DTOs.DutyTime
{
public class CreateDutyTimeDto
{
[Required, Comment("คำอธิบาย")]
public string Description { get; set; } = string.Empty;
[Required, Comment("เวลาเข้างานช่วงเช้า")]
public string StartTimeMorning { get; set; } = "00:00";
[Required, Comment("เวลาออกงานช่วงเช้า")]
public string EndTimeMorning { get; set; } = "00:00";
[Required, Comment("เวลาเข้างานช่วงบ่าย")]
public string StartTimeAfternoon { get; set; } = "00:00";
[Required, Comment("เวลาออกงานช่วงบ่าย")]
public string EndTimeAfternoon { get; set; } = "00:00";
[Required, Comment("สถานะว่ารอบใดเป็นค่า Default ของข้าราชการ (สำหรับทุกคนที่ยังไม่ได้ทำการเลือกรอบ)")]
public bool IsDefault { get; set; } = false;
}
}

View file

@ -0,0 +1,17 @@
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
namespace BMA.EHR.Command.Service.DTOs.DutyTime
{
public class UpdateDutyTimeDto
{
[Required, Comment("คำอธิบาย")]
public string Description { get; set; } = string.Empty;
[Required, Comment("สถานะว่ารอบใดเป็นค่า Default ของข้าราชการ (สำหรับทุกคนที่ยังไม่ได้ทำการเลือกรอบ)")]
public bool IsDefault { get; set; } = false;
[Required, Comment("สถานะการเปิดใช้งาน (เปิด/ปิด)")]
public bool IsActive { get; set; } = true;
}
}

View file

@ -0,0 +1,9 @@
namespace BMA.EHR.Command.Service.DTOs.POI
{
public class GetPOIDto
{
public double Lat { get; set; } = 0;
public double Lon { get; set; } = 0;
}
}

View file

@ -0,0 +1,28 @@
namespace BMA.EHR.Command.Service.DTOs.POI
{
public class GetPOIResultDto
{
public List<POIItem> results { get; set; } = new List<POIItem>();
}
public class POIItem
{
public string place_id { get; set; } = string.Empty;
public string name { get; set; } = string.Empty;
public GeometryItem geometry { get; set; } = new();
}
public class GeometryItem
{
public LocationItem location { get; set; } = new();
}
public class LocationItem
{
public double lat { get; set; } = 0;
public double lng { get; set; } = 0;
}
}

View file

@ -0,0 +1,13 @@
namespace BMA.EHR.Command.Service.DTOs.POI
{
public class POIResultDto
{
public string Id { get; set; } = string.Empty;
public string Name { get; set; } = string.Empty;
public double Latitude { get; set; } = 0;
public double Longitude { get; set; } = 0;
}
}

View file

@ -0,0 +1,27 @@
#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.
FROM mcr.microsoft.com/dotnet/aspnet:7.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build
WORKDIR /src
COPY ["BMA.EHR.Domain/BMA.EHR.Domain.csproj", "BMA.EHR.Domain/"]
COPY ["BMA.EHR.Application/BMA.EHR.Application.csproj", "BMA.EHR.Application/"]
COPY ["BMA.EHR.Infrastructure/BMA.EHR.Infrastructure.csproj", "BMA.EHR.Infrastructure/"]
COPY ["BMA.EHR.Leave.Service/BMA.EHR.Leave.Service.csproj", "BMA.EHR.Leave.Service/"]
RUN dotnet restore "BMA.EHR.Leave.Service/BMA.EHR.Leave.Service.csproj"
COPY . .
WORKDIR "/src/BMA.EHR.Leave.Service"
RUN dotnet build "BMA.EHR.Leave.Service.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "BMA.EHR.Leave.Service.csproj" -c Release -o /app/publish /p:UseAppHost=false
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "BMA.EHR.Leave.Service.dll"]

View file

@ -0,0 +1,162 @@
using BMA.EHR.Application;
using BMA.EHR.Command.Service;
using BMA.EHR.Domain.Middlewares;
using BMA.EHR.Infrastructure;
using BMA.EHR.Infrastructure.Persistence;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.AspNetCore.Mvc.Versioning;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Tokens;
using Serilog;
using Serilog.Exceptions;
using Serilog.Sinks.Elasticsearch;
using System.Reflection;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
{
var issuer = builder.Configuration["Jwt:Issuer"];
var key = builder.Configuration["Jwt:Key"];
IdentityModelEventSource.ShowPII = true;
builder.Services.AddHttpContextAccessor();
builder.Services.AddApiVersioning(opt =>
{
opt.DefaultApiVersion = new ApiVersion(1, 0);
opt.AssumeDefaultVersionWhenUnspecified = true;
opt.ReportApiVersions = true;
opt.ApiVersionReader = ApiVersionReader.Combine(new UrlSegmentApiVersionReader(),
new HeaderApiVersionReader("x-api-version"),
new MediaTypeApiVersionReader("x-api-version"));
});
builder.Services.AddVersionedApiExplorer(setup =>
{
setup.GroupNameFormat = "'v'VVV";
setup.SubstituteApiVersionInUrl = true;
});
builder.Services.AddEndpointsApiExplorer();
// Authorization
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(opt =>
{
opt.SaveToken = true;
opt.RequireHttpsMetadata = false; //false for dev
opt.Authority = issuer;
opt.TokenValidationParameters = new()
{
ValidateIssuer = true,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = issuer,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key))
};
});
builder.Services.AddAuthorization();
// use serilog
ConfigureLogs();
builder.Host.UseSerilog();
// Add config CORS
builder.Services.AddCors(options => options.AddDefaultPolicy(builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowedToAllowWildcardSubdomains();
}));
// Add services to the container.
builder.Services.AddApplication();
builder.Services.AddPersistence(builder.Configuration);
builder.Services.AddControllers(options =>
{
options.SuppressAsyncSuffixInActionNames = false;
})
.AddNewtonsoftJson(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
builder.Services.AddSwaggerGen();
builder.Services.ConfigureOptions<ConfigureSwaggerOptions>();
builder.Services.AddHealthChecks();
}
var app = builder.Build();
{
var apiVersionDescriptionProvider = app.Services.GetRequiredService<IApiVersionDescriptionProvider>();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(options =>
{
foreach (var description in apiVersionDescriptionProvider.ApiVersionDescriptions)
{
options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json",
description.GroupName.ToUpperInvariant());
}
});
}
app.MapHealthChecks("/health");
app.UseHttpsRedirection();
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.UseDefaultFiles();
app.UseStaticFiles();
app.MapControllers();
app.UseMiddleware<ErrorHandlerMiddleware>();
// apply migrations
await using var scope = app.Services.CreateAsyncScope();
await using var db = scope.ServiceProvider.GetRequiredService<LeaveDbContext>();
await db.Database.MigrateAsync();
app.Run();
}
void ConfigureLogs()
{
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile(
$"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json",
optional: true)
.Build();
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.MinimumLevel.Error()
.WriteTo.Console()
.Enrich.WithExceptionDetails()
.WriteTo.Elasticsearch(ConfigureElasticSink(configuration, environment ?? ""))
.Enrich.WithProperty("Environment", environment)
.ReadFrom.Configuration(configuration)
.CreateLogger();
}
ElasticsearchSinkOptions ConfigureElasticSink(IConfigurationRoot configuration, string environment)
{
return new ElasticsearchSinkOptions(new Uri(configuration["ElasticConfiguration:Uri"] ?? ""))
{
AutoRegisterTemplate = true,
IndexFormat = $"{Assembly.GetExecutingAssembly()?.GetName()?.Name?.ToLower().Replace(".", "-")}-{environment?.ToLower().Replace(".", "-")}"
};
}

View file

@ -0,0 +1,51 @@
{
"profiles": {
"https": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"dotnetRunMessages": true,
"applicationUrl": "https://localhost:7283;http://localhost:5028"
},
"http": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"dotnetRunMessages": true,
"applicationUrl": "http://localhost:5028"
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"Docker": {
"commandName": "Docker",
"launchBrowser": true,
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/swagger",
"environmentVariables": {
"ASPNETCORE_URLS": "https://+:443;http://+:80"
},
"publishAllPorts": true,
"useSSL": true
}
},
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:27010",
"sslPort": 44373
}
}
}

View file

@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

View file

@ -0,0 +1,48 @@
{
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Information",
"System": "Warning"
}
}
},
"ElasticConfiguration": {
"Uri": "http://localhost:9200"
},
"AllowedHosts": "*",
"ConnectionStrings": {
//"DefaultConnection": "User Id=sys;Password=P@ssw0rd;DBA Privilege=SYSDBA;Data Source=localhost:1521/ORCLCDB",
"DefaultConnection": "server=192.168.1.9;user=root;password=adminVM123;port=3306;database=bma_ehr_demo;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;",
"ExamConnection": "server=192.168.1.9;user=root;password=adminVM123;port=3306;database=bma_ehr_exam_demo;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;",
"LeaveConnection": "server=192.168.4.11;user=root;password=P@ssw0rd;port=3306;database=bma_ehr_leave;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;"
},
"Jwt": {
"Key": "HP-FnQMUj9msHMSD3T9HtdEnphAKoCJLEl85CIqROFI",
"Issuer": "https://id.frappet.synology.me/realms/bma-ehr"
},
"EPPlus": {
"ExcelPackage": {
"LicenseContext": "NonCommercial"
}
},
"MinIO": {
"Endpoint": "https://s3cluster.frappet.com/",
"AccessKey": "frappet",
"SecretKey": "FPTadmin2357",
"BucketName": "bma-ehr-fpt"
},
"Protocol": "HTTPS",
"Node": {
"API": "https://bma-ehr.frappet.synology.me/api/v1/probation"
},
"Mail": {
"Server": "mail.bangkok.go.th",
"User": "saraban.csc.rd@bangkok.go.th",
"Password": "Saraban5222",
"MailFrom": "saraban.csc.rd@bangkok.go.th",
"Port": "25"
},
"API": "https://bma-ehr.frappet.synology.me/api/v1"
}

View file

@ -0,0 +1,184 @@
<!--
~ Copyright 2016 Red Hat, Inc. and/or its affiliates
~ and other contributors as indicated by the @author tags.
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<html>
<head>
<script src="./keycloak.js"></script>
</head>
<body>
<div>
<button onclick="keycloak.login()">Login</button>
<button onclick="keycloak.login({ action: 'UPDATE_PASSWORD' })">Update Password</button>
<button onclick="keycloak.logout()">Logout</button>
<button onclick="keycloak.register()">Register</button>
<button onclick="keycloak.accountManagement()">Account</button>
<button onclick="refreshToken(9999)">Refresh Token</button>
<button onclick="refreshToken(30)">Refresh Token (if <30s validity)</button>
<button onclick="loadProfile()">Get Profile</button>
<button onclick="updateProfile()">Update profile</button>
<button onclick="loadUserInfo()">Get User Info</button>
<button onclick="output(keycloak.tokenParsed)">Show Token</button>
<button onclick="output(keycloak.refreshTokenParsed)">Show Refresh Token</button>
<button onclick="output(keycloak.idTokenParsed)">Show ID Token</button>
<button onclick="showExpires()">Show Expires</button>
<button onclick="output(keycloak)">Show Details</button>
<button onclick="output(keycloak.createLoginUrl())">Show Login URL</button>
<button onclick="output(keycloak.createLogoutUrl())">Show Logout URL</button>
<button onclick="output(keycloak.createRegisterUrl())">Show Register URL</button>
<button onclick="output(keycloak.createAccountUrl())">Show Account URL</button>
</div>
<h2>Result</h2>
<pre style="background-color: #ddd; border: 1px solid #ccc; padding: 10px; word-wrap: break-word; white-space: pre-wrap;" id="output"></pre>
<h2>Events</h2>
<pre style="background-color: #ddd; border: 1px solid #ccc; padding: 10px; word-wrap: break-word; white-space: pre-wrap;" id="events"></pre>
<script>
function loadProfile() {
keycloak.loadUserProfile().success(function(profile) {
output(profile);
}).error(function() {
output('Failed to load profile');
});
}
function updateProfile() {
var url = keycloak.createAccountUrl().split('?')[0];
var req = new XMLHttpRequest();
req.open('POST', url, true);
req.setRequestHeader('Accept', 'application/json');
req.setRequestHeader('Content-Type', 'application/json');
req.setRequestHeader('Authorization', 'bearer ' + keycloak.token);
req.onreadystatechange = function () {
if (req.readyState == 4) {
if (req.status == 200) {
output('Success');
} else {
output('Failed');
}
}
}
req.send('{"email":"myemail@foo.bar","firstName":"test","lastName":"bar"}');
}
function loadUserInfo() {
keycloak.loadUserInfo().success(function(userInfo) {
output(userInfo);
}).error(function() {
output('Failed to load user info');
});
}
function refreshToken(minValidity) {
keycloak.updateToken(minValidity).then(function(refreshed) {
if (refreshed) {
output(keycloak.tokenParsed);
} else {
output('Token not refreshed, valid for ' + Math.round(keycloak.tokenParsed.exp + keycloak.timeSkew - new Date().getTime() / 1000) + ' seconds');
}
}).catch(function() {
output('Failed to refresh token');
});
}
function showExpires() {
if (!keycloak.tokenParsed) {
output("Not authenticated");
return;
}
var o = 'Token Expires:\t\t' + new Date((keycloak.tokenParsed.exp + keycloak.timeSkew) * 1000).toLocaleString() + '\n';
o += 'Token Expires in:\t' + Math.round(keycloak.tokenParsed.exp + keycloak.timeSkew - new Date().getTime() / 1000) + ' seconds\n';
if (keycloak.refreshTokenParsed) {
o += 'Refresh Token Expires:\t' + new Date((keycloak.refreshTokenParsed.exp + keycloak.timeSkew) * 1000).toLocaleString() + '\n';
o += 'Refresh Expires in:\t' + Math.round(keycloak.refreshTokenParsed.exp + keycloak.timeSkew - new Date().getTime() / 1000) + ' seconds';
}
output(o);
}
function output(data) {
if (typeof data === 'object') {
data = JSON.stringify(data, null, ' ');
}
document.getElementById('output').innerHTML = data;
}
function event(event) {
var e = document.getElementById('events').innerHTML;
document.getElementById('events').innerHTML = new Date().toLocaleString() + "\t" + event + "\n" + e;
}
var keycloak = Keycloak();
keycloak.onAuthSuccess = function () {
event('Auth Success');
};
keycloak.onAuthError = function (errorData) {
event("Auth Error: " + JSON.stringify(errorData) );
};
keycloak.onAuthRefreshSuccess = function () {
event('Auth Refresh Success');
};
keycloak.onAuthRefreshError = function () {
event('Auth Refresh Error');
};
keycloak.onAuthLogout = function () {
event('Auth Logout');
};
keycloak.onTokenExpired = function () {
event('Access token expired.');
};
keycloak.onActionUpdate = function (status) {
switch (status) {
case 'success':
event('Action completed successfully'); break;
case 'cancelled':
event('Action cancelled by user'); break;
case 'error':
event('Action failed'); break;
}
};
// Flow can be changed to 'implicit' or 'hybrid', but then client must enable implicit flow in admin console too
var initOptions = {
responseMode: 'fragment',
flow: 'standard'
};
keycloak.init(initOptions).then(function(authenticated) {
output('Init Success (' + (authenticated ? 'Authenticated' : 'Not Authenticated') + ')');
}).catch(function() {
output('Init Error');
});
</script>
</body>
</html>

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,7 @@
{
"realm": "bma-ehr",
"auth-server-url": "https://id.frappet.synology.me",
"ssl-required": "external",
"resource": "bma-ehr",
"public-client": true
}