VirtualTask/Controllers/LoginController.cs
2023-12-07 09:14:14 +01:00

107 lines
3.4 KiB
C#

using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Diagnostics;
using System.Text;
using VirtualTask.Models;
namespace VirtualTask.Controllers
{
public class LoginController : Controller
{
string apiUrl=string.Empty;
HttpClient client;
SessionHelper helper;
string errMes=string.Empty;
private readonly IConfiguration _configuration;
public LoginController(IConfiguration configuration)
{
client = new HttpClient();
// helper = new SessionHelper(this);
_configuration = configuration;
var key = _configuration["ApplicationInsights:rootUrlApi"];
apiUrl = key;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Login2(Login model)
{
if (ModelState.IsValid)
{
helper = new SessionHelper(this);
string url = apiUrl + "loginTechnicalVT";
Uri baseAddress = new Uri(url);
client.BaseAddress = baseAddress;
ViewBag.Error = string.Empty;
ViewBag.Admin = string.Empty;
LoginOut loginOut = new LoginOut();
string data = JsonConvert.SerializeObject(model);
StringContent content = new StringContent(data, Encoding.UTF8, "application/json");
HttpResponseMessage response = client.PostAsync(baseAddress, content).Result;
if (response.IsSuccessStatusCode)
{
string risultato = response.Content.ReadAsStringAsync().Result;
loginOut = JsonConvert.DeserializeObject<LoginOut>(risultato);
helper.SetStringValue("tok", loginOut.Tok);
helper.SetStringValue("apiUrl", apiUrl);
helper.SetStringValue("tenant", model.Tenant);
helper.SetStringValue("tecnico", model.Username);
helper.SetStringValue("admin", loginOut.Tcsuper != null ? loginOut.Tcsuper : "N");
return RedirectToAction("Index", "Home");
}
else
{
errMes = response.Content.ReadAsStringAsync().Result;
loginOut = JsonConvert.DeserializeObject<LoginOut>(errMes);
helper.SetStringValue("errMsg", loginOut.err_detail);
ViewBag.Error = loginOut.err_detail;
return View();
}
}
else
{
foreach (var Elemento in ModelState.Values)
{
foreach (var Errore in Elemento.Errors)
{
string ErroreRilevato = Errore.ErrorMessage;
}
}
return View();
}
}
public IActionResult Login2()
{
return View();
}
public IActionResult Logout()
{
helper = new SessionHelper(this);
helper.ClearFormatedKey("tok");
helper.ClearFormatedKey("apiUrl");
helper.ClearFormatedKey("tenant");
helper.ClearFormatedKey("tecnico");
helper.ClearFormatedKey("admin");
return RedirectToAction("Login2", "Login");
}
}
}