using EFB.Controllers.API; using EFB.Models; using EFB.Models.JSON; using EFB.Sessions; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; namespace EFB.Controllers { //[Route("[controller]")] public class UserController : Controller { private readonly ILogger _logger; public UserController(ILogger logger) { _logger = logger; } public IActionResult Index() { return View(); } public async Task Login(string email, string password) { //Ensure that the user is not already logged in UserModel user = HttpContext.Session.GetObject("User"); if (user != null) return RedirectToAction("Index", "App"); if (!Form.FormAuthenticator.ValidateEMail(email)) { TempData["Error"] = "Please enter a valid E-Mail"; return RedirectToAction("Index", "Home"); } //API Helper APIInterface API = new APIInterface(); //Dictionary of Formdata to be encoded Dictionary formData = new Dictionary(); formData.Add("grant_type", "client_credentials"); formData.Add("client_id", email); formData.Add("client_secret", password); HttpContent content = new FormUrlEncodedContent(formData); var request = API.Post("https://api.autorouter.aero/v1.0/oauth2/token", null, content); //Wait for the response to come through ResponseModel 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"); } user = new UserModel { EMail = email, UserToken = new TokenModel { 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"); } public IActionResult Logout() { HttpContext.Session.SetObject("User", null); return RedirectToAction("Index", "Home"); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View("Error!"); } } }