Частично выполнен вход. Изменения в UserStorage

This commit is contained in:
GokaPek 2024-05-26 16:22:04 +04:00
parent 16cb48a2b1
commit df552c39e1
11 changed files with 144 additions and 45 deletions

View File

@ -0,0 +1,48 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using System.Text;
using UniversityContracts.ViewModels;
namespace UniversityClientAppStorekeeper
{
[Route("api/[controller]")]
[ApiController]
public class APIStorekeeper : ControllerBase
{
private static readonly HttpClient _client = new();
public static UserViewModel? Client { get; set; } = null;
public static void Connect(IConfiguration configuration)
{
_client.BaseAddress = new Uri(configuration["IPAddress"]);
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));
}
public static T? GetRequest<T>(string requestUrl)
{
var response = _client.GetAsync(requestUrl);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (response.Result.IsSuccessStatusCode)
{
return JsonConvert.DeserializeObject<T>(result);
}
else
{
throw new Exception(result);
}
}
public static void PostRequest<T>(string requestUrl, T model)
{
var json = JsonConvert.SerializeObject(model);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = _client.PostAsync(requestUrl, data);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (!response.Result.IsSuccessStatusCode)
{
throw new Exception(result);
}
}
}
}

View File

@ -1,6 +1,10 @@
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using UniversityClientApp.Models;
using UniversityClientAppStorekeeper;
using UniversityContracts.BindingModels;
using UniversityContracts.ViewModels;
using UniversityDataModels.Enums;
namespace UniversityClientApp.Controllers
{
@ -23,12 +27,49 @@ namespace UniversityClientApp.Controllers
return View();
}
[HttpGet]
public IActionResult Enter()
{
return View();
}
[HttpPost]
public void Enter(string login, string password)
{
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password))
{
throw new Exception("Ââåäèòå ëîãèí è ïàðîëü");
}
APIStorekeeper.Client = APIStorekeeper.GetRequest<UserViewModel>($"api/user/loginstorekeeper?login={login}&password={password}");
if (APIStorekeeper.Client == null)
{
throw new Exception("Íåâåðíûé ëîãèí/ïàðîëü");
}
Response.Redirect("Index");
}
[HttpGet]
public IActionResult Register()
{
return View();
}
[HttpPost]
public void Register(string login, string password, string email)
{
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(email))
{
throw new Exception("Ââåäèòå ëîãèí, ïàðîëü è ÔÈÎ");
}
APIStorekeeper.PostRequest("api/user/registerstorekeeper", new UserBindingModel
{
Login = login,
Email = email,
Password = password,
Role = UserRole.Êëàäîâùèê
});
Response.Redirect("Enter");
return;
}
public IActionResult Disciplines()
public IActionResult Disciplines()
{
return View();
}
@ -47,11 +88,6 @@ namespace UniversityClientApp.Controllers
return View();
}
public IActionResult Register()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{

View File

@ -1,16 +1,19 @@
using UniversityClientAppStorekeeper;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddControllersWithViews().AddRazorRuntimeCompilation();
var app = builder.Build();
APIStorekeeper.Connect(builder.Configuration);
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
@ -21,7 +24,7 @@ app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();

View File

@ -13,6 +13,11 @@
</PackageReference>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="6.0.26" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\UniversityDatabaseImplement\UniversityDatabaseImplement.csproj" />
</ItemGroup>

View File

@ -3,7 +3,17 @@
}
<div class="text-center">
@{
if (Model == null)
{
<h3 class="display-4">Log in</h3>
<a href="/Home/Enter">Enter</a>
<a href="/Home/Register">Register</a>
return;
}
}
<div class="menu">
<a href="/Home/Disciplines">Disciplines</a>
<a href="/Home/Teachers">Teachers</a>
@ -13,4 +23,6 @@
<div class="header">
<img src="" alt="Logo" class="logo">
</div>
</div>

View File

@ -2,36 +2,24 @@
ViewData["Title"] = "Register";
}
<div class="text-center">
<h2 class="display-4">Регистрация</h2>
<h2 class="display-4">Registration</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Логин:</div>
<div class="col-8"><input type="text" name="email" /></div>
<div class="col-4">Login:</div>
<div class="col-8"><input type="text" name="login" /></div>
</div>
<div class="row">
<div class="col-4">Пароль:</div>
<div class="col-4">Password:</div>
<div class="col-8"><input type="password" name="password" /></div>
</div>
<div class="row">
<div class="col-4">Фамилия:</div>
<div class="col-8"><input type="text" name="lastName" /></div>
<div class="col-4">Email:</div>
<div class="col-8"><input type="text" name="email" /></div>
</div>
<div class="row">
<div class="col-4">Имя:</div>
<div class="col-8"><input type="text" name="firstName" /></div>
</div>
<div class="row">
<div class="col-4">Отчество:</div>
<div class="col-8"><input type="text" name="midleName" /></div>
</div>
<div class="row">
<div class="col-4">Телефон:</div>
<div class="col-8"><input type="text" name="phoneNumber" /></div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Регистрация"
<div class="col-4"><input type="submit" value="Submit"
class="btn btn-primary" /></div>
</div>
</form>

View File

@ -5,5 +5,6 @@
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
"AllowedHosts": "*",
"IPAddress": "http://localhost:5032/"
}

View File

@ -30,16 +30,18 @@ namespace UniversityDatabaseImplement.Implements
}
public UserViewModel? GetElement(UserSearchModel model)
{
if (string.IsNullOrEmpty(model.Login) && string.IsNullOrEmpty(model.Email) && !model.Id.HasValue)
if (string.IsNullOrEmpty(model.Login) && string.IsNullOrEmpty(model.Password))
{
return null;
}
using var context = new UniversityDatabase();
//Поиск пользователя при входе в систему по логину, паролю и его роли (чтобы не могли войти в аккаунты другой роли)
//Поиск пользователя при входе в систему по логину, паролю и его роли (чтобы не могли войти в аккаунты другой роли)
// UPD По роли не ищется
if (!string.IsNullOrEmpty(model.Login) && !string.IsNullOrEmpty(model.Password) && model.Role.HasValue)
{
return context.Users.FirstOrDefault(x => x.Login == model.Login && x.Password == model.Password && x.Role == model.Role)?.GetViewModel;
return context.Users.FirstOrDefault(x => x.Login == model.Login && x.Password == model.Password)?.GetViewModel;
}
//Получение по логину (пользователей с таким логином будет 1 или 0)
if (!string.IsNullOrEmpty(model.Login))

View File

@ -11,7 +11,7 @@ namespace UniversityDatabaseImplement
if (optionsBuilder.IsConfigured == false)
{
//Возможно понадобится писать вместо (localdb) название пк, вот пк Егора: DESKTOP-N8BRIPR; other-name: LAPTOP-DYCTATOR; other-name: DyCTaTOR
optionsBuilder.UseSqlServer(@"Data Source=LAPTOP-DYCTATOR\SQLEXPRESS;Initial Catalog=UniversityDatabaseFull;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True");
optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-N8BRIPR\SQLEXPRESS;Initial Catalog=UniversityDatabaseFull;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True");
}
base.OnConfiguring(optionsBuilder);
}

View File

@ -45,7 +45,17 @@ namespace UniversityRestApi.Controllers
{
try
{
return _logic.ReadElement(new UserSearchModel
//
var x = _logic.ReadElement(new UserSearchModel
{
Login = login,
Password = password,
Role = UserRole.Кладовщик
});
//
return _logic.ReadElement(new UserSearchModel
{
Login = login,
Password = password,

View File

@ -1,6 +0,0 @@
@UniversityRestApi_HostAddress = http://localhost:5032
GET {{UniversityRestApi_HostAddress}}/weatherforecast/
Accept: application/json
###