change struct
This commit is contained in:
142
CyberBoom/Controllers/UserController.cs
Normal file
142
CyberBoom/Controllers/UserController.cs
Normal file
@ -0,0 +1,142 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using Mapster;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.Google;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace CyberBoom.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("[controller]")]
|
||||
public class UserController : ControllerBase
|
||||
{
|
||||
private static readonly string[] Summaries = new[]
|
||||
{
|
||||
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
|
||||
};
|
||||
|
||||
private readonly ILogger<UserController> _logger;
|
||||
|
||||
private readonly ApplicationContext _applicationContext;
|
||||
|
||||
public UserController(ILogger<UserController> logger, ApplicationContext applicationContext)
|
||||
{
|
||||
_logger = logger;
|
||||
_applicationContext = applicationContext;
|
||||
}
|
||||
|
||||
|
||||
// [HttpGet("google-auth")]
|
||||
// public IActionResult Regiester()
|
||||
// {
|
||||
// var properties = new AuthenticationProperties{
|
||||
// RedirectUri = Url.Action("GoogleResponse")
|
||||
// };
|
||||
// return Challenge(properties, GoogleDefaults.AuthenticationScheme);
|
||||
// }
|
||||
|
||||
// [Route("google-response")]
|
||||
// public async Task<IActionResult> GoogleResponse()
|
||||
// {
|
||||
// var result = await HttpContext.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme);
|
||||
|
||||
// var claims = result?.Principal?.Identities.First().Claims;
|
||||
// var jwt = new JwtSecurityToken(
|
||||
// issuer: AuthOptions.ISSUER,
|
||||
// audience: AuthOptions.AUDIENCE,
|
||||
// claims: claims,
|
||||
// expires: DateTime.UtcNow.Add(TimeSpan.FromMinutes(2)),
|
||||
// signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256));
|
||||
|
||||
// var strJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
|
||||
|
||||
// return Ok(new {
|
||||
// Token = strJwt
|
||||
// });
|
||||
// }
|
||||
|
||||
[HttpGet]
|
||||
public IEnumerable<WeatherForecast> Get()
|
||||
{
|
||||
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
|
||||
{
|
||||
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
|
||||
TemperatureC = Random.Shared.Next(-20, 55),
|
||||
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
|
||||
})
|
||||
.ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
[ApiController]
|
||||
[Route("[controller]")]
|
||||
public class MeetingController : ControllerBase
|
||||
{
|
||||
private static readonly string[] Summaries = new[]
|
||||
{
|
||||
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
|
||||
};
|
||||
|
||||
private readonly ILogger<UserController> _logger;
|
||||
|
||||
private readonly ApplicationContext _applicationContext;
|
||||
|
||||
public MeetingController(ILogger<UserController> logger, ApplicationContext applicationContext)
|
||||
{
|
||||
_logger = logger;
|
||||
_applicationContext = applicationContext;
|
||||
}
|
||||
|
||||
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> Post([FromForm]PostMeetingDto meeting)
|
||||
{
|
||||
await meeting.SpeackerImage.WriteFileToDirectory();
|
||||
var meetingWrite = meeting.Adapt<Meeting>();
|
||||
meetingWrite.SpeackerImage = meeting.SpeackerImage.JoinFileNames();
|
||||
await _applicationContext.Meetings.AddAsync(meetingWrite);
|
||||
|
||||
await _applicationContext.SaveChangesAsync();
|
||||
|
||||
|
||||
return Ok(new {
|
||||
meetingWrite.Id
|
||||
});
|
||||
}
|
||||
|
||||
[HttpPut]
|
||||
public async Task<IActionResult> Put([FromForm]PutMeetingDto meeting)
|
||||
{
|
||||
await meeting.SpeackerImage.WriteFileToDirectory();
|
||||
var meetingWrite = meeting.Adapt<Meeting>();
|
||||
meetingWrite.SpeackerImage = meeting.SpeackerImage.JoinFileNames();
|
||||
var findedMeeting = await _applicationContext.Meetings.FirstAsync(s => s.Id == meeting.Id);
|
||||
findedMeeting = meetingWrite;
|
||||
|
||||
await _applicationContext.SaveChangesAsync();
|
||||
return Ok();
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> Get(int id)
|
||||
{
|
||||
var meeting = await _applicationContext.Meetings.FirstOrDefaultAsync(s => s.Id == id);
|
||||
|
||||
|
||||
return Ok(meeting);
|
||||
}
|
||||
|
||||
|
||||
[HttpGet("/list")]
|
||||
public IActionResult GetList(int offset, int limit)
|
||||
{
|
||||
var meetings = _applicationContext.Meetings.Skip(offset).Take(limit);
|
||||
|
||||
|
||||
return Ok(meetings);
|
||||
}
|
||||
}
|
23
CyberBoom/CyberBoom.csproj
Normal file
23
CyberBoom/CyberBoom.csproj
Normal file
@ -0,0 +1,23 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net7.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<UserSecretsId>c28ad338-c527-4b98-b9a4-12b66b1a02dc</UserSecretsId>
|
||||
<UseAppHost>false</UseAppHost>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Mapster" Version="7.4.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.Google" Version="7.0.14" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.14" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="7.0.14" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="7.0.14" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.3" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.14" />
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.11" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
25
CyberBoom/CyberBoom.sln
Normal file
25
CyberBoom/CyberBoom.sln
Normal file
@ -0,0 +1,25 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.5.002.0
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CyberBoom", "CyberBoom.csproj", "{A8F9D7D8-DDA5-479B-8735-00E706A5827F}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{A8F9D7D8-DDA5-479B-8735-00E706A5827F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{A8F9D7D8-DDA5-479B-8735-00E706A5827F}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{A8F9D7D8-DDA5-479B-8735-00E706A5827F}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{A8F9D7D8-DDA5-479B-8735-00E706A5827F}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {674E1E42-AF3F-4DDA-A4F1-EDD84025DB24}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
107
CyberBoom/DbContext/User.cs
Normal file
107
CyberBoom/DbContext/User.cs
Normal file
@ -0,0 +1,107 @@
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
public class User : IdentityUser
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public class PostMeetingDto
|
||||
{
|
||||
public DateTime Time { get; set; }
|
||||
|
||||
public string Title { get; set; } = null!;
|
||||
|
||||
public string Theme { get; set; } = null!;
|
||||
|
||||
public string SpeakerName { get; set; } = null!;
|
||||
|
||||
public IEnumerable<IFormFile> SpeackerImage { get; set; } = null!;
|
||||
|
||||
public string Splecializations { get; set; } = null!;
|
||||
|
||||
public string Type { get; set; } = "онлайн/офлайн";
|
||||
|
||||
public string SpeakerTelephone { get; set; } = null!;
|
||||
|
||||
public string SpeakerEmail { get; set; } = null!;
|
||||
|
||||
public string Tags { get; set; } = null!;
|
||||
|
||||
public string VideoUrl { get; set; } = null!;
|
||||
}
|
||||
|
||||
|
||||
public class PutMeetingDto
|
||||
{
|
||||
public long Id { get; set; }
|
||||
|
||||
public DateTime Time { get; set; }
|
||||
|
||||
public string Title { get; set; } = null!;
|
||||
|
||||
public string Theme { get; set; } = null!;
|
||||
|
||||
public string SpeakerName { get; set; } = null!;
|
||||
|
||||
public IEnumerable<IFormFile> SpeackerImage { get; set; } = null!;
|
||||
|
||||
public string Splecializations { get; set; } = null!;
|
||||
|
||||
|
||||
public string Type { get; set; } = "онлайн/офлайн";
|
||||
|
||||
public string SpeakerTelephone { get; set; } = null!;
|
||||
|
||||
public string SpeakerEmail { get; set; } = null!;
|
||||
|
||||
public string Tags { get; set; } = null!;
|
||||
|
||||
public string VideoUrl { get; set; } = null!;
|
||||
}
|
||||
|
||||
public class Meeting
|
||||
{
|
||||
public long Id { get; set; }
|
||||
|
||||
public DateTime Time { get; set; }
|
||||
|
||||
public string Title { get; set; } = null!;
|
||||
|
||||
public string Theme { get; set; } = null!;
|
||||
|
||||
public string SpeakerName { get; set; } = null!;
|
||||
|
||||
public string SpeackerImage { get; set; } = null!;
|
||||
|
||||
public string Splecializations { get; set; } = null!;
|
||||
|
||||
|
||||
public string Type { get; set; } = "онлайн/офлайн";
|
||||
|
||||
public string SpeakerTelephone { get; set; } = null!;
|
||||
|
||||
public string SpeakerEmail { get; set; } = null!;
|
||||
|
||||
public string Tags { get; set; } = null!;
|
||||
|
||||
public string VideoUrl { get; set; } = null!;
|
||||
}
|
||||
|
||||
|
||||
public class ApplicationContext : IdentityDbContext<User>
|
||||
{
|
||||
public DbSet<Meeting> Meetings { get; set; }
|
||||
public ApplicationContext(DbContextOptions<ApplicationContext> options)
|
||||
: base(options)
|
||||
{
|
||||
Database.EnsureCreated();
|
||||
}
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder builder)
|
||||
{
|
||||
base.OnModelCreating(builder);
|
||||
builder.Entity<Meeting>();
|
||||
}
|
||||
}
|
128
CyberBoom/Program.cs
Normal file
128
CyberBoom/Program.cs
Normal file
@ -0,0 +1,128 @@
|
||||
using System.Text;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Mapster;
|
||||
using static Consts;
|
||||
|
||||
|
||||
TypeAdapterConfig<PutMeetingDto, Meeting>.NewConfig().Map(d => d.SpeackerImage, s => s.SpeackerImage.JoinFileNames());
|
||||
TypeAdapterConfig<PostMeetingDto, Meeting>.NewConfig().Map(d => d.SpeackerImage, s => s.SpeackerImage.JoinFileNames());
|
||||
|
||||
|
||||
TypeAdapterConfig<PostMeetingDto, Meeting>.NewConfig().Map(d => d.Splecializations, s => String.Join(FILES_SEPORATOR_IN_STORE, s.Splecializations));
|
||||
|
||||
TypeAdapterConfig<PutMeetingDto, Meeting>.NewConfig().Map(d => d.Splecializations, s => String.Join(FILES_SEPORATOR_IN_STORE, s.Splecializations));
|
||||
|
||||
|
||||
TypeAdapterConfig<PostMeetingDto, Meeting>.NewConfig().Map(d => d.Time, s => s.Time.ToUniversalTime());
|
||||
|
||||
TypeAdapterConfig<PutMeetingDto, Meeting>.NewConfig().Map(d => d.Time, s => s.Time.ToUniversalTime());
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
var configuration = builder.Configuration;
|
||||
|
||||
// Add services to the container.
|
||||
builder.Services.AddDbContext<ApplicationContext>(options =>
|
||||
options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));
|
||||
|
||||
builder.Services.AddIdentity<User, IdentityRole>()
|
||||
.AddEntityFrameworkStores<ApplicationContext>();
|
||||
|
||||
builder.Services.AddAuthorization();
|
||||
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
.AddJwtBearer(options =>
|
||||
{
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
// указывает, будет ли валидироваться издатель при валидации токена
|
||||
ValidateIssuer = true,
|
||||
// строка, представляющая издателя
|
||||
ValidIssuer = AuthOptions.ISSUER,
|
||||
// будет ли валидироваться потребитель токена
|
||||
ValidateAudience = true,
|
||||
// установка потребителя токена
|
||||
ValidAudience = AuthOptions.AUDIENCE,
|
||||
// будет ли валидироваться время существования
|
||||
ValidateLifetime = true,
|
||||
// установка ключа безопасности
|
||||
IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey(),
|
||||
// валидация ключа безопасности
|
||||
ValidateIssuerSigningKey = true,
|
||||
};
|
||||
})
|
||||
.AddGoogle(googleOptions =>
|
||||
{
|
||||
googleOptions.ClientId = configuration["Authentication:Google:ClientId"] ?? throw new NullReferenceException("");
|
||||
googleOptions.ClientSecret = configuration["Authentication:Google:ClientSecret"] ?? throw new NullReferenceException("");
|
||||
});
|
||||
|
||||
// builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
|
||||
// .AddEntityFrameworkStores<ApplicationContext>();
|
||||
// builder.Services.AddRazorPages();
|
||||
|
||||
|
||||
|
||||
builder.Services.AddControllers();
|
||||
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI();
|
||||
}
|
||||
|
||||
|
||||
|
||||
app.UseAuthentication(); // подключение аутентификации
|
||||
app.UseAuthorization();
|
||||
|
||||
|
||||
|
||||
app.MapControllers();
|
||||
//app.MapRazorPages();
|
||||
|
||||
app.Run();
|
||||
|
||||
public class AuthOptions
|
||||
{
|
||||
public const string ISSUER = "MyAuthServer"; // издатель токена
|
||||
public const string AUDIENCE = "MyAuthClient"; // потребитель токена
|
||||
const string KEY = "mysupersecret_secretkey!123"; // ключ для шифрации
|
||||
public static SymmetricSecurityKey GetSymmetricSecurityKey() =>
|
||||
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(KEY));
|
||||
}
|
||||
|
||||
public static class Consts
|
||||
{
|
||||
public const char FILES_SEPORATOR_IN_STORE = ';';
|
||||
}
|
||||
public static class PhileDataHelpers
|
||||
{
|
||||
public static string JoinFileNames(this IEnumerable<IFormFile> files) => files.Select(s => s.FileName).JoinStrings();
|
||||
|
||||
public static string JoinStrings(this IEnumerable<string> files) => String.Join(FILES_SEPORATOR_IN_STORE, files.Select(s => s));
|
||||
|
||||
|
||||
public static async Task WriteFileToDirectory(this IEnumerable<IFormFile> files)
|
||||
{
|
||||
var dir = Directory.CreateDirectory("cyber-boom-files");
|
||||
|
||||
foreach(var file in files)
|
||||
{
|
||||
var readStream = file.OpenReadStream();
|
||||
var memstream = new MemoryStream();
|
||||
await readStream.CopyToAsync(memstream);
|
||||
await File.WriteAllBytesAsync(Path.Combine(dir.FullName, file.FileName), memstream.ToArray());
|
||||
}
|
||||
|
||||
}
|
||||
}
|
31
CyberBoom/Properties/launchSettings.json
Normal file
31
CyberBoom/Properties/launchSettings.json
Normal file
@ -0,0 +1,31 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/launchsettings.json",
|
||||
"iisSettings": {
|
||||
"windowsAuthentication": false,
|
||||
"anonymousAuthentication": true,
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:32609",
|
||||
"sslPort": 44301
|
||||
}
|
||||
},
|
||||
"profiles": {
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"applicationUrl": "https://localhost:7223;http://localhost:5115",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"IIS Express": {
|
||||
"commandName": "IISExpress",
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
12
CyberBoom/WeatherForecast.cs
Normal file
12
CyberBoom/WeatherForecast.cs
Normal file
@ -0,0 +1,12 @@
|
||||
namespace CyberBoom;
|
||||
|
||||
public class WeatherForecast
|
||||
{
|
||||
public DateOnly Date { get; set; }
|
||||
|
||||
public int TemperatureC { get; set; }
|
||||
|
||||
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
|
||||
|
||||
public string? Summary { get; set; }
|
||||
}
|
8
CyberBoom/appsettings.Development.json
Normal file
8
CyberBoom/appsettings.Development.json
Normal file
@ -0,0 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
13
CyberBoom/appsettings.json
Normal file
13
CyberBoom/appsettings.json
Normal file
@ -0,0 +1,13 @@
|
||||
{
|
||||
"https_port": 7223,
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*",
|
||||
"ConnectionStrings": {
|
||||
"DefaultConnection": "Host=localhost; Database=CyberBoomWellBeing; Username=postgres; Password=supper_password_123"
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user