This commit is contained in:
jozsef.b@aycode.com 2023-11-27 09:59:26 +01:00
commit 819ced81e9
47 changed files with 1364 additions and 396 deletions

View File

@ -0,0 +1,54 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using TIAM.Database.DbContexts;
using TIAM.Entities.Auctions;
namespace TIAM.Database.DataLayers.Users
{
public class AuctionDal : TiamDalBase<AuctionDbContext>
{
public AuctionDal() : base()
{
}
public Task<List<AuctionBid>> GetBids()
{
return Ctx.AuctionBids.ToListAsync();
}
public Task<List<AuctionBid>> GetBidsByEmail(string email)
{
Console.WriteLine($"Getting bid from db {email}");
var emailLower = email.ToLower();
return Ctx.AuctionBids.Where(x => x.Email.ToLower() == emailLower).ToListAsync();
}
public async Task<AuctionBid?> GetBidById(Guid id)
{
Console.WriteLine($"Getting bid from db {id}");
return Ctx.AuctionBids.FirstOrDefault(x => x.Id == id);
}
public Task<bool> CreateBidAsync(AuctionBid auctionBid)
{
auctionBid.Created = DateTime.UtcNow;
auctionBid.Modified = DateTime.UtcNow;
Ctx.AuctionBids.Add(auctionBid);
Console.WriteLine($"Saving user to db {auctionBid.Id}, {auctionBid.Email}, {auctionBid.PhoneNumber}");
return Ctx.SaveChangesAsync().ContinueWith(x => x.Result > 0);
}
public Task<bool> UpdateBidAsync(AuctionBid auctionBid)
{
auctionBid.Modified = DateTime.UtcNow;
Ctx.AuctionBids.Update(auctionBid);
return Ctx.SaveChangesAsync().ContinueWith(x => x.Result > 0);
}
}
}

View File

@ -32,6 +32,27 @@ namespace TIAM.Database.DataLayers.Users
return Ctx.Users.SingleOrDefaultAsync(x=>x.Email.ToLower() == emailLower);
}
public virtual Task<User?> GetUserByPhoneNumberAsync(string phoneNumber)
{
Console.WriteLine($"Getting user from db {phoneNumber}");
var phoneNumberLower = phoneNumber.ToLower();
return Ctx.Users.SingleOrDefaultAsync(x=>x.PhoneNumber.ToLower() == phoneNumberLower);
}
public virtual Task<User?> GetUserByEmailOrPhoneNumberAsync(string emailOrPhoneNumber)
{
Console.WriteLine($"Getting user from db {emailOrPhoneNumber}");
var emailOrPhoneNumberLower = emailOrPhoneNumber.ToLower();
return Ctx.Users.SingleOrDefaultAsync(x=>x.Email.ToLower() == emailOrPhoneNumberLower || x.PhoneNumber.ToLower() == emailOrPhoneNumberLower);
}
//get user by Id
public virtual Task<User?> GetUserByIdAsync(Guid id)
{
Console.WriteLine($"Getting user from db {id}");
return Ctx.Users.SingleOrDefaultAsync(x=>x.Id == id);
}
public Task<bool> CreateUserAsync(User user)
{
user.Created = DateTime.UtcNow;
@ -41,11 +62,27 @@ namespace TIAM.Database.DataLayers.Users
return Ctx.SaveChangesAsync().ContinueWith(x=>x.Result > 0);
}
public Task<bool> UpdateUserAsync(User user)
public Task<bool> UpdateUserAsyncOld(User user)
{
user.Modified = DateTime.UtcNow;
Ctx.Users.Update(user);
return Ctx.SaveChangesAsync().ContinueWith(x=>x.Result > 0);
}
public Task<bool> UpdateUserAsync(User user)
{
var existingUser = Ctx.Users.FirstOrDefault(u => u.Email == user.Email);
if (existingUser != null)
{
user.Modified = DateTime.UtcNow;
existingUser = user;
Ctx.Users.Update(existingUser);
return Ctx.SaveChangesAsync().ContinueWith(x => x.Result > 0);
}
else
{
throw new Exception("User not found");
}
}
}
}

View File

@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AyCode.Database.DbContexts;
using Microsoft.EntityFrameworkCore;
using TIAM.Entities.Auctions;
using TIAM.Entities.TransferDestinations;
namespace TIAM.Database.DbContexts
{
public class AuctionDbContext : TiamDbContextBase
{
public virtual DbSet<AuctionBid> AuctionBids { get; set; }
public AuctionDbContext() //: this(string.Empty)
{
}
public AuctionDbContext(DbContextOptions<AuctionDbContext> options) //: this(string.Empty)
{
}
public AuctionDbContext(string name) : base(name)
{
}
public AuctionDbContext(DbContextOptions<DbContext> options, string name) : base(options, name)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.EnableDetailedErrors(true);
base.OnConfiguring(optionsBuilder);
}
}
}

View File

@ -0,0 +1,82 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AyCode.Entities.Interfaces;
using AyCode.Entities.Users;
using AyCode.Interfaces.TimeStampInfo;
namespace TIAM.Entities.Auctions
{
[Table("AuctionBids")]
public class AuctionBid : IEntityGuid, ITimeStampInfo
{
public AuctionBid() { }
public AuctionBid(Guid ownerId, int targetProduct, string email) : this(Guid.NewGuid(), ownerId, targetProduct, email) { }
public AuctionBid(Guid id, Guid ownerId, int targetProductId, string email) : this()
{
Id = id;
OwnerId = ownerId;
TargetProductId = targetProductId;
Email = email;
IsValid = false;
}
public AuctionBid(Guid ownerId, int targetProductId, string email, string phoneNumber) : this(Guid.NewGuid(), ownerId, targetProductId, email,phoneNumber)
{
}
public AuctionBid(Guid id, Guid ownerId, int targetProductId, string email, string? phoneNumber) : this()
{
Id = id;
OwnerId = ownerId;
TargetProductId = targetProductId;
Email = email;
PhoneNumber = phoneNumber;
IsValid = false;
}
public AuctionBid(Guid ownerId, int targetProductId, string email, string phoneNumber, int bidAmount) : this(Guid.NewGuid(), ownerId, targetProductId, email, phoneNumber, bidAmount)
{
OwnerId = ownerId;
TargetProductId = targetProductId;
Email = email;
PhoneNumber = phoneNumber;
BidAmount = bidAmount;
IsValid = false;
}
public AuctionBid(Guid id, Guid ownerId, int targetProductId, string email, string? phoneNumber, int bidAmount) : this()
{
Id = id;
OwnerId = ownerId;
TargetProductId = targetProductId;
Email = email;
PhoneNumber = phoneNumber;
BidAmount = bidAmount;
IsValid = false;
}
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
public Guid Id { get; set; }
public Guid OwnerId { get; set; }
public int TargetProductId { get; set; }
public string Email { get; set; }
public string? PhoneNumber { get; set; }
public int BidAmount { get; set; }
public bool? IsValid { get; set; }
public DateTime Created { get; set; }
public DateTime Modified { get; set; }
}
public enum TargetProductType
{
Product1 = 1,
Product2 = 2,
}
}

View File

@ -4,6 +4,7 @@ using TIAMWebApp.Shared.Application.Interfaces;
using DevExpress.Blazor;
using TIAMMobilApp.Services;
using TIAMWebApp.Shared.Application.Utility;
using AyCode.Interfaces.StorageHandlers;
namespace TIAMMobileApp
{
@ -44,9 +45,9 @@ namespace TIAMMobileApp
builder.Services.AddScoped<ITransferDataService, TransferDataService>();
builder.Services.AddScoped<IPopulationStructureDataProvider, PopulationStructureDataProvider>();
builder.Services.AddScoped<ISupplierService, SupplierService>();
builder.Services.AddScoped<IUserDataService, UserDataService>();
builder.Services.AddScoped<ISecureStorageHandler, SecureStorageHandler>();
builder.Services.AddScoped<LogToBrowserConsole>();
builder.Services.AddScoped<IUserDataService, UserDataServiceMobile>();
builder.Services.AddScoped<ISecureStorageHandler, SecureStorageHandler>();
builder.Services.AddScoped<ISessionService, SessionServiceMobile>();
return builder.Build();
}

View File

@ -1,4 +1,5 @@
using System;
using AyCode.Interfaces.StorageHandlers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

View File

@ -0,0 +1,13 @@
using System.Net;
using TIAMWebApp.Shared.Application.Interfaces;
using TIAMWebApp.Shared.Application.Models;
namespace TIAMMobileApp.Services
{
public class SessionServiceMobile : ISessionService
{
public string? SessionId { get; set; }
public UserSessionModel? User { get; set; }
public IPAddress? IPAddress { get; set; }
}
}

View File

@ -1,4 +1,5 @@
using Microsoft.EntityFrameworkCore.Infrastructure;
using AyCode.Interfaces.StorageHandlers;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.JSInterop;
using Newtonsoft.Json;
using System.Net.Http.Json;
@ -12,16 +13,14 @@ using TIAMWebApp.Shared.Application.Utility;
namespace TIAMMobilApp.Services
{
public class UserDataService : IUserDataService
public class UserDataServiceMobile : IUserDataService
{
private readonly HttpClient http;
private readonly ISecureStorageHandler secureStorageHandler;
public UserModel? User { get; set; } = new UserModel("", "", "");
public Dictionary<int, string> userRoleTypes { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public UserDataService(HttpClient http, ISecureStorageHandler secureStorageHandler)
public UserDataServiceMobile(HttpClient http, ISecureStorageHandler secureStorageHandler)
{
this.http = http;
this.secureStorageHandler = secureStorageHandler;
@ -43,35 +42,26 @@ namespace TIAMMobilApp.Services
};
public async Task<UserModel> IsLoggedInAsync()
public async Task<UserSessionModel> IsLoggedInAsync(Guid id)
{
if (User == null)
{
User = new UserModel("", "", "");
User.IsLoggedIn = false;
User.UserType = UserType.User;
return User;
}
else
{
return User;
}
UserSessionModel User = null;
var dbUser = await GetUserByIdAsync(id);
if (dbUser != null)
{
User = new UserSessionModel(dbUser.Id, UserType.User, dbUser.Email, 1);
return User;
}
else
{
return null;
}
}
//Mock method for now
public async Task<UserModel> AuthorizeUserAsync(int userType)
{
if (User == null)
{
User = new UserModel("", "", "");
}
//simply return true for now
User.IsLoggedIn = true;
User.UserType = (UserType)userType;
return User;
}
public async Task<string> TestUserApi(int Param)
{
@ -86,7 +76,7 @@ namespace TIAMMobilApp.Services
var result = string.Empty;
string result = string.Empty;
var url = APIUrls.AuthenticateUser;
var response = await http.PostAsJsonAsync(url, loginModel);
@ -108,8 +98,9 @@ namespace TIAMMobilApp.Services
public async Task<(bool isSuccess, string ErrorMessage)> CreateUser(RegistrationModel regModel)
{
var isSuccess = true;
var result = string.Empty;
bool isSuccess = true;
string result = string.Empty;
var url = APIUrls.CreateUser;
var response = await http.PostAsJsonAsync(url, regModel);
@ -138,11 +129,14 @@ namespace TIAMMobilApp.Services
{
return await http.GetFromJsonAsync<User?>(APIUrls.GetUserByEmail);
}
public async Task<User?> GetUserByIdAsync(Guid Id)
{
return await http.GetFromJsonAsync<User?>(APIUrls.GetUserById);
}
public async Task<bool> RefreshToken()
{
var isTokenRefreshed = false;
bool isTokenRefreshed = false;
using (var client = new HttpClient())
{
var url = APIUrls.RefreshToken;
@ -158,7 +152,7 @@ namespace TIAMMobilApp.Services
var response = await client.PostAsync(url, new StringContent(serializedStr, Encoding.UTF8, "application/json"));
if (response.IsSuccessStatusCode)
{
var contentStr = await response.Content.ReadAsStringAsync();
string contentStr = await response.Content.ReadAsStringAsync();
var mainResponse = JsonConvert.DeserializeObject<MainResponse>(contentStr);
if (mainResponse.IsSuccess)
{
@ -166,7 +160,7 @@ namespace TIAMMobilApp.Services
Setting.UserBasicDetails.AccessToken = tokenDetails.AccessToken;
Setting.UserBasicDetails.RefreshToken = tokenDetails.RefreshToken;
var userDetailsStr = JsonConvert.SerializeObject(Setting.UserBasicDetails);
string userDetailsStr = JsonConvert.SerializeObject(Setting.UserBasicDetails);
await secureStorageHandler.SaveToSecureStorageAsync(nameof(Setting.UserBasicDetails), userDetailsStr);
isTokenRefreshed = true;
}
@ -174,7 +168,7 @@ namespace TIAMMobilApp.Services
}
catch (Exception ex)
{
var msg = ex.Message;
string msg = ex.Message;
}
@ -185,9 +179,9 @@ namespace TIAMMobilApp.Services
public Task<Dictionary<int, string>> GetUserRolesAsync(UserModel userModel)
{
//TODO Finish this
//get the userModel's roles
var role = User.UserRoles;
int role = userModel.UserRoles;
foreach (var roleType in roleTypes)
{

View File

@ -54,6 +54,11 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Aycode.Blazor\AyCode.Blazor.Components\AyCode.Blazor.Components.csproj" />
<ProjectReference Include="..\..\Aycode.Blazor\AyCode.Blazor.Models\AyCode.Blazor.Models.csproj" />
<ProjectReference Include="..\..\Aycode.Blazor\AyCode.Maui.Core\AyCode.Maui.Core.csproj" />
<ProjectReference Include="..\TIAM.Core\TIAM.Core.csproj" />
<ProjectReference Include="..\TIAM.Entities\TIAM.Entities.csproj" />
<ProjectReference Include="..\TIAMSharedUI\TIAMSharedUI.csproj" />
<ProjectReference Include="..\TIAMWebApp\Shared\TIAMWebApp.Shared.Application.csproj" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" VersionOverride="7.0.1" Version="7.0.1" />

View File

@ -0,0 +1,13 @@
@page "/auction"
@using TIAMSharedUI.Pages.Components
@using TIAMWebApp.Shared.Application.Interfaces;
@using TIAMWebApp.Shared.Application.Models;
@inject ISessionService sessionService
<div class="container-fluid">
<h1>Auction</h1>
<AuctionComponent UserId="sessionService.User.UserId"></AuctionComponent>
</div>
@code {
}

View File

@ -5,6 +5,7 @@
@using Newtonsoft.Json
@using System.IdentityModel.Tokens.Jwt
@using TIAMWebApp.Shared.Application.Models.ClientSide
@using AyCode.Interfaces.StorageHandlers;
@inject NavigationManager NavManager
@inject IJSRuntime JSRuntime
@inject LogToBrowserConsole logToBrowserConsole

View File

@ -0,0 +1,16 @@

<h2>Hello @UserId.ToString()</h2>
<div class="row">
<div class="col-12, col-sm-6">
<AuctionItemComponent AuctionItemId="1"></AuctionItemComponent>
</div>
<div class="col-12, col-sm-6">
<AuctionItemComponent AuctionItemId="2"></AuctionItemComponent>
</div>
</div>
@code {
[Parameter]
public Guid UserId { get; set; }
}

View File

@ -0,0 +1,42 @@
using Microsoft.AspNetCore.Components;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TIAMWebApp.Shared.Application.Models;
namespace TIAMSharedUI.Pages.Components
{
public partial class AuctionItemComponent
{
[Parameter]
public int AuctionItemId { get; set; }
public string IsLoading { get; set; } = "";
public int currentStep = 0;
public AuctionBidModel auctionBidModel = new();
public void NextStep()
{
currentStep++;
}
public void PreviousStep()
{
currentStep--;
}
protected override void OnInitialized()
{
IsLoading = "loaded!";
base.OnInitialized();
}
public void SubmitBid()
{
}
}
}

View File

@ -0,0 +1,57 @@
@using TIAMWebApp.Shared.Application.Models;
<div class="card text-center">
<div style="max-height: 50vh; overflow-y:hidden;">
@{
var url = "_content/TIAMSharedUI/images/auction" + AuctionItemId.ToString() + ".jpg";
}
<img src=@url class="card-img-top" style="margin: 0 auto;" alt="...">
</div>
<div class="card-body">
<h5 class="card-title"><h3>Item @AuctionItemId.ToString()</h3></h5>
<p class="card-text">@IsLoading</p>
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item">An item</li>
<li class="list-group-item">A second item</li>
<li class="list-group-item">A third item</li>
</ul>
<div class="card-body">
<form class="p-3 mt-3">
<div>
@switch (currentStep)
{
case 0:
<AuctionStep0 onNext="NextStep" />
;
break;
case 1:
<AuctionStep1 @bind-AuctionBidModel="auctionBidModel" onNext="NextStep" />
;
break;
case 2:
<AuctionStep2 @bind-AuctionBidModel="auctionBidModel" onNext="NextStep" onPrev="PreviousStep" />
;
break;
case 3:
<AuctionStep3 @bind-AuctionBidModel="auctionBidModel" onSubmit="SubmitBid" onPrev="PreviousStep" />
;
break;
}
</div>
</form>
</div>
<div class="card-footer">
<p>Bid azonosító: @auctionBidModel.Id</p>
<!--a href="#" class="card-link">Card link</a>
<a-- href="#" class="card-link">Another link</a-->
</div>
</div>
@code {
}

View File

@ -0,0 +1,38 @@
@using TIAMWebApp.Shared.Application.Models.PageModels;
<div class="form-field d-flex align-items-center">
<DxButton Click="GoToNextStep">
Licitálok!
</DxButton>
</div>
@code {
[Parameter]
public EventCallback<string> onNext { get; set; }
private string spinnerClass = "";
private async Task GoToNextStep()
{
spinnerClass = "spinner-border spinner-border-sm";
await Task.Delay(500);
spinnerClass = "";
await onNext.InvokeAsync();
}
}

View File

@ -0,0 +1,65 @@
@using TIAMWebApp.Shared.Application.Models.PageModels;
@using TIAMWebApp.Shared.Application.Models;
<EditForm Model="@auctionBidModel" OnValidSubmit="GoToNextStep">
<DataAnnotationsValidator />
<h3>Step 1</h3>
<div class="form-field d-flex align-items-center">
<DxMaskedInput @bind-Value="@auctionBidModel.Email"
Id="Email"
CssClass="cw-320"
Mask="@EmailMask"
MaskMode="MaskMode.RegEx">
<DxRegExMaskProperties MaskAutoCompleteMode="@((MaskAutoCompleteMode)AutoCompleteMode)"
Placeholder="Placeholder"
PlaceholdersVisible="PlaceholderVisible" />
</DxMaskedInput>
</div>
<ValidationMessage For="@(() => auctionBidModel.Email)" />
<button class="btn btn-primary mt-3" type="submit">
<span class="@spinnerClass"></span>
Next
</button>
</EditForm>
@code {
[Parameter]
public AuctionBidModel auctionBidModel { get; set; }
//[Parameter]
//public string Email { get; set; }
[Parameter]
public EventCallback<string> onNext { get; set; }
[Parameter]
public EventCallback<AuctionBidModel> auctionBidModelChanged { get; set; }
IEnumerable<char> PredefinedPlaceholders { get; set; } = new List<char>() { '_', '#' };
string EmailMask { get; set; } = @"(\w|[.-])+@(\w|-)+\.(\w|-){2,4}";
MaskAutoCompleteMode AutoCompleteMode { get; set; } = MaskAutoCompleteMode.Strong;
char Placeholder { get; set; } = '_';
bool PlaceholderVisible { get; set; } = false;
private string spinnerClass = "";
private async Task GoToNextStep()
{
spinnerClass = "spinner-border spinner-border-sm";
await Task.Delay(500);
spinnerClass = "";
auctionBidModel.Id = Guid.NewGuid();
await auctionBidModelChanged.InvokeAsync(auctionBidModel);
await onNext.InvokeAsync();
}
}

View File

@ -0,0 +1,68 @@
@using TIAMWebApp.Shared.Application.Models.PageModels;
<h3>Step 2: Phone Number</h3>
<EditForm Model="@regModel" OnValidSubmit="GoToNextStep">
<DataAnnotationsValidator />
<div class="form-field d-flex align-items-center">
<DxMaskedInput @bind-Value="regModel.PhoneNumber"
Id="PhoneNumber"
Mask="\+(9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d|2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|4[987654310]|3[9643210]|2[70]|7|1)\W*\d\W*\d\W*\d\W*\d\W*\d\W*\d\W*\d\W*\d\W*(\d{1,2})"
MaskMode="@MaskMode.RegEx">
<DxRegExMaskProperties Placeholder="Placeholder"
PlaceholdersVisible=true/>
</DxMaskedInput>
</div>
<ValidationMessage For="@(() => regModel.PhoneNumber)" />
<a class="btn btn-primary mt-3" @onclick="GoToPreviousStep">Previous</a>
<button class="btn btn-primary mt-3" type="submit">
<span class="@spinnerClass"></span>
Next
</button>
</EditForm>
@code {
[Parameter]
public RegistrationModel regModel { get; set; }
[Parameter]
public EventCallback<RegistrationModel> onNext { get; set; }
[Parameter]
public EventCallback<RegistrationModel> onPrev { get; set; }
[Parameter]
public EventCallback<RegistrationModel> RegModelChanged { get; set; }
char Placeholder = '_';
private string spinnerClass = "";
private async Task GoToNextStep()
{
spinnerClass = "spinner-border spinner-border-sm";
await Task.Delay(500);
spinnerClass = "";
await RegModelChanged.InvokeAsync(regModel);
await onNext.InvokeAsync();
}
private async Task GoToPreviousStep()
{
await onPrev.InvokeAsync();
}
}

View File

@ -0,0 +1,64 @@
@using TIAMWebApp.Shared.Application.Models.PageModels;
<h3>Step 3: Password</h3>
<EditForm Model="@regModel" OnValidSubmit="SubmitRegistration">
<DataAnnotationsValidator />
<div class="form-field d-flex align-items-center">
<DxTextBox @bind-Text="@regModel.Password"
Id="Password"
Password="true"
CssClass="cw-320" />
</div>
<ValidationMessage For="@(() => regModel.Password)" />
<a class="btn btn-primary mt-3" @onclick="GoToPreviousStep">Previous</a>
<button class="btn btn-primary mt-3" type="submit">
<span class="@spinnerClass"></span>
Next
</button>
</EditForm>
@code {
[Parameter]
public RegistrationModel regModel { get; set; }
[Parameter]
public EventCallback<RegistrationModel> RegModelChanged { get; set; }
[Parameter]
public EventCallback<RegistrationModel> onPrev { get; set; }
[Parameter]
public EventCallback onSubmit { get; set; }
private string spinnerClass = "";
public async Task SubmitRegistration()
{
spinnerClass = "spinner-border spinner-border-sm";
await Task.Delay(500);
spinnerClass = "";
await RegModelChanged.InvokeAsync(regModel);
await onSubmit.InvokeAsync();
}
private async Task GoToPreviousStep()
{
await onPrev.InvokeAsync();
}
}

View File

@ -1,4 +1,17 @@
@page "/"
@using AyCode.Interfaces.StorageHandlers;
@using Newtonsoft.Json;
@using TIAMWebApp.Shared.Application.Interfaces
@using TIAMWebApp.Shared.Application.Models.ClientSide;
@using AyCode.Blazor.Components;
@using TIAMWebApp.Shared.Application.Models;
@using TIAMWebApp.Shared.Application.Utility;
@using System.IdentityModel.Tokens.Jwt;
@inject NavigationManager NavManager
@inject IUserDataService UserDataService;
@inject IJSRuntime jsRuntime;
@inject ISecureStorageHandler SecureStorageHandler
@inject ISessionService sessionService;
@using TIAMSharedUI.Shared
<PageTitle>Index</PageTitle>
@ -57,6 +70,76 @@
</div>
@code {
bool isUserLoggedIn;
int userType = 0;
int currentUserRole = 249;
public UserSessionModel MyUser;
//add a new dictionary for the role types
protected async override Task OnInitializedAsync()
{
//old
var logToBrowserConsole = new LogToBrowserConsole(jsRuntime);
//wait for 5 seconds
//await Task.Delay(5000);
string userDetailsStr = await SecureStorageHandler.GetFromSecureStorageAsync(nameof(Setting.UserBasicDetails));
logToBrowserConsole.LogToBC(userDetailsStr);
if (!string.IsNullOrWhiteSpace(userDetailsStr))
{
var userBasicDetail = JsonConvert.DeserializeObject<UserBasicDetails>(userDetailsStr);
var handler = new JwtSecurityTokenHandler();
var jsontoken = handler.ReadToken(userBasicDetail?.AccessToken) as JwtSecurityToken;
if (userBasicDetail != null)
Setting.UserBasicDetails = userBasicDetail;
if (jsontoken?.ValidTo < DateTime.UtcNow)
{
logToBrowserConsole.LogToBC("Token needs to be refreshed");
bool isTokenRefreshed = await UserDataService.RefreshToken();
if (isTokenRefreshed)
{
logToBrowserConsole.LogToBC("Token refreshed");
var myId = Guid.Parse(jsontoken.Claims.First(claim => claim.Type == JwtRegisteredClaimNames.NameId).Value);
//UserDataService.User.Email = jsontoken.Claims.First(claim => claim.Type == JwtRegisteredClaimNames.Email).Value;
MyUser = await UserDataService.IsLoggedInAsync(myId);
logToBrowserConsole.LogToBC(MyUser.UserId.ToString());
}
else
{
logToBrowserConsole.LogToBC("Couldn't refresh token");
}
}
else
{
logToBrowserConsole.LogToBC("Valid token found");
var myId = Guid.Parse(jsontoken.Claims.First(claim => claim.Type == JwtRegisteredClaimNames.NameId).Value);
logToBrowserConsole.LogToBC(myId.ToString());
//UserDataService.User.Email = jsontoken.Claims.First(claim => claim.Type == JwtRegisteredClaimNames.Email).Value;
MyUser = await UserDataService.IsLoggedInAsync(myId);
logToBrowserConsole.LogToBC(MyUser.UserId.ToString());
sessionService.User = MyUser;
logToBrowserConsole.LogToBC($"{sessionService.User.UserId.ToString()}, {sessionService.User.Email}.");
}
}
else
{
logToBrowserConsole.LogToBC("No token stored yet");
}
}
}

View File

@ -58,11 +58,11 @@
public async Task next()
{
var user = await userDataService.IsLoggedInAsync();
user.IsLoggedIn = true;
isUserLoggedIn = user.IsLoggedIn;
user.UserType = (UserType)CurrentValue;
navManager.NavigateTo("home");
//var user = await userDataService.IsLoggedInAsync();
//user.IsLoggedIn = true;
//isUserLoggedIn = user.IsLoggedIn;
//user.UserType = (UserType)CurrentValue;
//navManager.NavigateTo("home");
}

View File

@ -10,9 +10,10 @@
@using TIAMWebApp.Shared.Application.Models.ClientSide;
@using TIAMWebApp.Shared.Application.Models;
@using TIAMWebApp.Shared.Application.Utility;
@using AyCode.Interfaces.StorageHandlers;
@inject NavigationManager navManager
@inject LogToBrowserConsole logToBrowserConsole
@inject IUserDataService UserDataservice
@inject IUserDataService userDataService
@inject IJSRuntime jsRuntime
@inject ISecureStorageHandler SecureStorageHandler
@ -86,7 +87,7 @@
currentStep = 1;
logToBrowserConsole.LogToBC("Login started: " + "Email: " + loginModel.Email + ", Password: " + loginModel.Password);
var response = await UserDataservice.AuthenticateUser(loginModel);
var response = await userDataService.AuthenticateUser(loginModel);
//var response = await UserDataservice.TestUserApi(30);
logToBrowserConsole.LogToBC("Login started");
logToBrowserConsole.LogToBC(response);
@ -116,6 +117,9 @@
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);
@ -137,8 +141,7 @@
//await App.Current.MainPage.DisplayAlert("Success", "Successful login", "Ok");
//display success message via jsinterop
logToBrowserConsole.LogToBC("Successful login");
var user = await UserDataservice.IsLoggedInAsync();
user.IsLoggedIn = true;
var user = await userDataService.IsLoggedInAsync(myId);
user.UserType = UserType.Admin;
navManager.NavigateTo("home");

View File

@ -57,12 +57,7 @@
/*IEnumerable<char> PredefinedPlaceholders = new List<char>() { '_', '#' };
string Telephone { get; set; } = "5625595830";
char Placeholder { get; set; } = '_';
bool SaveLiterals { get; set; } = true;*/
private void next()
{
navManager.NavigateTo("register2");
}
bool SaveLiterals { get; set; } = true;*/
private int currentStep = 1;

View File

@ -758,11 +758,7 @@
protected override async Task OnInitializedAsync()
{
base.OnInitialized();
var user = await UserDataService.IsLoggedInAsync();
isUserLoggedIn = user.IsLoggedIn;
userType = (int)user.UserType;
base.OnInitialized();
OrderData = new object[]
{

View File

@ -1,8 +1,17 @@
@inherits LayoutComponentBase
@using AyCode.Interfaces.StorageHandlers;
@using Newtonsoft.Json;
@using TIAMWebApp.Shared.Application.Interfaces
@using TIAMWebApp.Shared.Application.Models.ClientSide;
@using AyCode.Blazor.Components;
@using TIAMWebApp.Shared.Application.Models;
@using TIAMWebApp.Shared.Application.Utility;
@using System.IdentityModel.Tokens.Jwt;
@inject NavigationManager NavManager
@inject IUserDataService UserDataService;
@inject IJSRuntime jsRuntime
@inject IJSRuntime jsRuntime;
@inject ISecureStorageHandler SecureStorageHandler
@inject ISessionService sessionService;
<div class="page">
@ -12,43 +21,18 @@
<main>
<article class="content">
@{
if(isUserLoggedIn)
{
<TopRow></TopRow>
}
}
@if (Setting.UserBasicDetails != null)
{
<TopRow />
}
@Body
</article>
</main>
<div class="footer">
</div>
</div>
@code {
bool isUserLoggedIn;
int userType = 0;
int currentUserRole = 249;
//add a new dictionary for the role types
protected override async Task OnInitializedAsync()
{
var user = await UserDataService.IsLoggedInAsync();
isUserLoggedIn = user.IsLoggedIn;
}
protected override void OnAfterRender(bool isFirst)
{
}
}

View File

@ -1,4 +1,5 @@
@using TIAMWebApp.Shared.Application.Interfaces
@using AyCode.Interfaces.StorageHandlers;
@inject ISecureStorageHandler SecureStorageHandler
<div class="top-row ps-3 navbar navbar-light">
@ -40,6 +41,16 @@
Transfer
</NavLink>
</div>
<div class="nav-item px-3">
<NavLink class="nav-link" href="auction">
Auction
</NavLink>
</div>
<div class="nav-item px-3">
<NavLink class="nav-link" href="swagger">
API
</NavLink>
</div>
<div class="nav-item px-3">
<NavLink class="nav-link" href="login">
Login

View File

@ -1,4 +1,5 @@
@using TIAMWebApp.Shared.Application.Interfaces
@using AyCode.Interfaces.StorageHandlers;
@inject ISecureStorageHandler SecureStorageHandler
<div class="top-row ps-3 navbar navbar-light">

View File

@ -17,6 +17,8 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Aycode.Blazor\AyCode.Blazor.Components\AyCode.Blazor.Components.csproj" />
<ProjectReference Include="..\..\Aycode.Blazor\AyCode.Blazor.Models\AyCode.Blazor.Models.csproj" />
<ProjectReference Include="..\TIAMWebApp\Shared\TIAMWebApp.Shared.Application.csproj" />
</ItemGroup>

Binary file not shown.

After

Width:  |  Height:  |  Size: 286 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 408 KiB

View File

@ -1,3 +1,4 @@
using AyCode.Interfaces.StorageHandlers;
using Blazored.LocalStorage;
using DevExpress.Blazor;
using Microsoft.AspNetCore.Components.Web;
@ -16,10 +17,11 @@ builder.Services.AddScoped<IWeatherForecastService, WeatherForecastService>();
builder.Services.AddScoped<ITransferDataService, TransferDataService>();
builder.Services.AddScoped<IPopulationStructureDataProvider, PopulationStructureDataProvider>();
builder.Services.AddScoped<ISupplierService, SupplierService>();
builder.Services.AddScoped<IUserDataService, UserDataService>();
builder.Services.AddScoped<IUserDataService, UserDataServiceWeb>();
builder.Services.AddScoped<ISecureStorageHandler, SecureStorageHandler>();
builder.Services.AddScoped<LogToBrowserConsole>();
builder.Services.AddBlazoredLocalStorage();
builder.Services.AddSingleton<ISessionService, SessionServiceWeb>();
//WebSpecific
builder.Services.AddScoped<SessionStorageAccessor>();
//WebSpecific end

View File

@ -1,4 +1,5 @@
using Blazored.LocalStorage;
using AyCode.Interfaces.StorageHandlers;
using Blazored.LocalStorage;
using TIAMWebApp.Shared.Application.Interfaces;
namespace TIAMWebApp.Client.Services

View File

@ -0,0 +1,13 @@
using System.Net;
using TIAMWebApp.Shared.Application.Interfaces;
using TIAMWebApp.Shared.Application.Models;
namespace TIAMWebApp.Client.Services
{
public class SessionServiceWeb : ISessionService
{
public string? SessionId { get; set; }
public UserSessionModel? User { get; set; }
public IPAddress? IPAddress { get; set; }
}
}

View File

@ -1,217 +0,0 @@
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.JSInterop;
using Newtonsoft.Json;
using System.Net.Http.Json;
using System.Text;
using TIAM.Entities.TransferDestinations;
using TIAM.Entities.Users;
using TIAMWebApp.Shared.Application.Interfaces;
using TIAMWebApp.Shared.Application.Models;
using TIAMWebApp.Shared.Application.Models.ClientSide;
using TIAMWebApp.Shared.Application.Models.PageModels;
using TIAMWebApp.Shared.Application.Utility;
namespace TIAMWebApp.Client.Services
{
public class UserDataService : IUserDataService
{
private readonly HttpClient http;
private readonly ISecureStorageHandler secureStorageHandler;
private readonly IJSRuntime jsRuntime;
private readonly LogToBrowserConsole logToBrowserConsole;
public UserModel? User { get; set; } = new UserModel("", "", "");
public Dictionary<int, string> userRoleTypes
{
get => throw new NotImplementedException();
set => throw new NotImplementedException();
}
public UserDataService(HttpClient http, ISecureStorageHandler secureStorageHandler, IJSRuntime jSRuntime)
{
this.http = http;
this.secureStorageHandler = secureStorageHandler;
this.jsRuntime = jSRuntime;
this.logToBrowserConsole = new LogToBrowserConsole(jsRuntime);
}
public List<RoleType> roleTypes = new List<RoleType>
{
new RoleType { Id = 1, RoleName = "Login" },
new RoleType { Id = 2, RoleName = "Member" },
new RoleType { Id = 4, RoleName = "Vip" },
new RoleType { Id = 8, RoleName = "Uvip" },
new RoleType { Id = 16, RoleName = "Volunteer" },
new RoleType { Id = 32, RoleName = "Guide" },
new RoleType { Id = 64, RoleName = "Protector" },
new RoleType { Id = 128, RoleName = "Admin" },
new RoleType { Id = 256, RoleName = "SuperAdmin" },
new RoleType { Id = 512, RoleName = "God" }
};
public async Task<UserModel> IsLoggedInAsync()
{
if (User == null)
{
User = new UserModel("", "", "");
User.IsLoggedIn = false;
User.UserType = UserType.User;
return User;
}
else
{
return User;
}
}
//Mock method for now
public async Task<UserModel> AuthorizeUserAsync(int userType)
{
if (User == null)
{
User = new UserModel("", "", "");
}
//simply return true for now
User.IsLoggedIn = true;
User.UserType = (UserType)userType;
return User;
}
public async Task<string> TestUserApi(int Param)
{
var url = APIUrls.UserTest;
var response = await http.PostAsJsonAsync(url, Param);
var result = await response.Content.ReadAsStringAsync();
return result;
}
public async Task<string> AuthenticateUser(LoginModel loginModel)
{
var result = string.Empty;
var url = APIUrls.AuthenticateUser;
var response = await http.PostAsJsonAsync(url, loginModel);
if (response.IsSuccessStatusCode)
{
result = await response.Content.ReadAsStringAsync();
}
else
{
result = await response.Content.ReadAsStringAsync();
}
//result = await response.Content.ReadAsStringAsync();
return result;
}
public async Task<(bool isSuccess, string ErrorMessage)> CreateUser(RegistrationModel regModel)
{
var isSuccess = true;
var result = string.Empty;
var url = $"{Setting.BaseUrl}/{APIUrls.CreateUser}";
logToBrowserConsole.LogToBC("CreateUser url: " + url);
var response = await http.PostAsJsonAsync(url, regModel);
result = await response.Content.ReadAsStringAsync();
/*if (response.IsSuccessStatusCode)
{
isSuccess = true;
result = await response.Content.ReadAsStringAsync();
}
else
{
isSuccess = false;
result = await response.Content.ReadAsStringAsync();
}*/
return (isSuccess, result);
}
public async Task<IEnumerable<User>?> GetUsersAsync()
{
return await http.GetFromJsonAsync<IEnumerable<User>>(APIUrls.GetUsers);
}
public async Task<User?> GetUserByEmailAsync(string email)
{
return await http.GetFromJsonAsync<User?>(APIUrls.GetUserByEmail);
}
public async Task<bool> RefreshToken()
{
logToBrowserConsole.LogToBC("RefreshToken() called");
var isTokenRefreshed = false;
using var client = new HttpClient();
var url = $"{Setting.BaseUrl}{APIUrls.RefreshToken}";
//var url = APIUrls.RefreshToken;
var serializedStr = JsonConvert.SerializeObject(new AuthenticateRequestAndResponse
{
RefreshToken = Setting.UserBasicDetails.RefreshToken,
AccessToken = Setting.UserBasicDetails.AccessToken
});
try
{
logToBrowserConsole.LogToBC("Refreshtoken url: " + url);
var response = await client.PostAsync(url, new StringContent(serializedStr, Encoding.UTF8, "application/json"));
if (response.IsSuccessStatusCode)
{
var contentStr = await response.Content.ReadAsStringAsync();
var mainResponse = JsonConvert.DeserializeObject<MainResponse>(contentStr);
if (mainResponse is { IsSuccess: true })
{
var tokenDetails = JsonConvert.DeserializeObject<AuthenticateRequestAndResponse>(mainResponse.Content.ToString());
Setting.UserBasicDetails.AccessToken = tokenDetails.AccessToken;
Setting.UserBasicDetails.RefreshToken = tokenDetails.RefreshToken;
var userDetailsStr = JsonConvert.SerializeObject(Setting.UserBasicDetails);
await secureStorageHandler.SaveToSecureStorageAsync(nameof(Setting.UserBasicDetails), userDetailsStr);
isTokenRefreshed = true;
}
}
}
catch (Exception ex)
{
var msg = ex.Message;
logToBrowserConsole.LogToBC("Refreshtoken exception: " + ex.ToString());
}
return isTokenRefreshed;
}
public Task<Dictionary<int, string>> GetUserRolesAsync(UserModel userModel)
{
//get the userModel's roles
var role = User.UserRoles;
foreach (var roleType in roleTypes)
{
if ((role & roleType.Id) == roleType.Id)
{
//add the role to the dictionary
userRoleTypes.Add(roleType.Id, roleType.RoleName);
}
}
return Task.FromResult(userRoleTypes);
}
}
}

View File

@ -0,0 +1,215 @@
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.JSInterop;
using Newtonsoft.Json;
using System.Net.Http.Json;
using System.Text;
using TIAM.Entities.TransferDestinations;
using TIAM.Entities.Users;
using TIAMWebApp.Shared.Application.Interfaces;
using TIAMWebApp.Shared.Application.Models;
using TIAMWebApp.Shared.Application.Models.ClientSide;
using TIAMWebApp.Shared.Application.Models.PageModels;
using TIAMWebApp.Shared.Application.Utility;
using AyCode.Interfaces.StorageHandlers;
namespace TIAMWebApp.Client.Services
{
public class UserDataServiceWeb : IUserDataService
{
private readonly HttpClient http;
private readonly ISecureStorageHandler secureStorageHandler;
private readonly IJSRuntime jsRuntime;
private readonly LogToBrowserConsole logToBrowserConsole;
public Dictionary<int, string> userRoleTypes { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public UserDataServiceWeb(HttpClient http, ISecureStorageHandler secureStorageHandler, IJSRuntime jSRuntime)
{
this.http = http;
this.secureStorageHandler = secureStorageHandler;
this.jsRuntime = jSRuntime;
this.logToBrowserConsole = new LogToBrowserConsole(jsRuntime);
}
public List<RoleType> roleTypes = new List<RoleType>
{
new RoleType { Id = 1, RoleName = "Login" },
new RoleType { Id = 2, RoleName = "Member" },
new RoleType { Id = 4, RoleName = "Vip" },
new RoleType { Id = 8, RoleName = "Uvip" },
new RoleType { Id = 16, RoleName = "Volunteer" },
new RoleType { Id = 32, RoleName = "Guide" },
new RoleType { Id = 64, RoleName = "Protector" },
new RoleType { Id = 128, RoleName = "Admin" },
new RoleType { Id = 256, RoleName = "SuperAdmin" },
new RoleType { Id = 512, RoleName = "God" }
};
public async Task<UserSessionModel> IsLoggedInAsync(Guid id)
{
UserSessionModel User = null;
var dbUser = await GetUserByIdAsync(id);
if (dbUser != null)
{
User = new UserSessionModel(dbUser.Id, UserType.User, dbUser.Email, 1);
return User;
}
else
{
return null;
}
}
public async Task<string> TestUserApi(int Param)
{
var url = APIUrls.UserTest;
var response = await http.PostAsJsonAsync(url, Param);
var result = await response.Content.ReadAsStringAsync();
return result;
}
public async Task<string> AuthenticateUser(LoginModel loginModel)
{
string result = string.Empty;
var url = APIUrls.AuthenticateUser;
var response = await http.PostAsJsonAsync(url, loginModel);
if (response.IsSuccessStatusCode)
{
result = await response.Content.ReadAsStringAsync();
}
else
{
result = await response.Content.ReadAsStringAsync();
}
//result = await response.Content.ReadAsStringAsync();
return result;
}
public async Task<(bool isSuccess, string ErrorMessage)> CreateUser(RegistrationModel regModel)
{
bool isSuccess = true;
string result = string.Empty;
var url = $"{Setting.BaseUrl}/{APIUrls.CreateUser}";
logToBrowserConsole.LogToBC("CreateUser url: " + url);
var response = await http.PostAsJsonAsync(url, regModel);
result = await response.Content.ReadAsStringAsync();
/*if (response.IsSuccessStatusCode)
{
isSuccess = true;
result = await response.Content.ReadAsStringAsync();
}
else
{
isSuccess = false;
result = await response.Content.ReadAsStringAsync();
}*/
return (isSuccess, result);
}
public async Task<IEnumerable<User>?> GetUsersAsync()
{
return await http.GetFromJsonAsync<IEnumerable<User>>(APIUrls.GetUsers);
}
public async Task<User?> GetUserByEmailAsync(string email)
{
var url = $"{Setting.BaseUrl}/{APIUrls.GetUserByEmail}";
return await http.GetFromJsonAsync<User?>(url);
}
public async Task<User?> GetUserByIdAsync(Guid Id)
{
var url = $"{Setting.BaseUrl}/{APIUrls.GetUserById}";
logToBrowserConsole.LogToBC("GetUserByIdAsync url: " + url + ", " + Id.ToString());
var response = await http.PostAsJsonAsync(url, Id);
var result = await response.Content.ReadAsStringAsync();
var user = JsonConvert.DeserializeObject<User>(result);
return user;
}
public async Task<bool> RefreshToken()
{
logToBrowserConsole.LogToBC("RefreshToken() called");
bool isTokenRefreshed = false;
using (var client = new HttpClient())
{
var url = $"{Setting.BaseUrl}{APIUrls.RefreshToken}";
//var url = APIUrls.RefreshToken;
var serializedStr = JsonConvert.SerializeObject(new AuthenticateRequestAndResponse
{
RefreshToken = Setting.UserBasicDetails.RefreshToken,
AccessToken = Setting.UserBasicDetails.AccessToken
});
try
{
logToBrowserConsole.LogToBC("Refreshtoken url: " + url);
var response = await client.PostAsync(url, new StringContent(serializedStr, Encoding.UTF8, "application/json"));
if (response.IsSuccessStatusCode)
{
string contentStr = await response.Content.ReadAsStringAsync();
var mainResponse = JsonConvert.DeserializeObject<MainResponse>(contentStr);
if (mainResponse.IsSuccess)
{
var tokenDetails = JsonConvert.DeserializeObject<AuthenticateRequestAndResponse>(mainResponse.Content.ToString());
Setting.UserBasicDetails.AccessToken = tokenDetails.AccessToken;
Setting.UserBasicDetails.RefreshToken = tokenDetails.RefreshToken;
string userDetailsStr = JsonConvert.SerializeObject(Setting.UserBasicDetails);
await secureStorageHandler.SaveToSecureStorageAsync(nameof(Setting.UserBasicDetails), userDetailsStr);
isTokenRefreshed = true;
}
}
}
catch (Exception ex)
{
string msg = ex.Message;
logToBrowserConsole.LogToBC("Refreshtoken exception: " + ex.ToString());
}
}
return isTokenRefreshed;
}
public Task<Dictionary<int, string>> GetUserRolesAsync(UserModel userModel)
{
//TODO: finish this
//get the userModel's roles
int role = userModel.UserRoles;
foreach (var roleType in roleTypes)
{
if ((role & roleType.Id) == roleType.Id)
{
//add the role to the dictionary
userRoleTypes.Add(roleType.Id, roleType.RoleName);
}
}
return Task.FromResult(userRoleTypes);
}
}
}

View File

@ -0,0 +1,168 @@
using DevExpress.Office.Crypto;
using DevExpress.Xpo.DB;
using DevExpress.XtraPrinting;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text.Json;
using TIAMWebApp.Shared.Application.Models;
using TIAMWebApp.Shared.Application.Models.PageModels;
using TIAMWebApp.Server.Models;
using System.Text;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using TIAM.Database.DataLayers.Users;
using AyCode.Utils.Helpers;
using TIAM.Entities.Users;
using TIAMWebApp.Server.ModelsTIAMWebApp.Shared.Application.Models;
using TIAMWebApp.Shared.Application.Utility;
using TIAM.Entities.Auctions;
namespace TIAMWebApp.Server.Controllers
{
[Authorize]
[ApiController]
[Route("api/[controller]")]
public class AuctionAPIController : ControllerBase
{
private AuctionDal _auctionDal;
private readonly IConfiguration _configuration;
private readonly IWebHostEnvironment _webHostEnvironment;
PasswordHasher hasher = new PasswordHasher();
private readonly ILogger<UserAPIController> _logger;
public AuctionAPIController(ILogger<UserAPIController> logger, IConfiguration configuration, IWebHostEnvironment webHostEnvironment, AuctionDal auctionDal)
{
_logger = logger;
_configuration = configuration;
_webHostEnvironment = webHostEnvironment;
_auctionDal = auctionDal;
}
[AllowAnonymous]
[HttpPost]
[Route("CreateBid")]
public async Task<IActionResult> CreateUser([FromBody] AuctionBid SerializedAuctionBidModel)
{
Console.WriteLine("CreateBid called");
//if (string.IsNullOrEmpty(SerializedAuctionBidModel.GetRawText()))
//{
// return BadRequest("SerializedAuctionBidModel is required");
//}
//else
//{
//AuctionBidModel? bid = JObject.Parse(SerializedAuctionBidModel.GetRawText()).ToObject<AuctionBidModel>();
AuctionBid bid = SerializedAuctionBidModel;
AuctionBid finalizedBidModel;
if(bid != null)
{
//add userModel to users array
//Array.Resize(ref users, users.Length + 1);
//users[users.Length - 1] = new UserModel(user.Email, user.PhoneNumber, user.Password);
var userId = bid.OwnerId;
var targetProductId = bid.TargetProductId;
string? email = bid?.Email;
string? phoneNumber = bid?.PhoneNumber;
int bidAmount = bid?.BidAmount ?? 0;
bool isValid = false;
if(userId == Guid.Empty || string.IsNullOrEmpty(email) || targetProductId==0 || bidAmount == 0)
{
return BadRequest("Invalid request");
}
else
{
Console.WriteLine($"Bid to be created: {userId}, {targetProductId}, {email}, {phoneNumber}, {bidAmount}, {isValid}");
finalizedBidModel = new AuctionBid(userId, targetProductId, email, phoneNumber, bidAmount);
await _auctionDal.CreateBidAsync(finalizedBidModel);
return Ok(finalizedBidModel.Id);
}
}
else
{
return BadRequest("Invalid request");
}
//}
}
[AllowAnonymous]
[HttpGet]
[Route("GetBids")]
public Task<List<AuctionBid>> GetBids()
{
//var users = await _userDal.Ctx.Users.ToListAsync();//.GetUsersAsync();
//return users;
return _auctionDal.GetBids();
}
[AllowAnonymous]
[HttpGet]
[Route("GetBidsByEmail")]
public async Task<List<AuctionBid>> GetUserByEmail(string email)
{
return await _auctionDal.GetBidsByEmail(email);
}
[AllowAnonymous]
[HttpPost]
[Route("ValidateBid")]
public async Task<IActionResult> ValidateBid([FromBody] AuctionBid SerializedAuctionBidModel)
{
Console.WriteLine("ValidateBid called");
//var validateBid = JObject.Parse(SerializedAuctionBidModel.GetRawText()).ToObject<AuctionBidModel>();
//check if bid exists
AuctionBid? dbBid = null;
//Console.WriteLine(validateBid?.Id);
Console.WriteLine(SerializedAuctionBidModel?.Id);
//if (validateBid != null)
if (SerializedAuctionBidModel != null)
{
//dbBid = await _auctionDal.GetBidById(validateBid.Id);
dbBid = await _auctionDal.GetBidById(SerializedAuctionBidModel.Id);
}
//check if password is valid
//bool isValidUser = await _userManager.CheckPasswordAsync(userModel, authenticateUser.Password);
//mocking
if (dbBid is null)
{
return Unauthorized("Not found in DB");
}
else
{
//if (dbBid.Email == validateBid?.Email)
if (dbBid.Email == SerializedAuctionBidModel?.Email)
{
Console.WriteLine("Bid is valid");
dbBid.IsValid = true;
//Update userModel with refreshToken!!
await _auctionDal.UpdateBidAsync(dbBid);
return Ok(dbBid.IsValid);
}
else
{
return Unauthorized("Emails not matching");
}
}
}
}
}

View File

@ -11,7 +11,16 @@ using System.Reflection.Metadata;
using TIAMWebApp.Shared.Application.Models;
using static DevExpress.XtraPrinting.Native.ExportOptionsPropertiesNames;
using System.Net;
using GoogleApi.Entities.Maps.Geocoding.Address.Request;
using GoogleApi.Entities.Maps.DistanceMatrix.Response;
using System.Net.Http;
using System.Text.Json;
using GoogleApi.Entities.Maps.Directions.Response;
using GoogleApi.Entities.Maps.Geocoding.Location.Request;
using GoogleApi;
using GoogleApi.Entities.Search.Common.Enums;
using Microsoft.AspNetCore.Razor.TagHelpers;
using GoogleApi.Entities.Maps.AddressValidation.Request;
namespace TIAMWebApp.Server.Controllers
{
@ -20,8 +29,7 @@ namespace TIAMWebApp.Server.Controllers
public class GoogleAPIController : ControllerBase
{
private string _apiKey = "AIzaSyAyEYJkpt2KDa3SJ34UNWO4-dNOJKmUtF8";
private static readonly TripInfo[] Trips = new TripInfo[]
{
@ -32,37 +40,87 @@ namespace TIAMWebApp.Server.Controllers
private readonly ILogger<SupplierAPIController> _logger;
public GoogleAPIController(ILogger<SupplierAPIController> logger)
{
_logger = logger;
}
[HttpGet]
[HttpPost]
[Route("GetAddressForCoordinates")]
public string GetAddressForCoordinates(TripInfo myTrip)
public async Task<string?> GetAddressForCoordinates(TripInfo myTrip)
{
var latitude = Trips[0].StartLatitude; // Example latitude
var latitude = myTrip.StartLatitude; // Example latitude
var longitude = Trips[0].StartLongitude; // Example longitude
var longitude = myTrip.StartLongitude; // Example longitude
Console.WriteLine(latitude);
Console.WriteLine(longitude);
var booo = new Coordinate(latitude, longitude);
var request = new LocationGeocodeRequest
{
Key = _apiKey,
Location = booo
};
try
{
/*var address = locationService.GetAddressFromLatLang(latitude, longitude);
Console.WriteLine(address.Address);
string myaddress = address.Address;
return "myaddress: " + myaddress;*/
return "";
var response = await GoogleMaps.Geocode.LocationGeocode.QueryAsync(request);
if (response.Status == Status.Ok)
{
return response.RawJson;
}
else
{
return "Something wrong";
}
}
catch (System.Net.WebException ex)
catch (Exception ex)
{
Console.WriteLine("Google Maps API Error {0}", ex.Message);
return "Google Maps API Error {0}" + ex.Message;
return ex + "Error occurred while calling GoogleMaps.Geocode.LocationGeocode.QueryAsync";
}
}
//google api call to get coordinates from address
[HttpPost]
[Route("ValidateAddress")]
public async Task<string> ValidateAddress(string address)
{
var request = new AddressValidationRequest
{
Key = _apiKey,
Address = new PostalAddress
{
AddressLines = new List<string>
{
address
}
}
};
var response = await GoogleMaps.AddressValidation.QueryAsync(request);
if (response.Status == Status.Ok)
{
return response.Result.Address.FormattedAddress;
}
else if (response.Status == Status.ZeroResults)
{
return "No results found for the given address.";
}
else
{
return "Something went wrong.";
}
}
[HttpGet]
[Route("GetTravelTime")]
//public string GetTravelTime(TripInfo)
@ -95,7 +153,7 @@ namespace TIAMWebApp.Server.Controllers
{
var request = new DistanceMatrixRequest
{
Key = "AIzaSyAyEYJkpt2KDa3SJ34UNWO4-dNOJKmUtF8",
Key = _apiKey,
Origins = new[]
{
new LocationEx(origin1),
@ -134,5 +192,16 @@ namespace TIAMWebApp.Server.Controllers
}
public class GoogleMapsResponse
{
public string Status { get; set; }
public Result[] Results { get; set; }
}
public class Result
{
public string FormattedAddress { get; set; }
}
}
}

View File

@ -53,37 +53,6 @@ namespace TIAMWebApp.Server.Controllers
}
/*[HttpPost]
[Route("Auth")]
public async Task<IActionResult> AuthenticateUser([FromBody] JsonElement SerializedLoginModel)
{
Console.WriteLine("Auth called");
Console.WriteLine(SerializedLoginModel.GetRawText());
if (string.IsNullOrEmpty(SerializedLoginModel.GetRawText()))
{
return BadRequest("SerializedLoginModel is required");
}
else
{
var userModel = JObject.Parse(SerializedLoginModel.GetRawText()).ToObject<LoginModel>();
Console.WriteLine(userModel.Email);
Console.WriteLine(userModel.Password);
if (userModel.Email == "test@tiam.hu" && userModel.Password == "Asdasd123456")
{
Console.WriteLine("UserModel authenticated");
return Ok("yes");
}
else
{
Console.WriteLine("UserModel NOT authenticated");
return Ok("no");
}
}
}*/
[AllowAnonymous]
[HttpPost]
[Route("AuthenticateUser")]
@ -208,6 +177,7 @@ namespace TIAMWebApp.Server.Controllers
{
//get user from db
dbUser = await _userDal.GetUserByEmailAsync(email.Value);
Console.WriteLine("DbUser email: " + dbUser?.Email);
}
//mocking - update userModel with new refreshToken so it returns true after the check below
@ -216,6 +186,7 @@ namespace TIAMWebApp.Server.Controllers
if (dbUser is null || dbUser.RefreshToken != refreshTokenRequest.RefreshToken)
{
response.ErrorMessage = "Invalid Request";
Console.WriteLine($"{dbUser?.RefreshToken}, {refreshTokenRequest.RefreshToken}");
return BadRequest(response);
}
@ -224,7 +195,8 @@ namespace TIAMWebApp.Server.Controllers
//mocking - update userModel with new refreshToken
dbUser.RefreshToken = refreshToken;
//await _userManager.UpdateAsync(userModel);
//TODO await _userManager.UpdateAsync(userModel);
await _userDal.UpdateUserAsync(dbUser);
response.IsSuccess = true;
response.Content = new AuthenticationResponse
@ -361,6 +333,16 @@ namespace TIAMWebApp.Server.Controllers
return await _userDal.GetUserByEmailAsync(email);
}
[AllowAnonymous]
[HttpPost]
[Route("GetUserById")]
public async Task<User?> GetUserById([FromBody] Guid id)
{
Console.WriteLine($"GetUserById called with id: {id}");
return await _userDal.GetUserByIdAsync(id);
}
private bool VerifyPassword(string password, string hashedPassword)
{
bool isPasswordValid = hasher.VerifyPassword(password, hashedPassword);

View File

@ -23,6 +23,7 @@ builder.Services.AddRazorPages();
//builder.Services.AddDbContext<TransferDestinationDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DeveloperDbConnection")));;
builder.Services.AddScoped<UserDal>();
builder.Services.AddScoped<AdminDal>();
builder.Services.AddScoped<AuctionDal>();
builder.Services.AddScoped<TransferDestinationDal>();
builder.Services.AddSwaggerGen(swagger =>

View File

@ -18,6 +18,7 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\Aycode.Blazor\AyCode.Blazor.Controllers\AyCode.Blazor.Controllers.csproj" />
<ProjectReference Include="..\..\TIAM.Database\TIAM.Database.csproj" />
<ProjectReference Include="..\..\TIAM.Entities.Server\TIAM.Entities.Server.csproj" />
<ProjectReference Include="..\..\TIAM.Entities\TIAM.Entities.csproj" />

View File

@ -1,17 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TIAMWebApp.Shared.Application.Interfaces
{
public interface ISecureStorageHandler
{
public Task SaveToSecureStorageAsync(string key, string value);
public Task<string> GetFromSecureStorageAsync(string key);
public Task DeleteFromSecureStorageAsync(string key);
public Task ClearAllSecureStorageAsync();
}
}

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using TIAMWebApp.Shared.Application.Models;
namespace TIAMWebApp.Shared.Application.Interfaces
{
public interface ISessionService
{
public string? SessionId { get; set; }
public UserSessionModel? User { get; set; }
public IPAddress? IPAddress { get; set; }
}
}

View File

@ -11,13 +11,9 @@ namespace TIAMWebApp.Shared.Application.Interfaces
{
public interface IUserDataService
{
public UserModel? User { get; set; }
public Dictionary<int, string> userRoleTypes { get; set; }
public Task<UserModel> IsLoggedInAsync();
//mock method for now
public Task<UserModel> AuthorizeUserAsync(int userType);
public Task<UserSessionModel> IsLoggedInAsync(Guid id);
public Task<string> AuthenticateUser(LoginModel loginModel);
public Task<(bool isSuccess, string ErrorMessage)> CreateUser(RegistrationModel regModel);

View File

@ -10,6 +10,7 @@ namespace TIAMWebApp.Shared.Application.Models
{
public const string UserTest = "api/UserAPI/test1";
public const string GetUserByEmail = "api/UserAPI/GetUserByEmail";
public const string GetUserById = "api/UserAPI/GetUserById";
public const string GetUsers = "api/UserAPI/GetUsers";
public const string AuthenticateUser = "api/UserAPI/AuthenticateUser";
public const string CreateUser = "api/UserAPI/CreateUser";

View File

@ -0,0 +1,14 @@
using TIAM.Entities.Auctions;
namespace TIAMWebApp.Shared.Application.Models
{
public class AuctionBidModel : AuctionBid
{
public AuctionBidModel() { }
public AuctionBidModel(Guid Id, Guid ownerId, int targetProduct, string email, string phoneNumber, int bidAmount) : base(ownerId, targetProduct, email, phoneNumber, bidAmount)
{ }
}
}

View File

@ -23,13 +23,4 @@ namespace TIAMWebApp.Shared.Application.Models
}
public enum UserType
{
Hotel = 1,
Transfer = 2,
Guide = 3,
Admin = 4,
User = 5,
Driver= 6
}
}

View File

@ -0,0 +1,32 @@
using TIAM.Entities.Users;
namespace TIAMWebApp.Shared.Application.Models
{
public class UserSessionModel
{
public Guid UserId { get; set; }
public UserType UserType { get; set; }
public string Email { get; set; }
public int UserRoles { get; set; }
public Dictionary<int, string> UserRolesDictionary { get; set; }
public UserSessionModel(Guid userId, UserType userType, string email, int userRoles)
{
UserId = userId;
UserType = userType;
Email = email;
UserRoles = userRoles;
UserRolesDictionary = new Dictionary<int, string>();
}
}
public enum UserType
{
Hotel = 1,
Transfer = 2,
Guide = 3,
Admin = 4,
User = 5,
Driver = 6
}
}

View File

@ -23,6 +23,16 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TIAM.Entities.Server", "TIA
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TIAM.Core", "TIAM.Core\TIAM.Core.csproj", "{4FDE0CD3-5914-4919-933B-6B0E04275313}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AyCode.Blazor.Components", "..\Aycode.Blazor\AyCode.Blazor.Components\AyCode.Blazor.Components.csproj", "{374FDE0D-C289-4069-AD74-AF32B81F9240}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AyCode.Blazor.Controllers", "..\Aycode.Blazor\AyCode.Blazor.Controllers\AyCode.Blazor.Controllers.csproj", "{75A00A4B-6A04-40E8-99FF-507B26E69DDA}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AyCode.Maui.Core", "..\Aycode.Blazor\AyCode.Maui.Core\AyCode.Maui.Core.csproj", "{E0D4D619-4F6C-4165-95CE-EB295947E4E3}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AyCode.Blazor.Models", "..\Aycode.Blazor\AyCode.Blazor.Models\AyCode.Blazor.Models.csproj", "{C0597140-AD8D-464B-B032-E11F7BC570BA}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AyCode.Blazor.Models.Server", "..\Aycode.Blazor\AyCode.Blazor.Models.Server\AyCode.Blazor.Models.Server.csproj", "{A36322E8-F485-455E-84AA-B911948B6702}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -71,6 +81,26 @@ Global
{4FDE0CD3-5914-4919-933B-6B0E04275313}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4FDE0CD3-5914-4919-933B-6B0E04275313}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4FDE0CD3-5914-4919-933B-6B0E04275313}.Release|Any CPU.Build.0 = Release|Any CPU
{374FDE0D-C289-4069-AD74-AF32B81F9240}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{374FDE0D-C289-4069-AD74-AF32B81F9240}.Debug|Any CPU.Build.0 = Debug|Any CPU
{374FDE0D-C289-4069-AD74-AF32B81F9240}.Release|Any CPU.ActiveCfg = Release|Any CPU
{374FDE0D-C289-4069-AD74-AF32B81F9240}.Release|Any CPU.Build.0 = Release|Any CPU
{75A00A4B-6A04-40E8-99FF-507B26E69DDA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{75A00A4B-6A04-40E8-99FF-507B26E69DDA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{75A00A4B-6A04-40E8-99FF-507B26E69DDA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{75A00A4B-6A04-40E8-99FF-507B26E69DDA}.Release|Any CPU.Build.0 = Release|Any CPU
{E0D4D619-4F6C-4165-95CE-EB295947E4E3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E0D4D619-4F6C-4165-95CE-EB295947E4E3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E0D4D619-4F6C-4165-95CE-EB295947E4E3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E0D4D619-4F6C-4165-95CE-EB295947E4E3}.Release|Any CPU.Build.0 = Release|Any CPU
{C0597140-AD8D-464B-B032-E11F7BC570BA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C0597140-AD8D-464B-B032-E11F7BC570BA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C0597140-AD8D-464B-B032-E11F7BC570BA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C0597140-AD8D-464B-B032-E11F7BC570BA}.Release|Any CPU.Build.0 = Release|Any CPU
{A36322E8-F485-455E-84AA-B911948B6702}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A36322E8-F485-455E-84AA-B911948B6702}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A36322E8-F485-455E-84AA-B911948B6702}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A36322E8-F485-455E-84AA-B911948B6702}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE