EFB/Controllers/UserController.cs

101 lines
3.0 KiB
C#
Raw Normal View History

2022-02-28 21:53:28 +00:00
using EFB.Controllers.API;
using EFB.Models;
using EFB.Models.JSON;
using EFB.Sessions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
2021-10-31 18:58:30 +00:00
using System;
using System.Collections.Generic;
using System.Net.Http;
2022-02-28 21:53:28 +00:00
using System.Threading.Tasks;
2021-10-31 18:58:30 +00:00
namespace EFB.Controllers
{
//[Route("[controller]")]
public class UserController : Controller
{
private readonly ILogger<UserController> _logger;
public UserController(ILogger<UserController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
return View();
}
2022-02-28 21:53:28 +00:00
public async Task<IActionResult> Login(string email, string password)
{
2021-10-31 18:58:30 +00:00
2022-02-18 22:01:53 +00:00
if (!Form.FormAuthenticator.ValidateEMail(email))
2021-10-31 18:58:30 +00:00
{
TempData["Error"] = "Please enter a valid E-Mail";
return RedirectToAction("Index", "Home");
}
2022-02-18 22:01:53 +00:00
//API Helper
APIInterface API = new APIInterface();
//Dictionary of Formdata to be encoded
Dictionary<string, string> formData = new Dictionary<string, string>();
formData.Add("grant_type", "client_credentials");
formData.Add("client_id", email);
formData.Add("client_secret", password);
HttpContent content = new FormUrlEncodedContent(formData);
2022-02-28 21:53:28 +00:00
2022-02-18 22:01:53 +00:00
var request = API.Post<Models.JSON.LoginResponse>("https://api.autorouter.aero/v1.0/oauth2/token", null, content);
//Wait for the response to come through
ResponseModel<LoginResponse> response = await request;
if (response.Error != null)
{
TempData["Error"] = response.Error;
TempData["email"] = email;
return RedirectToAction("Index", "Home");
}
//Type cast required but we know response will be of known type
LoginResponse login = response.Result;
//Generate User Session
if (login.error != null)
{
TempData["Error"] = login.error_description;
TempData["email"] = email;
return RedirectToAction("Index", "Home");
}
2022-02-28 21:53:28 +00:00
UserModel user = new UserModel
{
2022-02-18 22:01:53 +00:00
EMail = email,
2022-02-28 21:53:28 +00:00
UserToken = new TokenModel
{
2022-02-18 22:01:53 +00:00
TokenValue = login.access_token,
Expiration = DateTime.UtcNow.AddSeconds(login.expires_in)
}
};
//Using Session Extensions (Store the user session)
HttpContext.Session.SetObject("User", user);
return RedirectToAction("Index", "App");
2021-10-31 18:58:30 +00:00
}
2022-02-28 21:53:28 +00:00
public IActionResult Logout()
{
2022-02-07 20:58:32 +00:00
HttpContext.Session.SetObject("User", null);
return RedirectToAction("Index", "Home");
}
2021-10-31 18:58:30 +00:00
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View("Error!");
}
}
}