201 lines
7.7 KiB
C#
201 lines
7.7 KiB
C#
using Microsoft.AspNetCore.Components;
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Text.Json;
|
|
using TIAMWebApp.Shared.Application.Models.ClientSide;
|
|
using TIAMWebApp.Shared.Application.Models;
|
|
using TIAMWebApp.Shared.Application.Interfaces;
|
|
using Microsoft.JSInterop;
|
|
using AyCode.Interfaces.StorageHandlers;
|
|
using TIAMSharedUI.Resources;
|
|
using Microsoft.Extensions.Localization;
|
|
using AyCode.Services.Loggers;
|
|
using Microsoft.AspNetCore.Components.Authorization;
|
|
using TIAM.Core.Consts;
|
|
using TIAM.Entities.Users;
|
|
|
|
namespace TIAMSharedUI.Pages
|
|
{
|
|
public partial class Login : ComponentBase
|
|
{
|
|
|
|
[Inject]
|
|
public NavigationManager navManager { get; set; }
|
|
[Inject]
|
|
public IUserDataService userDataService { get; set; }
|
|
[Inject]
|
|
public IAcLogWriterClientBase BrowserConsoleLogWriter { get; set; }
|
|
[Inject]
|
|
public IJSRuntime jsRuntime { get; set; }
|
|
[Inject]
|
|
public ISecureStorageHandler secureStorageHandler { get; set; }
|
|
[Inject]
|
|
public IStringLocalizer<MyResources> localizer { get; set; }
|
|
[Inject]
|
|
public ISessionService sessionService { get; set; }
|
|
|
|
[Inject]
|
|
public AuthenticationStateProvider AuthStateProvider { get; set; }
|
|
|
|
//fill loginmodel with fake but valid data
|
|
|
|
//LoginModel loginModel = new();
|
|
|
|
//[Display(Name = "LoginTitleText", ResourceType = typeof(MyResources))]
|
|
public string TitleText { get; set; } = "dda,mnd,amn,a";
|
|
private int currentStep = 1;
|
|
bool loggedIn = false;
|
|
|
|
|
|
private void GoToNextStep()
|
|
{
|
|
currentStep++;
|
|
}
|
|
|
|
private void GoToPreviousStep()
|
|
{
|
|
currentStep--;
|
|
}
|
|
|
|
private async void SubmitLogin()
|
|
{
|
|
currentStep = 1;
|
|
BrowserConsoleLogWriter.Info("Login started: " + "Email: " + loginModel.Email + ", Password: " + loginModel.Password);
|
|
var response = await userDataService.AuthenticateUser(loginModel);
|
|
//var response = await UserDataservice.TestUserApi(30);
|
|
BrowserConsoleLogWriter.Info("Login started");
|
|
BrowserConsoleLogWriter.Info(response);
|
|
|
|
if (!string.IsNullOrEmpty(response))
|
|
{
|
|
//get token and save to local storage
|
|
//parse to Mainresponse from json string
|
|
|
|
|
|
//var Mainresponse = JsonSerializer.Deserialize<MainResponse>(response);
|
|
var mainResponse = JsonSerializer.Deserialize<MainResponse>(response, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
|
|
|
|
if (mainResponse != null)
|
|
{
|
|
|
|
//check for bad request
|
|
//TODO: fix hacky solution
|
|
string authResponseJson = JsonSerializer.Serialize(mainResponse.Content);
|
|
|
|
var authResponse = JsonSerializer.Deserialize<AuthenticationResponse>(authResponseJson, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
|
|
|
|
string accessToken = authResponse.AccessToken;
|
|
|
|
var token = ProcessToken(accessToken);
|
|
|
|
string userId = token.Claims.First(claim => claim.Type == JwtRegisteredClaimNames.NameId).Value;
|
|
string email = token.Claims.First(claim => claim.Type == JwtRegisteredClaimNames.Email).Value;
|
|
|
|
var myId = Guid.Parse(userId);
|
|
//userDataService.User.Email = _email;
|
|
|
|
var userBasicDetails = new UserBasicDetails(userId, email, authResponse.AccessToken, authResponse.RefreshToken);
|
|
|
|
string userBasicDetailsJson = JsonSerializer.Serialize(userBasicDetails);
|
|
|
|
|
|
//save to local storage
|
|
await secureStorageHandler.SaveToSecureStorageAsync(nameof(Setting.UserBasicDetails), userBasicDetailsJson);
|
|
|
|
await AuthStateProvider.GetAuthenticationStateAsync();
|
|
|
|
|
|
if (!mainResponse.IsSuccess)
|
|
{
|
|
//await App.Current.MainPage.DisplayAlert("Error", "Invalid credentials", "Ok");
|
|
//display error message via jsinterop
|
|
BrowserConsoleLogWriter.Info("Invalid credentials");
|
|
navManager.NavigateTo("login");
|
|
}
|
|
else
|
|
{
|
|
//await App.Current.MainPage.DisplayAlert("Success", "Successful login", "Ok");
|
|
//display success message via jsinterop
|
|
BrowserConsoleLogWriter.Info("Successful login");
|
|
var user = await userDataService.IsLoggedInAsync(myId);
|
|
SaveToSessionInfo(user);
|
|
user.UserType = UserType.Admin;
|
|
navManager.NavigateTo("/");
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
else
|
|
{
|
|
//api error
|
|
//await App.Current.MainPage.DisplayAlert("Error", "An error occured while trying to login", "Ok");
|
|
//display error message via jsinterop
|
|
BrowserConsoleLogWriter.Info("An error occured while trying to login");
|
|
navManager.NavigateTo("login");
|
|
}
|
|
|
|
}
|
|
|
|
protected override void OnInitialized()
|
|
{
|
|
|
|
base.OnInitialized();
|
|
if(sessionService.IsAuthenticated)
|
|
{
|
|
navManager.NavigateTo("index");
|
|
}
|
|
|
|
}
|
|
|
|
public JwtSecurityToken ProcessToken(string accessToken)
|
|
{
|
|
var handler = new JwtSecurityTokenHandler();
|
|
var token = handler.ReadJwtToken(accessToken) as JwtSecurityToken;
|
|
return token;
|
|
}
|
|
/// <summary>
|
|
/// This method stores the user data in the session service so we know during navigation that the user is logged in.
|
|
/// </summary>
|
|
/// <param name="user"></param>
|
|
protected void SaveToSessionInfo(UserSessionModel user)
|
|
{
|
|
sessionService.User = user;
|
|
sessionService.IsAuthenticated = true;
|
|
sessionService.HasCompany = user.UserModelDto.UserProductMappings.Count > 0;
|
|
sessionService.IsDriver = CheckIfDriver(user.UserModelDto.UserProductMappings);
|
|
if (user.UserModelDto.Id == TiamConstClient.DevAdminIds[0] || user.UserModelDto.Id == TiamConstClient.DevAdminIds[1])
|
|
{
|
|
sessionService.IsDevAdmin = true;
|
|
}
|
|
foreach (var guid in TiamConstClient.SysAdmins)
|
|
{
|
|
if (user.UserModelDto.Id == guid)
|
|
{
|
|
sessionService.IsSysAdmin = true;
|
|
}
|
|
}
|
|
BrowserConsoleLogWriter.Debug($"Saved to session: IsAuthenticated: {sessionService.IsAuthenticated}, HasCompany: {sessionService.HasCompany}, IsDriver: {sessionService.IsDriver}, IsDevAdmin: {sessionService.IsDevAdmin}, IsSysAdmin: {sessionService.IsSysAdmin}");
|
|
}
|
|
|
|
public bool CheckIfDriver(List<UserProductMapping> Permissions)
|
|
{
|
|
bool _isDriver = false;
|
|
foreach (UserProductMapping Permission in Permissions)
|
|
{
|
|
if (IsPowerOfTwoInSum(2, Permission.Permissions))
|
|
{
|
|
_isDriver = true;
|
|
sessionService.DriverPersmissionId = Permission.Id;
|
|
}
|
|
}
|
|
return _isDriver;
|
|
}
|
|
|
|
public static bool IsPowerOfTwoInSum(int number, int power)
|
|
{
|
|
int powerOfTwo = 1 << power; // Calculate 2^power
|
|
return (number & powerOfTwo) != 0; // Check if the bit at position `power` is set
|
|
}
|
|
}
|
|
}
|