POS_Sprint_1 #3

Merged
s426229 merged 12 commits from POS_Sprint_1 into develop 2020-12-07 19:41:00 +01:00
40 changed files with 16222 additions and 7312 deletions

View File

@ -1,11 +1,11 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.28307.1300
# Visual Studio Version 16
VisualStudioVersion = 16.0.30717.126
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Klient.Android", "Klient\Klient.Android\Klient.Android.csproj", "{8FF60786-AD97-4373-9B4D-6EF28BE7C2A2}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Poszukiwacz", "Klient\Klient.Android\Poszukiwacz.csproj", "{8FF60786-AD97-4373-9B4D-6EF28BE7C2A2}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Klient", "Klient\Klient\Klient.csproj", "{46672F33-450A-4DD4-BA9F-C15E88C20AC8}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Klient", "Klient\Klient\Klient.csproj", "{46672F33-450A-4DD4-BA9F-C15E88C20AC8}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution

View File

@ -6,20 +6,97 @@ using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Xamarin.Essentials;
using System.Net.Http;
using System.Collections.Generic;
using System.Security;
using System.Net;
using System.Linq;
namespace Klient.Droid
{
[Activity(Label = "Klient", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
private static readonly HttpClient client = new HttpClient();
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
SetContentView(Resource.Layout.ekranLogowania);
}
[Java.Interop.Export("SignIn")]
async public void SignIn(View v)
{
var Login = FindViewById<EditText>(Resource.Id.Login).Text;
SecureString Password = new NetworkCredential("", FindViewById<EditText>(Resource.Id.Password).Text).SecurePassword;
if(Login.Length < 3 || Login.Length > 12)
{
SetContentView(Resource.Layout.ekranLogowania);
}
if(string.IsNullOrWhiteSpace(new NetworkCredential("", Password).Password))
{
SetContentView(Resource.Layout.ekranLogowania);
}
var values = new Dictionary<string, string>
{
{ "login", Login },
{ "password", new NetworkCredential("", Password).Password }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("https://localhost:44371/api/User/SignIn", content);
var responseString = await response.Content.ReadAsStringAsync();
}
[Java.Interop.Export("ResetPassword")]
async public void ResetPassword()
{
}
[Java.Interop.Export("SignUp")]
async public void SignUp()
{
var Name = FindViewById<EditText>(Resource.Id.Name).Text;
var Surname = FindViewById<EditText>(Resource.Id.Surname).Text;
var Email = FindViewById<EditText>(Resource.Id.Email).Text;
var Login = FindViewById<EditText>(Resource.Id.NewLogin).Text;
SecureString Password = new NetworkCredential("", FindViewById<EditText>(Resource.Id.NewPassword).Text).SecurePassword;
SecureString Password2 = new NetworkCredential("", FindViewById<EditText>(Resource.Id.RepeatPassword).Text).SecurePassword;
if(new NetworkCredential("", Password).Password != new NetworkCredential("", Password2).Password)
{
SetContentView(Resource.Layout.ekranRejestracji);
}
var values = new Dictionary<string, string>
{
{ "email", Email },
{ "name", Name },
{ "surname", Surname },
{ "login", Login },
{ "password", new NetworkCredential("", Password).Password }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("https://localhost:44371/api/User/Register", content);
var responseString = await response.Content.ReadAsStringAsync();
}
[Java.Interop.Export("HelpLoginScreen")]
public void HelpLoginScreen(View v)
{
SetContentView(Resource.Layout.ekranRejestracji);
}
}
}

View File

@ -8,7 +8,7 @@
<TemplateGuid>{c9e5eea5-ca05-42a1-839b-61506e0a37df}</TemplateGuid>
<OutputType>Library</OutputType>
<RootNamespace>Klient.Droid</RootNamespace>
<AssemblyName>Klient.Android</AssemblyName>
<AssemblyName>Poszukiwacz</AssemblyName>
<AndroidApplication>True</AndroidApplication>
<AndroidResgenFile>Resources\Resource.designer.cs</AndroidResgenFile>
<AndroidResgenClass>Resource</AndroidResgenClass>
@ -16,7 +16,7 @@
<MonoAndroidResourcePrefix>Resources</MonoAndroidResourcePrefix>
<MonoAndroidAssetsPrefix>Assets</MonoAndroidAssetsPrefix>
<AndroidUseLatestPlatformSdk>false</AndroidUseLatestPlatformSdk>
<TargetFrameworkVersion>v8.1</TargetFrameworkVersion>
<TargetFrameworkVersion>v9.0</TargetFrameworkVersion>
<AndroidHttpClientHandlerType>Xamarin.Android.Net.AndroidClientHandler</AndroidHttpClientHandlerType>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
@ -30,6 +30,11 @@
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<AndroidLinkMode>None</AndroidLinkMode>
<AotAssemblies>false</AotAssemblies>
<EnableLLVM>false</EnableLLVM>
<AndroidEnableProfiledAot>false</AndroidEnableProfiledAot>
<BundleAssemblies>false</BundleAssemblies>
<MandroidI18n />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@ -43,18 +48,23 @@
</PropertyGroup>
<ItemGroup>
<Reference Include="Mono.Android" />
<Reference Include="Mono.Android.Export" />
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Xamarin.Forms" Version="3.4.0.1008975" />
<PackageReference Include="Xamarin.Android.Support.Design" Version="27.0.2.1" />
<PackageReference Include="Xamarin.Android.Support.v7.AppCompat" Version="27.0.2.1" />
<PackageReference Include="Xamarin.Android.Support.v4" Version="27.0.2.1" />
<PackageReference Include="Xamarin.Android.Support.v7.CardView" Version="27.0.2.1" />
<PackageReference Include="Xamarin.Android.Support.v7.MediaRouter" Version="27.0.2.1" />
<PackageReference Include="Xamarin.Essentials">
<Version>1.5.3.2</Version>
</PackageReference>
<PackageReference Include="Xamarin.Forms" Version="4.8.0.1687" />
<PackageReference Include="Xamarin.Android.Support.Design" Version="28.0.0.3" />
<PackageReference Include="Xamarin.Android.Support.v7.AppCompat" Version="28.0.0.3" />
<PackageReference Include="Xamarin.Android.Support.v4" Version="28.0.0.3" />
<PackageReference Include="Xamarin.Android.Support.v7.CardView" Version="28.0.0.3" />
<PackageReference Include="Xamarin.Android.Support.v7.MediaRouter" Version="28.0.0.3" />
</ItemGroup>
<ItemGroup>
<Compile Include="MainActivity.cs" />
@ -67,8 +77,6 @@
<None Include="Properties\AndroidManifest.xml" />
</ItemGroup>
<ItemGroup>
<AndroidResource Include="Resources\layout\Tabbar.axml" />
<AndroidResource Include="Resources\layout\Toolbar.axml" />
<AndroidResource Include="Resources\values\styles.xml" />
<AndroidResource Include="Resources\values\colors.xml" />
<AndroidResource Include="Resources\mipmap-anydpi-v26\icon.xml" />
@ -98,5 +106,20 @@
<Name>Klient</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<AndroidResource Include="Resources\layout\ekranLogowania.xml">
<SubType>Designer</SubType>
</AndroidResource>
</ItemGroup>
<ItemGroup>
<AndroidResource Include="Resources\layout\ekranRejestracji.xml">
<SubType>Designer</SubType>
</AndroidResource>
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath)\Xamarin\Android\Xamarin.Android.CSharp.targets" />
<ProjectExtensions>
<VisualStudio>
<UserProperties TriggeredFromHotReload="False" />
</VisualStudio>
</ProjectExtensions>
</Project>

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.Klient.Android">
<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="27" />
<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="28" />
<application android:label="Klient.Android"></application>
</manifest>

File diff suppressed because it is too large Load Diff

View File

@ -1,11 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.TabLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:tabIndicatorColor="@android:color/white"
app:tabGravity="fill"
app:tabMode="fixed" />

View File

@ -1,9 +0,0 @@
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

View File

@ -0,0 +1,93 @@
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffbdd7f0"
>
<android.support.design.widget.TextInputEditText
android:layout_width="204.0dp"
android:layout_height="58.0dp"
android:id="@+id/Login"
android:layout_alignParentStart="false"
android:minWidth="25px"
android:minHeight="25px"
android:layout_centerInParent="false"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true"
android:hint="Login"
android:gravity="center_horizontal|center_vertical"
android:textColor="#ff000000"
android:textColorHint="#ff6c6767" />
<android.support.design.widget.TextInputEditText
android:layout_width="204.0dp"
android:layout_height="58.0dp"
android:id="@+id/Password"
android:layout_centerHorizontal="true"
android:layout_below="@+id/Login"
android:hint="Hasło"
android:gravity="center_horizontal|center_vertical"
android:inputType="none|textPassword"
android:textColor="#ff000000"
android:textColorHint="#ff6c6767" />
<Button
android:layout_width="100.5dp"
android:layout_height="50dp"
android:id="@+id/In"
android:layout_below="@id/Password"
android:layout_alignParentRight="false"
android:gravity="center"
android:onClick="SignIn"
android:text="Zaloguj"
android:layout_centerHorizontal="true"
android:foregroundGravity="center" />
<Button
android:text=" Reset \n Hasła"
android:layout_width="100.5dp"
android:layout_height="50dp"
android:id="@+id/Reset"
android:gravity="center"
android:layout_below="@id/In"
android:layout_alignParentRight="false"
android:autoSizeTextType="uniform"
android:onClick="ResetPassword"
android:textColor="#ff790000"
android:layout_centerHorizontal="true"
android:foregroundGravity="center" />
<Button
android:text="?"
android:layout_width="35.0dp"
android:layout_height="35.0dp"
android:id="@+id/help"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:background="#ff0b31c8"
android:textColor="#fffcfcfc"
android:gravity="center"
android:onClick="HelpLoginScreen" />
<TextView
android:text="Poszukiwacz 2020"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/text1"
android:textColor="#ff000000"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/LoginPasswordSee"
android:layout_below="@id/Login"
android:layout_toRightOf="@id/Password" />
</RelativeLayout>

View File

@ -0,0 +1,126 @@
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffbdd7f0">
<android.support.design.widget.TextInputEditText
android:layout_width="204.0dp"
android:layout_height="58.0dp"
android:minWidth="25px"
android:minHeight="25px"
android:id="@+id/Name"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:capitalize="words"
android:textColorHint="#ff6c6767"
android:textColor="#ff000000"
android:hint="Imie"
android:gravity="center"
android:inputType="none|textPersonName" />
<android.support.design.widget.TextInputEditText
android:layout_width="204.0dp"
android:layout_height="58.0dp"
android:minWidth="25px"
android:minHeight="25px"
android:id="@+id/Surname"
android:hint="Nazwisko"
android:textColorHint="#ff6c6767"
android:layout_below="@id/Name"
android:gravity="center"
android:textColor="#ff000000"
android:inputType="none|textPersonName" />
<android.support.design.widget.TextInputEditText
android:layout_width="204.0dp"
android:layout_height="58.0dp"
android:minWidth="25px"
android:minHeight="25px"
android:id="@+id/Email"
android:layout_below="@+id/NewLogin"
android:hint="Email"
android:gravity="center"
android:textColorHint="#ff6c6767"
android:textColor="#ff000000"
android:inputType="none|textEmailAddress" />
<android.support.design.widget.TextInputEditText
android:layout_width="204.0dp"
android:layout_height="58.0dp"
android:minWidth="25px"
android:minHeight="25px"
android:id="@+id/NewPassword"
android:hint="Hasło"
android:layout_below="@+id/Email"
android:gravity="center"
android:inputType="none|textPassword"
android:textColorHint="#ff6c6767" />
<android.support.design.widget.TextInputEditText
android:layout_width="204.0dp"
android:layout_height="58.0dp"
android:minWidth="25px"
android:minHeight="25px"
android:id="@+id/RepeatPassword"
android:layout_below="@+id/NewPassword"
android:hint="Powtórz hasło"
android:inputType="none|textPassword"
android:gravity="center"
android:textColorHint="#ff6c6767"
android:textColor="#ff000000" />
<android.support.design.widget.TextInputEditText
android:layout_width="204.0dp"
android:layout_height="58.0dp"
android:minWidth="25px"
android:minHeight="25px"
android:id="@+id/NewLogin"
android:hint="Login"
android:gravity="center"
android:textColorHint="#ff6c6767"
android:textColor="#ff000000"
android:layout_below="@+id/Surname" />
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/PasswordSee1"
android:layout_toRightOf="@id/NewPassword"
android:layout_below="@id/Email" />
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/PasswordSee2"
android:layout_toRightOf="@id/RepeatPassword"
android:layout_below="@id/NewPassword"
android:checked="false" />
<Button
android:text=" Załóż \n konto"
android:layout_width="100.5dp"
android:layout_height="50dp"
android:id="@+id/SignUp"
android:autoSizeTextType="uniform"
android:gravity="center"
android:layout_below="@id/RepeatPassword"
android:layout_alignParentRight="false"
android:foregroundGravity="center"
android:layout_centerHorizontal="true"
android:onClick="SignUp" />
<TextView
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/text2"
android:layout_below="@id/Email"
android:layout_alignParentRight="false"
android:layout_toRightOf="@id/NewPassword" />
<TextView
android:text="Poszukiwacz 2020"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/text3"
android:textColor="#ff000000"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>

View File

@ -10,6 +10,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Xamarin.Forms" Version="3.4.0.1008975" />
<PackageReference Include="Xamarin.Essentials" Version="1.5.3.2" />
<PackageReference Include="Xamarin.Forms" Version="4.8.0.1687" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,43 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Serwer.Infrastructure.DTO;
using Serwer.Infrastructure.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Serwer.Api.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
private readonly IUserService _userService;
public UserController(IUserService userService)
{
_userService = userService;
}
[HttpPost("Register")]
public async Task<IActionResult> Register(string email, string name, string surname, string login, string password)
{
await _userService.RegisterAsync(email, name, surname, login, password);
return Ok();
}
[HttpPost("SignIn")]
public async Task<IActionResult> SignIn(string login, string password)
{
var user = await _userService.SignInAsync(login, password);
return Ok(user);
}
[HttpGet("Test")]
public IActionResult Test()
{
return NoContent();
}
}
}

View File

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Serwer.Api
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}

View File

@ -4,23 +4,24 @@
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:50287",
"sslPort": 44305
"applicationUrl": "http://localhost:50760",
"sslPort": 44371
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "api/values",
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"Serwer": {
"Serwer.Api": {
"commandName": "Project",
"dotnetRunMessages": "true",
"launchBrowser": true,
"launchUrl": "api/values",
"launchUrl": "swagger",
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"

View File

@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.0" NoWarn="NU1605" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="5.0.0" NoWarn="NU1605" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Serwer.Core\Serwer.Core.csproj" />
<ProjectReference Include="..\Serwer.Infrastructure\Serwer.Infrastructure.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,92 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Serwer.Core.Repositories;
using Serwer.Infrastructure.Mappers;
using Serwer.Infrastructure.Repositories;
using Serwer.Infrastructure.Services;
using Serwer.Infrastructure.Settings;
namespace Serwer.Api
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Serwer.Api", Version = "v1" });
});
var jwtSettings = new JwtSettings()
{
Issuer = "PoszukiwaczInc",
ExpiryMinutes = 120,
Key = "Fjjji0Hdsa4$JgrwIO1j678dCelgFymdo"
};
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(c =>
{
c.TokenValidationParameters = new TokenValidationParameters
{
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.Key)),
ValidIssuer = jwtSettings.Issuer,
ValidateAudience = false,
ValidateLifetime = true
};
});
services.AddSingleton<IMapper>(AutoMapperConfig.Initialize());
services.AddSingleton<IJwtHandler, JwtHandler>(sp => new JwtHandler(jwtSettings));
services.AddScoped<IUserRepository, UserRepository>();
services.AddScoped<IUserService, UserService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Serwer.Api v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}

View File

@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}

View File

@ -0,0 +1,10 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}

View File

@ -0,0 +1,106 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serwer.Core.Domain
{
public class User
{
public Guid Id { get; protected set; }
public string Email { get; protected set; }
public string Name { get; protected set; }
public string Surname { get; protected set; }
public string Login { get; protected set; }
public string Password { get; protected set; }
public DateTime CreatedAt { get; protected set; }
public DateTime UpdatedAt { get; protected set; }
protected User() { }
public User(string email, string name, string surname, string login, string password)
{
Id = Guid.NewGuid();
SetEmail(email);
SetName(name);
SetSurname(surname);
SetLogin(login);
SetPassword(password);
}
public void SetEmail(string email)
{
if (string.IsNullOrWhiteSpace(email))
{
throw new Exception("Email cannot be empty");
}
if (Email == email)
{
return;
}
Email = email;
UpdatedAt = DateTime.UtcNow;
}
public void SetName(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
throw new Exception("Name cannot be empty");
}
if (Name == name)
{
return;
}
Name = name;
UpdatedAt = DateTime.UtcNow;
}
public void SetSurname(string surname)
{
if (string.IsNullOrWhiteSpace(surname))
{
throw new Exception("Surname cannot be empty");
}
if (Surname == surname)
{
return;
}
Surname = surname;
UpdatedAt = DateTime.UtcNow;
}
public void SetLogin(string login)
{
if (string.IsNullOrWhiteSpace(login))
{
throw new Exception("Login cannot be empty");
}
if (Login == login)
{
return;
}
Login = login;
UpdatedAt = DateTime.UtcNow;
}
public void SetPassword(string password)
{
if (string.IsNullOrWhiteSpace(password))
{
throw new Exception("Password cannot be empty");
}
if (Password == password)
{
return;
}
Password = password;
UpdatedAt = DateTime.UtcNow;
}
}
}

View File

@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serwer.Core.Repositories
{
public interface IRepository
{
}
}

View File

@ -0,0 +1,19 @@
using Serwer.Core.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serwer.Core.Repositories
{
public interface IUserRepository : IRepository
{
Task<User> GetAsync(Guid id);
Task<User> GetAsync(string login);
Task<IEnumerable<User>> GetAllAsync();
Task AddAsync(User user);
Task UpdateAsync(User user);
Task RemoveAsync(Guid id);
}
}

View File

@ -0,0 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serwer.Infrastructure.DTO
{
public class JwtDto
{
public Guid UserId { get; set; }
public string Token { get; set; }
public long Expires { get; set; }
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serwer.Infrastructure.DTO
{
public class SignedUserDto
{
public UserDto User { get; set; }
public JwtDto Jwt { get; set; }
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serwer.Infrastructure.DTO
{
public class UserDto
{
public string Email { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Login { get; set; }
public DateTime CreatedAt { get; protected set; }
public DateTime UpdatedAt { get; protected set; }
}
}

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serwer.Infrastructure.Extentions
{
public static class Extentions
{
public static long ToTimestamp(this DateTime dateTime)
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var time = dateTime.Ticks - epoch.Ticks;
return time / TimeSpan.TicksPerSecond;
}
}
}

View File

@ -0,0 +1,21 @@
using AutoMapper;
using Serwer.Core.Domain;
using Serwer.Infrastructure.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serwer.Infrastructure.Mappers
{
public static class AutoMapperConfig
{
public static IMapper Initialize()
=> new MapperConfiguration(cfg =>
{
cfg.CreateMap<User, UserDto>();
})
.CreateMapper();
}
}

View File

@ -0,0 +1,51 @@
using Serwer.Core.Domain;
using Serwer.Core.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serwer.Infrastructure.Repositories
{
public class UserRepository : IUserRepository
{
private static ISet<User> _users = new HashSet<User>();
public async Task AddAsync(User user)
{
await Task.FromResult(_users.Add(user));
}
public async Task<IEnumerable<User>> GetAllAsync()
{
return await Task.FromResult(_users);
}
public async Task<User> GetAsync(Guid id)
{
return await Task.FromResult(_users.SingleOrDefault(x => x.Id == id));
}
public async Task<User> GetAsync(string login)
{
return await Task.FromResult(_users.SingleOrDefault(x => x.Login == login));
}
public async Task RemoveAsync(Guid id)
{
var user = await GetAsync(id);
_users.Remove(user);
}
public async Task UpdateAsync(User user)
{
var dbuser = await GetAsync(user.Id);
dbuser.SetEmail(user.Email);
dbuser.SetLogin(user.Login);
dbuser.SetName(user.Name);
dbuser.SetSurname(user.Surname);
dbuser.SetPassword(user.Password);
}
}
}

View File

@ -0,0 +1,14 @@
using Serwer.Infrastructure.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serwer.Infrastructure.Services
{
public interface IJwtHandler
{
JwtDto CreateToken(Guid userId);
}
}

View File

@ -0,0 +1,15 @@
using Serwer.Infrastructure.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serwer.Infrastructure.Services
{
public interface IUserService
{
Task RegisterAsync(string email, string name, string surname, string login, string password);
Task<SignedUserDto> SignInAsync(string login, string password);
}
}

View File

@ -0,0 +1,55 @@
using Microsoft.IdentityModel.Tokens;
using Serwer.Infrastructure.DTO;
using Serwer.Infrastructure.Extentions;
using Serwer.Infrastructure.Settings;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
namespace Serwer.Infrastructure.Services
{
public class JwtHandler: IJwtHandler
{
private readonly JwtSettings _settings;
public JwtHandler(JwtSettings settings)
{
_settings = settings;
}
public JwtDto CreateToken(Guid userId)
{
var now = DateTime.UtcNow;
var claims = new Claim[]
{
new Claim(JwtRegisteredClaimNames.Sub, userId.ToString()),
new Claim(JwtRegisteredClaimNames.UniqueName, userId.ToString()),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Iat, now.ToTimestamp().ToString(), ClaimValueTypes.Integer64)
};
var expires = now.AddMinutes(_settings.ExpiryMinutes);
var signingCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_settings.Key)),
SecurityAlgorithms.HmacSha256);
var jwt = new JwtSecurityToken(
issuer: _settings.Issuer,
claims: claims,
notBefore: now,
expires: expires,
signingCredentials: signingCredentials
);
var token = new JwtSecurityTokenHandler().WriteToken(jwt);
return new JwtDto
{
UserId = userId,
Token = token,
Expires = expires.ToTimestamp()
};
}
}
}

View File

@ -0,0 +1,58 @@
using AutoMapper;
using Serwer.Core.Domain;
using Serwer.Core.Repositories;
using Serwer.Infrastructure.DTO;
using Serwer.Infrastructure.Mappers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serwer.Infrastructure.Services
{
public class UserService: IUserService
{
private readonly IUserRepository _userRepository;
private readonly IJwtHandler _jwtHandler;
private readonly IMapper _mapper;
public UserService(IUserRepository userRepository, IJwtHandler jwtHandler, IMapper mapper)
{
_userRepository = userRepository;
_jwtHandler = jwtHandler;
_mapper = mapper;
}
public async Task RegisterAsync(string email, string name, string surname, string login, string password)
{
if(await _userRepository.GetAsync(login) != null)
{
throw new Exception($"User with login: {login} already exists.");
}
var user = new User(email, name, surname, login, password);
await _userRepository.AddAsync(user);
}
public async Task<SignedUserDto> SignInAsync(string login, string password)
{
var user = await _userRepository.GetAsync(login);
if(user == null)
{
throw new Exception("User not found.");
}
if(user.Password != password)
{
throw new Exception("Incorrect password.");
}
var jwt = _jwtHandler.CreateToken(user.Id);
return new SignedUserDto()
{
User = _mapper.Map<UserDto>(user),
Jwt = _mapper.Map<JwtDto>(jwt)
};
}
}
}

View File

@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="10.1.1" />
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="6.8.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.8.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Serwer.Core\Serwer.Core.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serwer.Infrastructure.Settings
{
public class JwtSettings
{
public string Key { get; set; }
public string Issuer { get; set; }
public int ExpiryMinutes { get; set; }
}
}

View File

@ -1,11 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.28307.852
# Visual Studio Version 16
VisualStudioVersion = 16.0.30717.126
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Serwer", "Serwer\Serwer.csproj", "{CCE1E4CC-EC14-46A3-BCC9-2CBD8F2284D6}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Serwer.Tests", "Serwer.Tests\Serwer.Tests.csproj", "{4169F6FD-E08D-4329-BF87-A1411A9F1EF4}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Serwer.Tests", "Serwer.Tests\Serwer.Tests.csproj", "{4169F6FD-E08D-4329-BF87-A1411A9F1EF4}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Serwer.Core", "Serwer.Core\Serwer.Core.csproj", "{115E0BB1-FCC1-4E45-92B0-D3B6B4A3DA82}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Serwer.Infrastructure", "Serwer.Infrastructure\Serwer.Infrastructure.csproj", "{523E9EE6-B8D9-4E08-A9A0-50D7F872C79C}"
ProjectSection(ProjectDependencies) = postProject
{115E0BB1-FCC1-4E45-92B0-D3B6B4A3DA82} = {115E0BB1-FCC1-4E45-92B0-D3B6B4A3DA82}
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Serwer.Api", "Serwer.Api\Serwer.Api.csproj", "{335159FF-5AB8-48E5-A04C-778A46058204}"
ProjectSection(ProjectDependencies) = postProject
{115E0BB1-FCC1-4E45-92B0-D3B6B4A3DA82} = {115E0BB1-FCC1-4E45-92B0-D3B6B4A3DA82}
{523E9EE6-B8D9-4E08-A9A0-50D7F872C79C} = {523E9EE6-B8D9-4E08-A9A0-50D7F872C79C}
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -13,14 +24,22 @@ Global
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{CCE1E4CC-EC14-46A3-BCC9-2CBD8F2284D6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CCE1E4CC-EC14-46A3-BCC9-2CBD8F2284D6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CCE1E4CC-EC14-46A3-BCC9-2CBD8F2284D6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CCE1E4CC-EC14-46A3-BCC9-2CBD8F2284D6}.Release|Any CPU.Build.0 = Release|Any CPU
{4169F6FD-E08D-4329-BF87-A1411A9F1EF4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4169F6FD-E08D-4329-BF87-A1411A9F1EF4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4169F6FD-E08D-4329-BF87-A1411A9F1EF4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4169F6FD-E08D-4329-BF87-A1411A9F1EF4}.Release|Any CPU.Build.0 = Release|Any CPU
{115E0BB1-FCC1-4E45-92B0-D3B6B4A3DA82}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{115E0BB1-FCC1-4E45-92B0-D3B6B4A3DA82}.Debug|Any CPU.Build.0 = Debug|Any CPU
{115E0BB1-FCC1-4E45-92B0-D3B6B4A3DA82}.Release|Any CPU.ActiveCfg = Release|Any CPU
{115E0BB1-FCC1-4E45-92B0-D3B6B4A3DA82}.Release|Any CPU.Build.0 = Release|Any CPU
{523E9EE6-B8D9-4E08-A9A0-50D7F872C79C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{523E9EE6-B8D9-4E08-A9A0-50D7F872C79C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{523E9EE6-B8D9-4E08-A9A0-50D7F872C79C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{523E9EE6-B8D9-4E08-A9A0-50D7F872C79C}.Release|Any CPU.Build.0 = Release|Any CPU
{335159FF-5AB8-48E5-A04C-778A46058204}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{335159FF-5AB8-48E5-A04C-778A46058204}.Debug|Any CPU.Build.0 = Debug|Any CPU
{335159FF-5AB8-48E5-A04C-778A46058204}.Release|Any CPU.ActiveCfg = Release|Any CPU
{335159FF-5AB8-48E5-A04C-778A46058204}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@ -1,45 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace Serwer.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
[HttpGet("{id}")]
public ActionResult<string> Get(int id)
{
return "value";
}
// POST api/values
[HttpPost]
public void Post([FromBody] string value)
{
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}

View File

@ -1,24 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Serwer
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}

View File

@ -1,13 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
</ItemGroup>
</Project>

View File

@ -1,48 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Serwer
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// 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();
app.UseMvc();
}
}
}

View File

@ -1,9 +0,0 @@
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}

View File

@ -1,8 +0,0 @@
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}