diff --git a/Program/Common/Auth/APIHeaderMiddleware.cs b/Program/Common/Auth/APIHeaderMiddleware.cs index ab4c7f9..8f5b411 100644 --- a/Program/Common/Auth/APIHeaderMiddleware.cs +++ b/Program/Common/Auth/APIHeaderMiddleware.cs @@ -46,6 +46,13 @@ public class APIHeaderMiddleware public async Task Invoke(HttpContext context) { + + if (context.Request.Path.StartsWithSegments("/api/v1/in/app", StringComparison.OrdinalIgnoreCase)) + { + await _next(context); + return; + } + // Scoped 사용해서 값 가져오는 곳임 var headerConfig = context.RequestServices.GetRequiredService(); diff --git a/Program/Common/Model/APISetting.cs b/Program/Common/Model/APISetting.cs index e26c6fd..2836748 100644 --- a/Program/Common/Model/APISetting.cs +++ b/Program/Common/Model/APISetting.cs @@ -7,6 +7,9 @@ namespace AcaMate.Common.Models; public class APIHeader { [Key] + public string specific_id { get; set; } + + public DateTime connect_date { get; set; } public string h_key { get; set; } public string h_value { get; set; } } diff --git a/Program/V1/Controllers/AppController.cs b/Program/V1/Controllers/AppController.cs index 897ebd0..0b85eb0 100644 --- a/Program/V1/Controllers/AppController.cs +++ b/Program/V1/Controllers/AppController.cs @@ -1,10 +1,14 @@ +using System.Diagnostics; using Microsoft.AspNetCore.Mvc; using System.Text.Json; +using System.Security.Cryptography; +using System.Text; using AcaMate.Common.Data; using AcaMate.Common.Models; using AcaMate.Common.Token; using AcaMate.V1.Models; using AcaMate.V1.Services; +using Microsoft.AspNetCore.Http.HttpResults; using Microsoft.EntityFrameworkCore; using Microsoft.IdentityModel.Tokens; using Version = AcaMate.V1.Models.Version; @@ -29,6 +33,133 @@ public class AppController : ControllerBase _jwtTokenService = jwtTokenService; } + + // 이 키값의 제한 시간은 24h이다 + [HttpGet] + [CustomOperation("헤더 정보 생성", "헤더에 접근하기 위한 키 값 받아오기", "시스템")] + public async Task GetHeaderValue(string type, string specific, string project) + { + if (string.IsNullOrEmpty(specific) || string.IsNullOrEmpty(type) || string.IsNullOrEmpty(project)) + return BadRequest(APIResponse.InvalidInputError()); + if (!ModelState.IsValid) return BadRequest(APIResponse.InvalidInputError()); + string summary = String.Empty; + + try + { + summary = _repositoryService.ReadSummary(typeof(AppController), "GetHeaderValue"); + bool valid = false; + + switch (type) + { + case "I": + if (project == "me.myds.ipstein.acamate.AcaMate") valid = true; + break; + case "A": + break; + case "W": + break; + default: + return BadRequest(APIResponse.InvalidInputError($"[{summary}], 타입 에러")); + break; + } + + if (valid) + { + + var apiHeader = await _dbContext.APIHeader.FirstOrDefaultAsync(h => h.specific_id == specific); + + string nowTime = DateTime.Now.ToString("o"); + string combineText = $"{project}_{nowTime}_{specific}"; + string headerValue = KeyGenerator(combineText); + + if (apiHeader != null) + { + if (DateTime.Now - apiHeader.connect_date > TimeSpan.FromHours(24)) + { + _logger.LogInformation($"[{summary}] : 해당 키 유효기간 경과"); + apiHeader.h_value = headerValue; + + if (await _repositoryService.SaveData(apiHeader)) + { + string msg = "정상 - 로그 저장 실패"; + var logProject = new LogProject + { + create_date = DateTime.Now , + log = $"[{summary}] : 해당 키 유효시간 만료로 인한 새 키 부여" + }; + if (await _repositoryService.SaveData(logProject)) + msg = "정상"; + return Ok(APIResponse.Send("001", msg, new { header = headerValue })); + } + else + { + // 저장이 안된거니 서버 오류 + return StatusCode(500, APIResponse.InternalSeverError()); + } + } + else + { + // 유효기간 만료 이상 없이 다 잘 됨 + return Ok(APIResponse.Send("000", "정상", new { header = apiHeader.h_value })); + } + } + else + { + _logger.LogInformation($"[{summary}] : 저장 된게 없음"); + + var newHeader = new APIHeader + { + h_key = type == "I" ? "iOS_AM_Connect_Key" + : (type == "A" ? "And_AM_Connect_Key" + : (type == "W" ? "Web_AM_Connect_Key": throw new Exception("ERROR"))), + h_value = headerValue, + connect_date = DateTime.Now, + specific_id = specific + }; + + if (await _repositoryService.SaveData(newHeader)) + { + string msg = "정상 - 로그 저장 실패"; + var logProject = new LogProject + { + create_date = DateTime.Now , + log = $"[{summary}] : 해당 키 유효시간 만료로 인한 새 키 부여" + }; + // 이거 로그 저장 안되는거 확인! + _logger.LogInformation($"[{summary}] : {logProject.log}"); + if (await _repositoryService.SaveData(logProject)) + msg = "정상"; + + return Ok(APIResponse.Send("001", msg, new { header = headerValue })); + } + else + { + // 저장이 안된거니 서버 오류 + return StatusCode(500, APIResponse.InternalSeverError()); + } + } + } + return BadRequest(APIResponse.InvalidInputError()); + + + // return Ok(APIResponse.Send("000", "정상", Empty)); + } + catch (Exception ex) + { + _logger.LogError($"[{summary}] : {ex.Message}"); + return StatusCode(500, APIResponse.UnknownError(ex.Message)); + } + } + + public string KeyGenerator(string combineText) + { + using (SHA256 sha256 = SHA256.Create()) + { + byte[] hashBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(combineText)); + return BitConverter.ToString(hashBytes).Replace("-", string.Empty).ToLowerInvariant(); + } + } + [HttpGet("version")] [CustomOperation("앱 버전 확인","앱 버전을 확인해서 업데이트 여부 판단", "시스템")] public IActionResult GetVersionData(string type) diff --git a/Program/V1/Models/Log.cs b/Program/V1/Models/Log.cs index d342fb9..ee27de8 100644 --- a/Program/V1/Models/Log.cs +++ b/Program/V1/Models/Log.cs @@ -5,6 +5,19 @@ using Microsoft.EntityFrameworkCore.Metadata.Internal; namespace AcaMate.V1.Models; + +[Table("log_project")] +public class LogProject +{ + [Key] + [DatabaseGenerated(DatabaseGeneratedOption.Identity)] + public int lid { get; set; } + public DateTime create_date {get; set;} + public string log { get; set; } +} + + + [Table("log_push")] public class LogPush {