forked from AcaMate/AcaMate_API
[♻️] JWT 토큰 관련해서 인증 로직 전제적으로 변경
This commit is contained in:
parent
96d8999317
commit
0b65855e15
|
@ -17,7 +17,6 @@ namespace AcaMate.Common.Token;
|
|||
public class JwtTokenService
|
||||
{
|
||||
private readonly JwtSettings _jwtSettings;
|
||||
|
||||
private readonly ILogger<JwtTokenService> _logger;
|
||||
|
||||
public JwtTokenService(IOptions<JwtSettings> jwtSettings, ILogger<JwtTokenService> logger)
|
||||
|
@ -79,7 +78,7 @@ public class JwtTokenService
|
|||
/// <summary>
|
||||
/// 여기는 엑세스 토큰의 확인을 위한 jwt 서비스 내의 인증 메서드
|
||||
/// </summary>
|
||||
public ClaimsPrincipal ValidateToken(string token)
|
||||
public async Task<ClaimsPrincipal?> ValidateToken(string token)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(token)) return null;
|
||||
var tokenHandler = new JwtSecurityTokenHandler();
|
||||
|
@ -101,9 +100,9 @@ public class JwtTokenService
|
|||
var principal = tokenHandler.ValidateToken(token, validationParameters, out var securityToken);
|
||||
return principal;
|
||||
}
|
||||
catch (Exception e)
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"검증 실패 {e}");
|
||||
_logger.LogError($"엑세스 토큰 오류: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
|
||||
|
|
|
@ -41,17 +41,22 @@ public static class APIResponse
|
|||
public static APIResponseStatus<string> Success (){
|
||||
return Send("000", "정상", "");
|
||||
}
|
||||
|
||||
|
||||
public static APIResponseStatus<string> InvalidInputError(string? msg = null)
|
||||
{
|
||||
return Send("100", msg ?? "입력 값이 유효하지 않습니다.", "");
|
||||
}
|
||||
|
||||
|
||||
public static APIResponseStatus<string> NotFoundError(string? msg = null)
|
||||
{
|
||||
return Send("200", msg ?? "알맞은 값을 찾을 수 없습니다.", "");
|
||||
}
|
||||
|
||||
public static APIResponseStatus<string> AccessExpireError(string? msg = null)
|
||||
{
|
||||
return Send("201", msg ?? "엑세스 토큰이 만료되었습니다.", "");
|
||||
}
|
||||
|
||||
public static APIResponseStatus<string> InternalSeverError(string? msg = null)
|
||||
{
|
||||
return Send("300", msg ?? "통신에 오류가 발생하였습니다.", "");
|
||||
|
|
|
@ -2,6 +2,10 @@ using Microsoft.AspNetCore.Mvc;
|
|||
using System.Text.Json;
|
||||
using AcaMate.Common.Data;
|
||||
using AcaMate.Common.Models;
|
||||
using AcaMate.Common.Token;
|
||||
using AcaMate.V1.Models;
|
||||
using AcaMate.V1.Services;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Version = AcaMate.V1.Models.Version;
|
||||
|
||||
|
@ -13,10 +17,16 @@ namespace AcaMate.V1.Controllers;
|
|||
public class AppController : ControllerBase
|
||||
{
|
||||
private readonly AppDbContext _dbContext;
|
||||
private readonly ILogger<AppController> _logger;
|
||||
private readonly IRepositoryService _repositoryService;
|
||||
private readonly JwtTokenService _jwtTokenService;
|
||||
|
||||
public AppController(AppDbContext dbContext)
|
||||
public AppController(AppDbContext dbContext, ILogger<AppController> logger, IRepositoryService repositoryService, JwtTokenService jwtTokenService)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
_logger = logger;
|
||||
_repositoryService = repositoryService;
|
||||
_jwtTokenService = jwtTokenService;
|
||||
}
|
||||
|
||||
[HttpGet("version")]
|
||||
|
@ -69,12 +79,58 @@ public class AppController : ControllerBase
|
|||
|
||||
[HttpGet("auth")]
|
||||
[CustomOperation("서버 접근 권한 확인", "서버 기능을 사용하기 위한 접근에 대해 권한 확인", "시스템")]
|
||||
public async Task<IActionResult> AuthProgram(string key)
|
||||
public async Task<IActionResult> AuthProgram([FromBody] AuthKey keys)
|
||||
{
|
||||
string summary = String.Empty;
|
||||
|
||||
try
|
||||
{
|
||||
summary = _repositoryService.ReadSummary(typeof(AppController), "AuthProgram");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError($"[{summary}] : {ex.Message}");
|
||||
return StatusCode(500, APIResponse.UnknownError(ex.Message));
|
||||
}
|
||||
|
||||
return Ok(APIResponse.Send("000", "OK", Empty));
|
||||
}
|
||||
|
||||
|
||||
[HttpGet("retryAccess")]
|
||||
[CustomOperation("엑세스 토큰 재발급", "액세스 토큰 재발급 동작 수행", "시스템")]
|
||||
public async Task<IActionResult> RetryAccessToken(string refresh)
|
||||
{
|
||||
string summary = String.Empty;
|
||||
|
||||
try
|
||||
{
|
||||
summary = _repositoryService.ReadSummary(typeof(AppController), "AuthProgram");
|
||||
var refreshToken = await _dbContext.RefreshTokens
|
||||
.FirstOrDefaultAsync(t => t.refresh_token == refresh);
|
||||
if (refreshToken == null) throw new TokenException($"[{summary}] : 리프레시 토큰의 문제");
|
||||
if (refreshToken.revoke_Date < DateTime.Now) throw new TokenException($"[{summary}] : 리프레시 토큰 만료");
|
||||
if (refreshToken.expire_date < DateTime.Now) throw new TokenException($"[{summary}] : 리프레시 토큰 폐기");
|
||||
string access = _jwtTokenService.GenerateJwtToken(refreshToken.uid);
|
||||
return Ok(APIResponse.Send("000", $"[{summary}], 토큰 생성 완료",
|
||||
new {
|
||||
access = access
|
||||
}));
|
||||
}
|
||||
catch (TokenException ex)
|
||||
{
|
||||
_logger.LogError($"[{summary}] : {ex.Message}");
|
||||
return Ok(APIResponse.InvalidInputError(ex.Message));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError($"[{summary}] : {ex.Message}");
|
||||
return StatusCode(500, APIResponse.UnknownError(ex.Message));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Update.Internal;
|
||||
|
@ -8,6 +9,7 @@ using Microsoft.AspNetCore.Http.HttpResults;
|
|||
using AcaMate.Common.Data;
|
||||
using AcaMate.V1.Services;
|
||||
using AcaMate.Common.Models;
|
||||
using AcaMate.Common.Token;
|
||||
using AcaMate.V1.Models;
|
||||
|
||||
|
||||
|
@ -23,14 +25,19 @@ public class PushController : ControllerBase
|
|||
private readonly IPushQueue _pushQueue;
|
||||
private readonly AppDbContext _dbContext;
|
||||
private readonly IRepositoryService _repositoryService;
|
||||
public PushController(ILogger<PushController> logger, IPushQueue pushQueue, AppDbContext dbContext, IRepositoryService repositoryService)
|
||||
private readonly JwtTokenService _jwtTokenService;
|
||||
public PushController(ILogger<PushController> logger, IPushQueue pushQueue, AppDbContext dbContext, IRepositoryService repositoryService, JwtTokenService jwtTokenService)
|
||||
{
|
||||
_logger = logger;
|
||||
_pushQueue = pushQueue;
|
||||
_dbContext = dbContext;
|
||||
_repositoryService = repositoryService;
|
||||
_jwtTokenService = jwtTokenService;
|
||||
}
|
||||
|
||||
// 추가 사항
|
||||
// 카테고리 별 조회 하는 부분도 추가를 할 지 고민을 해야 할 것 같음
|
||||
|
||||
[HttpGet()]
|
||||
[CustomOperation("푸시 확인", "저장된 양식을 확인 할 수 있다.", "푸시")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(APIResponseStatus<object>))]
|
||||
|
@ -186,22 +193,23 @@ public class PushController : ControllerBase
|
|||
[HttpPost("set")]
|
||||
[CustomOperation("푸시 변경", "저장된 양식을 변경한다.", "푸시")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(APIResponseStatus<object>))]
|
||||
public async Task<IActionResult> SetPush(string token, string refresh, [FromBody] DBPayload request)
|
||||
public async Task<IActionResult> SetPush(string token, [FromBody] DBPayload request)
|
||||
{
|
||||
string uid = "";
|
||||
if (string.IsNullOrEmpty(token)) return BadRequest(APIResponse.InvalidInputError());
|
||||
if (!ModelState.IsValid) return BadRequest(APIResponse.InvalidInputError());
|
||||
string summary = String.Empty;
|
||||
string uid = String.Empty;
|
||||
|
||||
try {
|
||||
|
||||
try
|
||||
{
|
||||
if (token == "System") uid = "System";
|
||||
else {
|
||||
if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(refresh)) return BadRequest(APIResponse.InvalidInputError());
|
||||
if(!ModelState.IsValid) return BadRequest(APIResponse.InvalidInputError());
|
||||
|
||||
var validateToken = await _repositoryService.ValidateToken(token, refresh);
|
||||
uid = validateToken.uid;
|
||||
else
|
||||
{
|
||||
var validateToken = await _jwtTokenService.ValidateToken(token);
|
||||
if (validateToken == null) return Ok(APIResponse.AccessExpireError());
|
||||
uid = validateToken.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? string.Empty;
|
||||
}
|
||||
|
||||
|
||||
summary = _repositoryService.ReadSummary(typeof(PushController), "SetPush");
|
||||
var dbPayload = await _dbContext.DBPayload
|
||||
.FirstOrDefaultAsync(p => p.pid == request.pid && p.bid == request.bid);
|
||||
|
@ -246,10 +254,12 @@ public class PushController : ControllerBase
|
|||
[HttpPost("create")]
|
||||
[CustomOperation("푸시 생성", "새로운 푸시 양식을 생성한다.", "푸시")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(APIResponseStatus<object>))]
|
||||
public async Task<IActionResult> CreatePush(string token, string refresh, [FromBody] CreatePush request)
|
||||
public async Task<IActionResult> CreatePush(string token, [FromBody] CreatePush request)
|
||||
{
|
||||
string uid = "";
|
||||
if (string.IsNullOrEmpty(token)) return BadRequest(APIResponse.InvalidInputError());
|
||||
if (!ModelState.IsValid) return BadRequest(APIResponse.InvalidInputError());
|
||||
string summary = String.Empty;
|
||||
string uid = "";
|
||||
|
||||
Func<string, int, string> randomLetter = (letters, count) => new string(Enumerable.Range(0, count).Select(_ => letters[new Random().Next(letters.Length)]).ToArray());
|
||||
var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
|
@ -257,15 +267,13 @@ public class PushController : ControllerBase
|
|||
var frontLetters = $"{randomLetter(letters, 1)}{randomLetter(digits, 1)}{randomLetter(letters, 1)}";
|
||||
var afterLetters = $"{randomLetter(letters, 1)}{randomLetter(digits, 1)}{randomLetter(letters, 1)}";
|
||||
|
||||
try {
|
||||
|
||||
try
|
||||
{
|
||||
if (token == "System") uid = "System";
|
||||
else {
|
||||
if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(refresh)) return BadRequest(APIResponse.InvalidInputError());
|
||||
if(!ModelState.IsValid) return BadRequest(APIResponse.InvalidInputError());
|
||||
|
||||
var validateToken = await _repositoryService.ValidateToken(token, refresh);
|
||||
uid = validateToken.uid;
|
||||
var validateToken = await _jwtTokenService.ValidateToken(token);
|
||||
if (validateToken == null) return Ok(APIResponse.AccessExpireError());
|
||||
uid = validateToken.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? string.Empty;
|
||||
}
|
||||
|
||||
summary = _repositoryService.ReadSummary(typeof(PushController), "CreatePush");
|
||||
|
@ -327,8 +335,10 @@ public class PushController : ControllerBase
|
|||
[HttpDelete("delete")]
|
||||
[CustomOperation("푸시 삭제", "저장된 푸시 양식을 삭제 한다.", "푸시")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(APIResponseStatus<object>))]
|
||||
public async Task<IActionResult> DeletePush(string token, string refresh, string bid, string pid)
|
||||
public async Task<IActionResult> DeletePush(string token, string bid, string pid)
|
||||
{
|
||||
if (string.IsNullOrEmpty(token)) return BadRequest(APIResponse.InvalidInputError());
|
||||
if (!ModelState.IsValid) return BadRequest(APIResponse.InvalidInputError());
|
||||
string uid = "";
|
||||
string summary = String.Empty;
|
||||
|
||||
|
@ -336,12 +346,11 @@ public class PushController : ControllerBase
|
|||
{
|
||||
if (token == "System") uid = "System";
|
||||
else {
|
||||
if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(refresh)) return BadRequest(APIResponse.InvalidInputError());
|
||||
if(!ModelState.IsValid) return BadRequest(APIResponse.InvalidInputError());
|
||||
|
||||
var validateToken = await _repositoryService.ValidateToken(token, refresh);
|
||||
uid = validateToken.uid;
|
||||
var validateToken = await _jwtTokenService.ValidateToken(token);
|
||||
if (validateToken == null) return Ok(APIResponse.AccessExpireError());
|
||||
uid = validateToken.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? string.Empty;
|
||||
}
|
||||
|
||||
summary = _repositoryService.ReadSummary(typeof(PushController), "DeletePush");
|
||||
|
||||
var payload = await _dbContext.DBPayload.FirstOrDefaultAsync(p => p.bid == bid && p.pid == pid);
|
||||
|
@ -374,21 +383,21 @@ public class PushController : ControllerBase
|
|||
[HttpDelete("delete/list")]
|
||||
[CustomOperation("사용자 푸시 목록 삭제", "사용자가 받은 푸시목록에서 푸시를 삭제한다..", "푸시")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(APIResponseStatus<object>))]
|
||||
public async Task<IActionResult> DeleteListPush(string token, string refresh, int id)
|
||||
public async Task<IActionResult> DeleteListPush(string token, int id)
|
||||
{
|
||||
if (string.IsNullOrEmpty(token)) return BadRequest(APIResponse.InvalidInputError());
|
||||
if (!ModelState.IsValid) return BadRequest(APIResponse.InvalidInputError());
|
||||
string uid = "";
|
||||
string summary = String.Empty;
|
||||
|
||||
try
|
||||
{
|
||||
if (token == "System") uid = "System";
|
||||
else {
|
||||
if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(refresh)) return BadRequest(APIResponse.InvalidInputError());
|
||||
if(!ModelState.IsValid) return BadRequest(APIResponse.InvalidInputError());
|
||||
|
||||
var validateToken = await _repositoryService.ValidateToken(token, refresh);
|
||||
uid = validateToken.uid;
|
||||
var validateToken = await _jwtTokenService.ValidateToken(token);
|
||||
if (validateToken == null) return Ok(APIResponse.AccessExpireError());
|
||||
uid = validateToken.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? string.Empty;
|
||||
}
|
||||
|
||||
summary = _repositoryService.ReadSummary(typeof(PushController), "DeleteListPush");
|
||||
var cabinetPush = await _dbContext.PushCabinet.FirstOrDefaultAsync(c => c.id == id);
|
||||
if (cabinetPush == null) return Ok(APIResponse.Send("001", $"[{summary}], 삭제 할 PUSH 없음", Empty));
|
||||
|
@ -420,20 +429,20 @@ public class PushController : ControllerBase
|
|||
[HttpPost("list")]
|
||||
[CustomOperation("사용자 푸시 목록 조회", "해당 사용자가 받은 푸시의 정보를 조회한다.", "푸시")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(APIResponseStatus<object>))]
|
||||
public async Task<IActionResult> SearchToUserPush(string token, string refresh, int size, [FromBody] PushCabinet? request)
|
||||
public async Task<IActionResult> SearchToUserPush(string token, int size, [FromBody] PushCabinet? request)
|
||||
{
|
||||
if (string.IsNullOrEmpty(token)) return BadRequest(APIResponse.InvalidInputError());
|
||||
if (!ModelState.IsValid) return BadRequest(APIResponse.InvalidInputError());
|
||||
string uid = "";
|
||||
string summary = String.Empty;
|
||||
|
||||
|
||||
try
|
||||
{
|
||||
if (token == "System") uid = "System";
|
||||
else {
|
||||
if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(refresh)) return BadRequest(APIResponse.InvalidInputError());
|
||||
if(!ModelState.IsValid) return BadRequest(APIResponse.InvalidInputError());
|
||||
|
||||
var validateToken = await _repositoryService.ValidateToken(token, refresh);
|
||||
uid = validateToken.uid;
|
||||
var validateToken = await _jwtTokenService.ValidateToken(token);
|
||||
if (validateToken == null) return Ok(APIResponse.AccessExpireError());
|
||||
uid = validateToken.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? string.Empty;
|
||||
}
|
||||
|
||||
summary = _repositoryService.ReadSummary(typeof(PushController), "SearchToUserPush");
|
||||
|
|
|
@ -42,20 +42,20 @@ public class UserController : ControllerBase
|
|||
|
||||
[HttpGet]
|
||||
[CustomOperation("회원 정보 조회", "회원 정보 조회 (자기자신)", "사용자")]
|
||||
public async Task<IActionResult> GetUserData(string token, string refresh)
|
||||
public async Task<IActionResult> GetUserData(string token)
|
||||
{
|
||||
if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(refresh))
|
||||
return BadRequest(APIResponse.InvalidInputError());
|
||||
if (string.IsNullOrEmpty(token)) return BadRequest(APIResponse.InvalidInputError());
|
||||
if (!ModelState.IsValid) return BadRequest(APIResponse.InvalidInputError());
|
||||
string summary = String.Empty;
|
||||
|
||||
try
|
||||
{
|
||||
var validateToken = await _repositoryService.ValidateToken(token, refresh);
|
||||
var validateToken = await _jwtTokenService.ValidateToken(token);
|
||||
if (validateToken == null) return Ok(APIResponse.AccessExpireError());
|
||||
var uid = validateToken.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? string.Empty;
|
||||
summary = _repositoryService.ReadSummary(typeof(UserController), "GetUserData");
|
||||
|
||||
|
||||
var user = await _dbContext.User
|
||||
.Where(u => u.uid == validateToken.uid)
|
||||
.Where(u => u.uid == uid)
|
||||
.Select(u => new User
|
||||
{
|
||||
uid = u.uid,
|
||||
|
@ -70,16 +70,6 @@ public class UserController : ControllerBase
|
|||
|
||||
return Ok(APIResponse.Send("000", $"[{summary}], 정상", user));
|
||||
}
|
||||
catch (TokenException tokenEx)
|
||||
{
|
||||
_logger.LogInformation($"[{summary}] : {tokenEx}");
|
||||
return Ok(APIResponse.Send("001", $"[{summary}], 토큰에 문제가 있음", Empty));
|
||||
}
|
||||
catch (RefreshRevokeException refreshEx)
|
||||
{
|
||||
_logger.LogInformation($"[{summary}] : {refreshEx}");
|
||||
return Ok(APIResponse.Send("001", $"[{summary}], 폐기된 리프레시 토큰", Empty));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return StatusCode(500, APIResponse.UnknownError(ex.Message));
|
||||
|
@ -88,21 +78,22 @@ public class UserController : ControllerBase
|
|||
|
||||
[HttpGet("academy")]
|
||||
[CustomOperation("학원 리스트 확인", "사용자가 등록된 학원 리스트 확인", "사용자")]
|
||||
public async Task<IActionResult> ReadAcademyInfo(string token, string refresh)
|
||||
public async Task<IActionResult> ReadAcademyInfo(string token)
|
||||
{
|
||||
if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(refresh))
|
||||
return BadRequest(APIResponse.InvalidInputError());
|
||||
if (string.IsNullOrEmpty(token)) return BadRequest(APIResponse.InvalidInputError());
|
||||
if (!ModelState.IsValid) return BadRequest(APIResponse.InvalidInputError());
|
||||
string summary = String.Empty;
|
||||
|
||||
try
|
||||
{
|
||||
var validateToken = await _repositoryService.ValidateToken(token, refresh);
|
||||
var validateToken = await _jwtTokenService.ValidateToken(token);
|
||||
if (validateToken == null) return Ok(APIResponse.AccessExpireError());
|
||||
var uid = validateToken.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? string.Empty;
|
||||
|
||||
summary = _repositoryService.ReadSummary(typeof(UserController), "ReadAcademyInfo");
|
||||
|
||||
var academies = await (from ua in _dbContext.UserAcademy
|
||||
join a in _dbContext.Academy on ua.bid equals a.bid
|
||||
where ua.uid == validateToken.uid
|
||||
where ua.uid == uid
|
||||
select new AcademyName
|
||||
{
|
||||
bid = a.bid,
|
||||
|
@ -132,10 +123,10 @@ public class UserController : ControllerBase
|
|||
|
||||
[HttpGet("login")]
|
||||
[CustomOperation("SNS 로그인", "로그인 후 회원이 있는지 확인", "사용자")]
|
||||
public async Task<IActionResult> Login(string acctype, string sns_id)
|
||||
public async Task<IActionResult> Login(string acctype, string snsId)
|
||||
{
|
||||
// API 동작 파라미터 입력 값 확인
|
||||
if (string.IsNullOrEmpty(acctype) && string.IsNullOrEmpty(sns_id))
|
||||
if (string.IsNullOrEmpty(acctype) && string.IsNullOrEmpty(snsId))
|
||||
return BadRequest(APIResponse.InvalidInputError());
|
||||
if (!ModelState.IsValid) return BadRequest(APIResponse.InvalidInputError());
|
||||
string summary = String.Empty;
|
||||
|
@ -145,7 +136,7 @@ public class UserController : ControllerBase
|
|||
summary = _repositoryService.ReadSummary(typeof(UserController), "Login");
|
||||
|
||||
var login = await _dbContext.Login
|
||||
.FirstOrDefaultAsync(l => l.sns_type == acctype && l.sns_id == sns_id);
|
||||
.FirstOrDefaultAsync(l => l.sns_type == acctype && l.sns_id == snsId);
|
||||
|
||||
if (login != null)
|
||||
{
|
||||
|
@ -306,21 +297,20 @@ public class UserController : ControllerBase
|
|||
|
||||
[HttpGet("logout")]
|
||||
[CustomOperation("로그아웃", "사용자 로그아웃", "사용자")]
|
||||
public async Task<IActionResult> Logout(string token, string refresh)
|
||||
public async Task<IActionResult> Logout(string token)
|
||||
{
|
||||
if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(refresh))
|
||||
return BadRequest(APIResponse.InvalidInputError());
|
||||
if (string.IsNullOrEmpty(token)) return BadRequest(APIResponse.InvalidInputError());
|
||||
if (!ModelState.IsValid) return BadRequest(APIResponse.InvalidInputError());
|
||||
string summary = String.Empty;
|
||||
|
||||
try
|
||||
{
|
||||
var validateToken = await _jwtTokenService.ValidateToken(token);
|
||||
if (validateToken == null) return Ok(APIResponse.AccessExpireError());
|
||||
var uid = validateToken.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? string.Empty;
|
||||
|
||||
summary = _repositoryService.ReadSummary(typeof(UserController), "UserRegister");
|
||||
|
||||
// 여기서 애초에 토큰 관련 에러가 2개가 나오게 만들어져 있음
|
||||
var validateToken = await _repositoryService.ValidateToken(token, refresh);
|
||||
|
||||
var refreshToken = await _dbContext.RefreshTokens.FirstOrDefaultAsync(r => r.uid == validateToken.uid);
|
||||
|
||||
var refreshToken = await _dbContext.RefreshTokens.FirstOrDefaultAsync(r => r.uid == uid);
|
||||
|
||||
if (refreshToken != null)
|
||||
{
|
||||
|
@ -332,14 +322,6 @@ public class UserController : ControllerBase
|
|||
// 리프레시 토큰이 없다?? 그럼 이거 무조건 문제지 (이유를 알 수 없는)
|
||||
return Ok(APIResponse.UnknownError());
|
||||
}
|
||||
catch (TokenException tokenEx)
|
||||
{
|
||||
return Ok(APIResponse.Send("101", $"[{summary}], 입력 받은 토큰의 문제", Empty));
|
||||
}
|
||||
catch (RefreshRevokeException refreshEx)
|
||||
{
|
||||
return Ok(APIResponse.Send("102", $"[{summary}], 폐기된 리프레시 토큰", Empty));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return StatusCode(500, APIResponse.UnknownError($"[{summary}], {ex.Message}"));
|
||||
|
@ -349,21 +331,23 @@ public class UserController : ControllerBase
|
|||
|
||||
[HttpGet("cancel")]
|
||||
[CustomOperation("회원 탈퇴", "사용자 탈퇴", "사용자")]
|
||||
public async Task<IActionResult> Cancel(string token, string refresh)
|
||||
public async Task<IActionResult> Cancel(string token)
|
||||
{
|
||||
if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(refresh))
|
||||
return BadRequest(APIResponse.InvalidInputError());
|
||||
if (string.IsNullOrEmpty(token)) return BadRequest(APIResponse.InvalidInputError());
|
||||
if (!ModelState.IsValid) return BadRequest(APIResponse.InvalidInputError());
|
||||
string summary = String.Empty;
|
||||
|
||||
|
||||
try
|
||||
{
|
||||
var validateToken = await _jwtTokenService.ValidateToken(token);
|
||||
if (validateToken == null) return Ok(APIResponse.AccessExpireError());
|
||||
var uid = validateToken.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? string.Empty;
|
||||
|
||||
summary = _repositoryService.ReadSummary(typeof(UserController), "Cancel");
|
||||
|
||||
|
||||
// 여기서 애초에 토큰 관련 에러가 2개가 나오게 만들어져 있음
|
||||
var validateToken = await _repositoryService.ValidateToken(token, refresh);
|
||||
var user = await _dbContext.User.FirstOrDefaultAsync(u => u.uid == validateToken.uid);
|
||||
var user = await _dbContext.User.FirstOrDefaultAsync(u => u.uid == uid);
|
||||
|
||||
if (user == null)
|
||||
return Ok(APIResponse.Send("001", $"[{summary}], 회원 정보 확인 오류", Empty));
|
||||
|
@ -371,7 +355,7 @@ public class UserController : ControllerBase
|
|||
|
||||
var logUser = new LogUser
|
||||
{
|
||||
uid = validateToken.uid,
|
||||
uid = uid,
|
||||
create_date = DateTime.Now,
|
||||
create_uid = "System",
|
||||
log = ""
|
||||
|
@ -388,20 +372,10 @@ public class UserController : ControllerBase
|
|||
returnCode = "001";
|
||||
}
|
||||
|
||||
if (!(await _repositoryService.SaveData<LogUser>(logUser)))
|
||||
_logger.LogError($"[{summary}] : 로그 저장 실패");
|
||||
if (!(await _repositoryService.SaveData<LogUser>(logUser))) _logger.LogError($"[{summary}] : 로그 저장 실패");
|
||||
|
||||
return Ok(APIResponse.Send(returnCode, returnMsg, Empty));
|
||||
|
||||
|
||||
}
|
||||
catch (TokenException tokenEx)
|
||||
{
|
||||
return Ok(APIResponse.Send("101", $"[{summary}], 입력 받은 토큰의 문제", Empty));
|
||||
}
|
||||
catch (RefreshRevokeException refreshEx)
|
||||
{
|
||||
return Ok(APIResponse.Send("102", $"[{summary}], 폐기된 리프레시 토큰", Empty));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
|
11
Program/V1/Models/AuthKey.cs
Normal file
11
Program/V1/Models/AuthKey.cs
Normal file
|
@ -0,0 +1,11 @@
|
|||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
|
||||
namespace AcaMate.V1.Models;
|
||||
|
||||
[Table("authkey")]
|
||||
public class AuthKey
|
||||
{
|
||||
|
||||
}
|
|
@ -18,7 +18,7 @@ namespace AcaMate.V1.Services;
|
|||
|
||||
public interface IRepositoryService
|
||||
{
|
||||
Task<ValidateToken> ValidateToken(string token, string refresh);
|
||||
// Task<ValidateToken> ValidateToken(string token, string refresh);
|
||||
Task<bool> SaveData<T>(T entity, Expression<Func<T, object>> key = null) where T : class;
|
||||
Task<bool> DeleteData<T>(T entity, Expression<Func<T, object>> key = null) where T : class;
|
||||
String ReadSummary(Type type, String name);
|
||||
|
@ -36,63 +36,61 @@ public class RepositoryService: IRepositoryService
|
|||
_logger = logger;
|
||||
_jwtTokenService = jwtTokenService;
|
||||
}
|
||||
//토큰 태울때는 인코딩 된 걸로 태워야지 원본꺼 태우면 데이터에 손상옵니다.
|
||||
/// <summary>
|
||||
/// 실제로 엑세스 토큰과 리프레시 토큰으로 접근 하기 위한 메서드
|
||||
/// </summary>
|
||||
public async Task<ValidateToken> ValidateToken(string token, string refresh)
|
||||
{
|
||||
var principalToken = _jwtTokenService.ValidateToken(token);
|
||||
if (principalToken != null)
|
||||
{
|
||||
var uid = principalToken.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? string.Empty;
|
||||
_logger.LogInformation($"토큰 변환 - {uid}");
|
||||
return new ValidateToken
|
||||
{
|
||||
token = token,
|
||||
refresh = refresh,
|
||||
uid = uid
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogInformation("엑세스 토큰 만료");
|
||||
var refreshToken = await _dbContext.RefreshTokens
|
||||
.FirstOrDefaultAsync(t => t.refresh_token == refresh);
|
||||
if (refreshToken == null)
|
||||
throw new TokenException("입력 받은 토큰 자체의 문제");
|
||||
|
||||
var uid = refreshToken.uid;
|
||||
|
||||
if (refreshToken.revoke_Date < DateTime.Now)
|
||||
throw new RefreshRevokeException("리프레시 토큰 해지");
|
||||
|
||||
if (refreshToken.expire_date > DateTime.Now)
|
||||
{
|
||||
_logger.LogInformation($"인증 완료 리프레시 : {uid}");
|
||||
var access = _jwtTokenService.GenerateJwtToken(uid);
|
||||
|
||||
return new ValidateToken
|
||||
{
|
||||
token = access,
|
||||
refresh = refreshToken.refresh_token,
|
||||
uid = uid
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
refreshToken = _jwtTokenService.GenerateRefreshToken(uid);
|
||||
_logger.LogInformation("리프레시 토큰 만료");
|
||||
// await SaveData<RefreshToken, string>(refreshToken, rt => rt.uid);
|
||||
return new ValidateToken
|
||||
{
|
||||
token = token,
|
||||
refresh = refreshToken.refresh_token,
|
||||
uid = uid
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// public async Task<ValidateToken> ValidateToken(string token, string refresh)
|
||||
// {
|
||||
// var principalToken = await _jwtTokenService.ValidateToken(token);
|
||||
// if (principalToken != null)
|
||||
// {
|
||||
// var uid = principalToken.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? string.Empty;
|
||||
// _logger.LogInformation($"토큰 변환 - {uid}");
|
||||
// return new ValidateToken
|
||||
// {
|
||||
// token = token,
|
||||
// refresh = refresh,
|
||||
// uid = uid
|
||||
// };
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// _logger.LogInformation("엑세스 토큰 만료");
|
||||
// // var refreshToken = await _dbContext.RefreshTokens
|
||||
// // .FirstOrDefaultAsync(t => t.refresh_token == refresh);
|
||||
// // if (refreshToken == null)
|
||||
// // throw new TokenException("입력 받은 토큰 자체의 문제");
|
||||
// //
|
||||
// // var uid = refreshToken.uid;
|
||||
// //
|
||||
// // if (refreshToken.revoke_Date < DateTime.Now)
|
||||
// // throw new RefreshRevokeException("리프레시 토큰 해지");
|
||||
// //
|
||||
// // if (refreshToken.expire_date > DateTime.Now)
|
||||
// // {
|
||||
// // _logger.LogInformation($"인증 완료 리프레시 : {uid}");
|
||||
// // var access = _jwtTokenService.GenerateJwtToken(uid);
|
||||
// //
|
||||
// // return new ValidateToken
|
||||
// // {
|
||||
// // token = access,
|
||||
// // refresh = refreshToken.refresh_token,
|
||||
// // uid = uid
|
||||
// // };
|
||||
// // }
|
||||
// // else
|
||||
// // {
|
||||
// // refreshToken = _jwtTokenService.GenerateRefreshToken(uid);
|
||||
// // _logger.LogInformation("리프레시 토큰 만료");
|
||||
// // // await SaveData<RefreshToken, string>(refreshToken, rt => rt.uid);
|
||||
// // return new ValidateToken
|
||||
// // {
|
||||
// // token = token,
|
||||
// // refresh = refreshToken.refresh_token,
|
||||
// // uid = uid
|
||||
// // };
|
||||
// // }
|
||||
// }
|
||||
// }
|
||||
|
||||
public async Task<bool> SaveData<T>(T entity, Expression<Func<T, object>> key = null) where T : class
|
||||
{
|
||||
|
@ -166,6 +164,7 @@ public class RepositoryService: IRepositoryService
|
|||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public async Task<bool> DeleteData<T>(T entity, Expression<Func<T, object>> key = null) where T : class
|
||||
{
|
||||
|
|
Loading…
Reference in New Issue
Block a user