using ApiSoftway.Models; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System.IdentityModel.Tokens.Jwt; namespace ApiSoftway.Controllers { [Route("api/[controller]")] [ApiController] public class TokenController : ControllerBase { private readonly ILogger _logger; private readonly IConfiguration? _configuration; private readonly TOKEN_DbContext _token_context; public TokenController(ILogger logger, IConfiguration? configuration, TOKEN_DbContext token_context) { _logger = logger; _configuration = configuration; _token_context = token_context; } private Token fillTokenByInput(string tokenDevice, string tokenLogin) { Token r = new Token(); string ten = "GESA"; string tecnico = getClaimValueByToken(tokenLogin, "codice"); r.tenant = ten; r.usr = tecnico; r.token = tokenDevice; r.ts = DateTime.Now; return r; } private string getClaimValueByToken(string token, string claimName) { string t = string.Empty; var handler = new JwtSecurityTokenHandler(); var jwtSecurityToken = handler.ReadJwtToken(token); if (jwtSecurityToken != null) { var id = jwtSecurityToken.Claims.First(claim => claim.Type == claimName).Value; t = id; } return t; } [HttpPost] [Route("add")] public async Task> addToken(string tokenDevice, string token) { Token_out t = new Token_out(); bool da_inserire = false; try { List co = new List(); if (_token_context is not null && _token_context.tok is not null) { co = await _token_context.tok.Where(c => c.token.Equals(tokenDevice)).ToListAsync(); } Token inp = fillTokenByInput(tokenDevice, token); if (co.Count == 0) { da_inserire = true; } else { //il token c'è. controllo che sia associato all'utente corretto //string ten = getClaimValueByToken(token, "tenant"); string ten = "GESA"; string tecnico = getClaimValueByToken(token, "tccodice"); bool token_corretto_presente = false; foreach (Token tt in co) { if (tt.usr is not null && tt.usr.Equals(tecnico) && tt.tenant is not null && tt.tenant.Equals(ten)) { token_corretto_presente = true; } else { using (var transaction = _token_context.Database.BeginTransaction()) { Token entitasViewModel = _token_context.tok.Where(p => p.Id == tt.Id).FirstOrDefault(); _token_context.Entry(entitasViewModel).State = EntityState.Deleted; await _token_context.SaveChangesAsync(); transaction.Commit(); } } } if (!token_corretto_presente) da_inserire = true; } if (da_inserire) { using (var transaction = _token_context.Database.BeginTransaction()) { await _token_context.tok.AddAsync(inp); await _token_context.SaveChangesAsync(); transaction.Commit(); } t.err_status_code = "200"; } return StatusCode(StatusCodes.Status200OK, t); } catch (Exception ex) { string errmsg = ex.InnerException != null ? ex.InnerException.Message : ex.Message; t.err_title = ex.Message; t.err_detail = errmsg; t.err_status_code = "500"; return StatusCode(StatusCodes.Status500InternalServerError, t); } } } }