273 lines
10 KiB
C#
273 lines
10 KiB
C#
using CPRNIMS.Domain.Services;
|
|
using CPRNIMS.Domain.UIContracts.Account;
|
|
using CPRNIMS.Domain.UIContracts.Attachment;
|
|
using CPRNIMS.Domain.UIContracts.CaptCha;
|
|
using CPRNIMS.Infrastructure.Helper;
|
|
using CPRNIMS.Infrastructure.Models.Account;
|
|
using CPRNIMS.Infrastructure.ViewModel.Account;
|
|
using CPRNIMS.WebApps.Controllers.Base;
|
|
using CPRNIMS.WebApps.Models;
|
|
using Microsoft.AspNetCore.Authentication;
|
|
using Microsoft.AspNetCore.Authentication.Cookies;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.IdentityModel.JsonWebTokens;
|
|
using System.Diagnostics;
|
|
using System.Security.Claims;
|
|
using System.Web;
|
|
|
|
namespace CPRNIMS.WebApps.Controllers
|
|
{
|
|
public class HomeController : BaseMethod
|
|
{
|
|
private readonly ILogger<HomeController> _logger;
|
|
private readonly IAccount _account;
|
|
private readonly IAttachment _attachment;
|
|
private readonly ICaptchaService _captchaService;
|
|
private readonly TokenHelper _tokenHelper;
|
|
public HomeController(TokenHelper tokenHelper,
|
|
ErrorLogHelper errorMessageService,
|
|
IWebHostEnvironment webHostEnvironment,
|
|
IAttachment attachment, IAccount account,
|
|
ICaptchaService captchaService) :
|
|
base(errorMessageService, webHostEnvironment,tokenHelper,account)
|
|
{
|
|
_account = account;
|
|
_attachment = attachment;
|
|
_captchaService = captchaService;
|
|
_tokenHelper = tokenHelper;
|
|
}
|
|
[HttpGet]
|
|
public IActionResult GetCaptcha()
|
|
{
|
|
var (code, image) = _captchaService.GenerateCaptcha();
|
|
HttpContext.Session.SetString("CaptchaCode", code);
|
|
return File(image, "image/png");
|
|
}
|
|
public IActionResult ValidateCaptcha(string captchaCode)
|
|
{
|
|
try
|
|
{
|
|
// Decode the captcha code
|
|
var decodedCaptcha = HttpUtility.UrlDecode(captchaCode);
|
|
|
|
// Get stored captcha from session
|
|
var storedCaptcha = HttpContext.Session.GetString("CaptchaCode");
|
|
|
|
if (string.IsNullOrEmpty(storedCaptcha))
|
|
{
|
|
return Json(new
|
|
{
|
|
success = false,
|
|
message = "CAPTCHA has expired. Please refresh and try again."
|
|
});
|
|
}
|
|
|
|
// Compare captcha (case-insensitive)
|
|
bool isValid = decodedCaptcha.Equals(storedCaptcha,
|
|
StringComparison.OrdinalIgnoreCase);
|
|
|
|
return Json(new
|
|
{
|
|
success = isValid,
|
|
message = isValid ? "Validation successful" : "Invalid CAPTCHA code"
|
|
});
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
// Log the error
|
|
return StatusCode(500, new
|
|
{
|
|
success = false,
|
|
message = "An error occurred during validation"
|
|
});
|
|
}
|
|
}
|
|
[HttpPost]
|
|
public async Task<IActionResult> UploadFile(IFormFile file)
|
|
{
|
|
// Save the uploaded file to a temporary location
|
|
var filePath = Path.GetTempFileName();
|
|
using (var stream = new FileStream(filePath, FileMode.Create))
|
|
{
|
|
await file.CopyToAsync(stream);
|
|
}
|
|
|
|
// Call the GoogleDriveService to upload the file
|
|
var googleDriveService = new GoogleDriveService("d");
|
|
var fileId = await googleDriveService.UploadFileAsync(filePath, file.FileName);
|
|
|
|
// Optionally, do something with the file ID
|
|
|
|
return RedirectToAction("Index");
|
|
}
|
|
public IActionResult Index()
|
|
{
|
|
Response.Headers.Add("Cache-Control", "no-cache, no-store, must-revalidate");
|
|
Response.Headers.Add("Pragma", "no-cache");
|
|
Response.Headers.Add("Expires", "0");
|
|
HttpContext.Session.Clear();
|
|
TempData.Clear();
|
|
ViewBag.UserRoles = "";
|
|
var cred = new Infrastructure.Models.Account.User { ErrMessage = false };
|
|
return View(cred);
|
|
}
|
|
public IActionResult Logout()
|
|
{
|
|
Response.Headers.Add("Cache-Control", "no-cache, no-store, must-revalidate");
|
|
Response.Headers.Add("Pragma", "no-cache");
|
|
Response.Headers.Add("Expires", "0");
|
|
HttpContext.Session.Clear();
|
|
TempData.Clear();
|
|
ViewBag.UserRoles = "";
|
|
var cred = new Infrastructure.Models.Account.User { ErrMessage = false };
|
|
return View(cred);
|
|
}
|
|
public async Task<IActionResult> RouteController(User user)
|
|
{
|
|
try
|
|
{
|
|
var storedCaptchaCode = HttpContext.Session.GetString("CaptchaCode");
|
|
if (string.IsNullOrEmpty(storedCaptchaCode))
|
|
{
|
|
return Json(new
|
|
{
|
|
success = false,
|
|
ResponseMessage = "CAPTCHA validation is required."
|
|
});
|
|
}
|
|
|
|
var cred = new LoginVM
|
|
{
|
|
UserName = user.UserName,
|
|
Password = user.Password
|
|
};
|
|
|
|
var login = await _tokenHelper.LoginAsync(cred);
|
|
|
|
if (login == null || login.messCode == 0)
|
|
{
|
|
return Json(new
|
|
{
|
|
success = false,
|
|
responseStatus = login?.messCode ?? 0,
|
|
ResponseMessage = login?.message ?? "Invalid login"
|
|
});
|
|
}
|
|
|
|
DateTime expirationTime = DateTime.UtcNow.AddHours(2);
|
|
|
|
var handler = new JsonWebTokenHandler();
|
|
var jwtToken = handler.ReadJsonWebToken(login.token);
|
|
|
|
var claims = new List<Claim>
|
|
{
|
|
new Claim(ClaimTypes.NameIdentifier, login.userId),
|
|
new Claim(ClaimTypes.Name, login.userName),
|
|
new Claim("FullName", login.fullName),
|
|
new Claim("DepartmentId", Convert.ToString(login.departmentId)),
|
|
new Claim("Company", login.company),
|
|
new Claim("Token", login.token),
|
|
new Claim("TokenExpiry", expirationTime.ToString("O"))
|
|
};
|
|
foreach (var roleClaim in jwtToken.Claims
|
|
.Where(c => c.Type == ClaimTypes.Role))
|
|
{
|
|
claims.Add(new Claim(ClaimTypes.Role, roleClaim.Value));
|
|
}
|
|
if (!string.IsNullOrEmpty(login.refreshToken))
|
|
{
|
|
claims.Add(new Claim("RefreshToken", login.refreshToken));
|
|
}
|
|
|
|
var identity = new ClaimsIdentity(
|
|
claims,
|
|
CookieAuthenticationDefaults.AuthenticationScheme
|
|
);
|
|
|
|
var authProperties = new AuthenticationProperties
|
|
{
|
|
IsPersistent = true,
|
|
ExpiresUtc = DateTimeOffset.UtcNow.AddHours(2),
|
|
AllowRefresh = true
|
|
};
|
|
|
|
await HttpContext.SignInAsync(
|
|
CookieAuthenticationDefaults.AuthenticationScheme,
|
|
new ClaimsPrincipal(identity),
|
|
authProperties
|
|
);
|
|
var currentUser = new Infrastructure.Models.Account.User
|
|
{
|
|
UserId = login.userId,
|
|
UserName = login.userName,
|
|
FullName = login.fullName,
|
|
Company = login.company,
|
|
Token = login.token,
|
|
MyAccess = string.Join(",", jwtToken.Claims
|
|
.Where(c => c.Type == ClaimTypes.Role)
|
|
.Select(c => c.Value))
|
|
};
|
|
|
|
var userAccess = await _account.GetLandingPageByUserId(currentUser, login.token);
|
|
|
|
var landingAction = userAccess?.FirstOrDefault(u => u.AccessTypeId == 1);
|
|
|
|
if (landingAction != null)
|
|
{
|
|
return Json(new
|
|
{
|
|
success = true,
|
|
Response = true,
|
|
responseAction = landingAction.Action,
|
|
responseController = landingAction.Controller
|
|
});
|
|
}
|
|
|
|
return Json(new { success = false, ResponseMessage = "No Access" });
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return Json(new
|
|
{
|
|
success = false,
|
|
ResponseMessage = ex.InnerException?.Message ?? ex.Message
|
|
});
|
|
}
|
|
}
|
|
public async Task<bool> GetUserAttribute(Infrastructure.Models.Account.User user, string token)
|
|
{
|
|
if (user.Password != null && user.UserName != null)
|
|
{
|
|
if (token !=null)
|
|
{
|
|
//Getting the URL
|
|
var URLAttachment = await _attachment.GetAttachmentById(user);
|
|
if (URLAttachment != null)
|
|
{
|
|
GetStoreAttachment(URLAttachment, true);
|
|
return true;
|
|
}
|
|
else
|
|
{
|
|
GetStoreAttachment(URLAttachment, false);
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
public IActionResult Privacy()
|
|
{
|
|
return View();
|
|
}
|
|
|
|
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
|
|
public IActionResult Error()
|
|
{
|
|
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
|
|
}
|
|
}
|
|
}
|