add environ error message

add to environ some data and some codereview pages
some fix oembed and OpenGraph
This commit is contained in:
Дмитрий Шиманский
2023-12-20 23:57:55 +03:00
parent 8a73f597cf
commit 921b8f3db3
14 changed files with 96 additions and 94 deletions

View File

@@ -1,5 +1,6 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.RateLimiting;
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Nodes; using System.Text.Json.Nodes;
using yaflay.ru.Models.Tables; using yaflay.ru.Models.Tables;
@@ -29,32 +30,7 @@ namespace yaflay.ru.Новая_папка
public string uri { get; set; } public string uri { get; set; }
public string author { get; set; } public string author { get; set; }
} }
/// <summary>
/// Getting redirect url from github file
/// </summary>
/// <param name="baseUrl"> uri-key of json in github file</param>
/// <returns type="string">url</returns>
private async Task<string?> getUrlFromGit(string baseUrl)
{
try
{
HttpClient client = new();
HttpResponseMessage getter = await client.GetAsync("https://raw.githubusercontent.com/yawaflua/yaflay.ru/master/redirect_uris.json");
JsonDocumentOptions jsonDocumentOptions = new ()
{
AllowTrailingCommas = true
};
JsonNode? allFile = JsonNode.Parse(await getter.Content.ReadAsStringAsync(),
documentOptions: jsonDocumentOptions);
;
return (string?)allFile[baseUrl];
}
catch (Exception except)
{
await Console.Out.WriteLineAsync(except.Message.ToString());
return null;
}
}
[HttpPost("api/redirects")] [HttpPost("api/redirects")]
public async Task<IActionResult> createRedirectUri([FromBody]redirectBody body) public async Task<IActionResult> createRedirectUri([FromBody]redirectBody body)
{ {
@@ -68,7 +44,7 @@ namespace yaflay.ru.Новая_папка
} }
string responseBody = await message.Content.ReadAsStringAsync(); string responseBody = await message.Content.ReadAsStringAsync();
JsonNode response = JsonNode.Parse(responseBody); JsonNode response = JsonNode.Parse(responseBody);
if (response["user"] != null || response["user"]?["id"].ToString() == "945317832290336798") if (response["user"] != null || response["user"]?["id"].ToString() == Startup.ownerId)
{ {
Redirects redirects = new() Redirects redirects = new()
{ {
@@ -97,7 +73,7 @@ namespace yaflay.ru.Новая_папка
} }
string responseBody = await message.Content.ReadAsStringAsync(); string responseBody = await message.Content.ReadAsStringAsync();
JsonNode response = JsonNode.Parse(responseBody); JsonNode response = JsonNode.Parse(responseBody);
if (response["user"] != null || response["user"]?["id"].ToString() == "945317832290336798") if (response["user"] != null || response["user"]?["id"].ToString() == Startup.ownerId)
{ {
Author author = new() Author author = new()
{ {
@@ -144,22 +120,22 @@ namespace yaflay.ru.Новая_папка
Comments comment = new() Comments comment = new()
{ {
creatorMail = body.sender, creatorMail = body.sender,
dateTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds(), dateTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
Text = body.text, Text = body.text,
postId = blogId postId = blogId
}; };
await Startup.dbContext.Comments.AddAsync(comment); await Startup.dbContext.Comments.AddAsync(comment);
await Startup.dbContext.SaveChangesAsync(); await Startup.dbContext.SaveChangesAsync();
return Ok(); return Ok();
} }
[HttpGet("api/Blog/{blogId}")] [HttpGet("api/Blog/{blogId}")]
public async Task<IActionResult> blog(int blogId) public async Task<IActionResult> blog(int blogId)
{ {
Blogs? blog = Startup.dbContext.Blogs.FirstOrDefault(k => k.Id == blogId) ?? null; Blogs? blog = Startup.dbContext.Blogs.FirstOrDefault(k => k.Id == blogId);
return Ok(blog); return Ok(blog);
} }
@@ -168,14 +144,9 @@ namespace yaflay.ru.Новая_папка
{ {
string? url = Startup.dbContext.Redirects.FirstOrDefault(k => k.uri == uri)?.redirectTo; string? url = Startup.dbContext.Redirects.FirstOrDefault(k => k.uri == uri)?.redirectTo;
if (url != null) return Redirect(url ?? "/404");
{
return Redirect(url);
}
else
{
return Redirect("/404");
}
} }

View File

@@ -21,9 +21,11 @@ ENV PSQL_HOST localhost
ENV PSQL_USER root ENV PSQL_USER root
ENV PSQL_PASSWORD root ENV PSQL_PASSWORD root
ENV PSQL_DATABASE database ENV PSQL_DATABASE database
ENV OWNERID 1111111
ENV READMEFILE https://raw.githubusercontent.com/yawaflua/yawaflua/main/README.md
RUN dotnet publish "yaflay.ru.csproj" -c Release -o /app/publish /p:UseAppHost=false RUN dotnet publish "yaflay.ru.csproj" -c Release -o /app/publish /p:UseAppHost=false
FROM base AS final FROM base AS final
WORKDIR /app WORKDIR /app
COPY --from=publish /app/publish . COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "yaflay.ru.dll", "/p:redirectUrl=$REDIRECTURL;clientId=$CLIENTID;clientSecret=$CLIENTSECRET;Host=$PSQL_HOST;Username=$PSQL_USER;Password=$PSQL_PASSWORD;Database=$PSQL_DATABASE"] ENTRYPOINT ["dotnet", "yaflay.ru.dll"]

View File

@@ -8,7 +8,7 @@
@if (Request.Cookies["melon"] != null) @if (Request.Cookies["melon"] != null)
{ {
if (Request.Cookies["cable"] != "945317832290336798") if (Request.Cookies["cable"] != Startup.ownerId)
{ {
<h1 align="center">Вы не авторизованы! Сасни хуйца, олух</h1> <h1 align="center">Вы не авторизованы! Сасни хуйца, олух</h1>
isAllowed = false; isAllowed = false;

View File

@@ -3,11 +3,13 @@
@using System.Text.Json.Nodes @using System.Text.Json.Nodes
@{ @{
ViewData["Title"] = "Authorize"; ViewData["Title"] = "Authorize";
string authorizationUrl = "https://discord.com/api/oauth2/authorize?client_id=@Startup.clientId&response_type=code&redirect_uri=@Startup.redirectUrl&scope=identify";
<p style="display:none;">Data: @Startup.clientId @Startup.redirectUrl @Startup.ownerId @Model.code</p>
if (Model.code == null) if (Model.code == null)
{ {
if (Request.Cookies["melon"]?.ToString() == null) if (Request.Cookies["melon"]?.ToString() == null)
{ {
<a href="https://discord.com/api/oauth2/authorize?client_id=1115013432710799440&response_type=code&redirect_uri=https%3A%2F%2Fyawaflua.ru%2Fauthorize&scope=identify">Login while Discord</a> <a href="@authorizationUrl">Login while Discord</a>
} }
else else
{ {
@@ -28,7 +30,7 @@
else else
{ {
<h4> <h4>
Токен авторизации неправильный! Попробуйте <a href="https://discord.com/api/oauth2/authorize?client_id=1115013432710799440&response_type=code&redirect_uri=https%3A%2F%2Fyawaflua.ru%2Fauthorize&scope=identify">заново</a> Токен авторизации неправильный! Попробуйте <a href="@authorizationUrl">заново</a>
</h4> </h4>
} }
@@ -52,6 +54,13 @@
if (body["access_token"]?.ToString() == null) if (body["access_token"]?.ToString() == null)
{ {
<h4>Ошибка! Попробуй авторизоваться заново</h4> <h4>Ошибка! Попробуй авторизоваться заново</h4>
Console.Error.WriteLine("Don't worry, this message is not bad as you think \n START \\/");
Console.Error.WriteLine("Error: DiscordAuthorize is not worked");
Console.Error.WriteLine($"Body from discord: {body}");
Console.Error.WriteLine($"Check environment data: \n ClientId={Startup.clientId}\nClientSecret={Startup.clientSecret}\nRedirectUrl={Startup.redirectUrl}\nOwnerId=wwwwwwwwwwwwwwwwwwwwwww{Startup.ownerId} ");
Console.Error.WriteLine("If any data is null and you set data in environment or appsettings.json, please create issue with this debug messages ");
Console.Error.WriteLine("END /\\");
} }
else else
{ {

View File

@@ -33,7 +33,7 @@
<div id="blogId" style="display:none;">@Model.Id</div> <div id="blogId" style="display:none;">@Model.Id</div>
<p align="center"><img src="@Post.ImageUrl" style="width:50vmax;"/></p> <p align="center"><img src="@Post.ImageUrl" style="width:50vmax;"/></p>
<p align="center">@Html.Raw(Post.Text)</p> <p align="center">@Html.Raw(Post.Text)</p>
<h6 align="left">Статья подготовлена <a href="https://yawaflua.ru/gh">Дмитрием</a></h6> <h6 align="left">Статья подготовлена <a href="https://discord.com/users/@Post.author.Id">@Post.author.discordNickName</a></h6>
<div class="container my-5 py-5 bg-dark text-muted"> <div class="container my-5 py-5 bg-dark text-muted">
<div class="row d-flex justify-content-center"> <div class="row d-flex justify-content-center">
<div class="col-md-12 col-lg-10"> <div class="col-md-12 col-lg-10">
@@ -73,23 +73,23 @@
var allBlogs = Startup.dbContext.Blogs.ToArray(); var allBlogs = Startup.dbContext.Blogs.ToArray();
if (allBlogs.Length == 0) if (allBlogs.Length == 0)
{ {
<p> <p>
<h1 align="center">Ничего нет...</h1> <h1 align="center">Ничего нет...</h1>
<h1 align="center">Вот вам банан -> 🍌</h1> <h1 align="center">Вот вам банан -> 🍌</h1>
</p> </p>
} }
else else
{ {
foreach (var blog in allBlogs) foreach (Blogs blog in allBlogs)
{ {
<div class="card text-white bg-dark mb-3 text-center" style="width: 18rem;"> <div class="card text-white bg-dark mb-3 text-center" style="width: 18rem;">
<img src="@blog.ImageUrl" class="card-img-top" alt="..."> <img src="@blog.ImageUrl" class="card-img-top" />
<div class="card-body "> <div class="card-body ">
<h5 class="card-title">@Html.Raw(blog.Title)</h5> <h5 class="card-title">@Html.Raw(blog.Title)</h5>
<p class="card-text">@Html.Raw(blog.Annotation)</p> <p class="card-text">@Html.Raw(blog.Annotation)</p>
<a href="/Blog/@blog.Id" class="btn btn-primary center">Читать</a> <a href="/Blog/@blog.Id" class="btn btn-primary center">Читать</a>
</div> </div>
</div> </div>
} }
} }
} }

View File

@@ -7,7 +7,7 @@
<h3 align="left" class="readme" >README.md</h3> <h3 align="left" class="readme" >README.md</h3>
@{ @{
string Github_readme = Startup.client.GetStringAsync("https://raw.githubusercontent.com/yawaflua/yawaflua/main/README.md").Result; string Github_readme = Startup.client.GetStringAsync(Startup.readmeFile).Result;
<div class="text"> @Html.Raw(Github_readme) </div> <div class="text"> @Html.Raw(Github_readme) </div>
} }

View File

@@ -9,7 +9,7 @@
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Page not found</title> <title>Page not found</title>
<link rel="stylesheet" href="https://yaflay.ru/css/500.css" /> <link rel="stylesheet" href="~/css/500.css" />
</head> </head>
<body> <body>
<div class="main-error-page"> <div class="main-error-page">

View File

@@ -23,7 +23,7 @@
<div class="col-lg-7 text-center"> <div class="col-lg-7 text-center">
<img src="~/img/error-404.png" alt="image 404"> <img src="~/img/error-404.png" alt="image 404">
<h2><b>404</b> Страница не найдена</h2> <h2><b>404</b> Страница не найдена</h2>
<p>посетите главную страницу <br> возможно вы найдёте её</p> <p>посетите главную страницу <br> возможно вы найдёте свой путь</p>
<a href="@path" class="cmn-btn mt-4">На главную</a> <a href="@path" class="cmn-btn mt-4">На главную</a>
</div> </div>
</div> </div>

View File

@@ -3,10 +3,10 @@
Layout = null; Layout = null;
this.Response.ContentType = "text/plain"; this.Response.ContentType = "text/plain";
} }
# /Robots.txt file for httpы://yawaflua.ru/
User-agent: * User-agent: *
<environment include="Development,Staging">Disallow: /*</environment> <environment include="Development,Staging">Disallow: /*</environment>
<environment include="Production">Disallow: /* </environment> <environment include="Production">Disallow: /* </environment>
<environment include="Production">Allow: /Blog </environment> <environment include="Production">Allow: /Blog </environment>
<environment include="Production">Allow: /Blog/* </environment>
<environment include="Production">Allow: /Privacy </environment> <environment include="Production">Allow: /Privacy </environment>
<environment include="Production">Allow: / </environment> <environment include="Production">Allow: / </environment>

View File

@@ -8,7 +8,7 @@
<title>@ViewData["Title"] - @Context.Request.Host.Host</title> <title>@ViewData["Title"] - @Context.Request.Host.Host</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" /> <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" /> <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<link type="application/json+oembed" href="~/json/oembed.json" />
<!--<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">--> <!--<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css">
@@ -16,7 +16,7 @@
<!-- and it's easy to individually load additional languages --> <!-- and it's easy to individually load additional languages -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/go.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/go.min.js"></script>
@if (Context.Request.Path == "") @if (!Context.Request.Path.ToString().StartsWith("/Blog/"))
{ {
<meta property="og:title" content="yawaflua readme" /> <meta property="og:title" content="yawaflua readme" />
<meta property="og:type" content="rich" /> <meta property="og:type" content="rich" />
@@ -26,8 +26,9 @@
content="Here you can check info about yawaflua: social networks, programming languages that he knows and his projects." /> content="Here you can check info about yawaflua: social networks, programming languages that he knows and his projects." />
<meta property="og:locale" content="en_US" /> <meta property="og:locale" content="en_US" />
<meta property="og:site_name" content="yawaflua.ru" /> <meta property="og:site_name" content="yawaflua.ru" />
<link type="application/json+oembed" href="~/json/oembed.json" />
} }
else else if (Context.Request.Path.ToString().StartsWith("/Blog/"))
{ {
<meta property="og:title" content="@ViewData["og:title"]" /> <meta property="og:title" content="@ViewData["og:title"]" />
<meta property="og:type" content="rich" /> <meta property="og:type" content="rich" />
@@ -123,10 +124,11 @@
<footer class="border-top footer text-muted margin-2-vm"> <footer class="border-top footer text-muted margin-2-vm">
<div class="container margin-2-vm"> <div class="container margin-2-vm">
&copy; 2023 - @Context.Request.Host.Host - <a asp-area="" asp-page="/Privacy">Privacy</a> &copy; 2023 - @Context.Request.Host.Host - <a asp-area="" asp-page="/Privacy">Privacy</a>
<b class="flex-row margin-2-vm container-md">
сrafted by <a href="https://yawaflua.ru/gh" class="underline dashed decoration-purple text-white hover:decoration-wavy">yawaflua</a>
</b>
</div> </div>
<p class="flex-row margin-2-vm container-md">
сrafted by <a href="https://yawaflua.ru/gh" class="underline dashed decoration-purple text-white hover:decoration-wavy">yawaflua</a>
</p>
</footer> </footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script> <script src="~/lib/jquery/dist/jquery.min.js"></script>

View File

@@ -4,14 +4,17 @@ public class Program
{ {
public static void Main() public static void Main()
{ {
var parse = (string name) => Environment.GetEnvironmentVariable(name) ?? null; Func<string, string?> parse = (string name) => Environment.GetEnvironmentVariable(name) ?? null;
Startup.clientId = parse("CLIENTID"); Startup.clientId = parse("CLIENTID");
Startup.clientSecret = parse("CLIENTSECRET"); Startup.clientSecret = parse("CLIENTSECRET");
Startup.redirectUrl = parse("REDIRECTURL"); Startup.redirectUrl = parse("REDIRECTURL");
Startup.connectionString = $"Host={parse("PSQL_HOST")};Username={parse("PSQL_USER")};Password={parse("PSQL_PASSWORD")};Database={parse("PSQL_DATABASE")}"; Startup.connectionString = $"Host={parse("PSQL_HOST")};Username={parse("PSQL_USER")};Password={parse("PSQL_PASSWORD")};Database={parse("PSQL_DATABASE")}";
Startup.ownerId = parse("OWNERID");
Startup.readmeFile = parse("READMEFILE");
CreateHostBuilder() CreateHostBuilder()
.Build() .Build()
.Run(); .Run();
} }
private static IHostBuilder CreateHostBuilder() private static IHostBuilder CreateHostBuilder()
{ {

View File

@@ -20,6 +20,8 @@ namespace yaflay.ru
public static string? clientId = null; public static string? clientId = null;
public static string? clientSecret = null; public static string? clientSecret = null;
public static string? redirectUrl = null; public static string? redirectUrl = null;
public static string? ownerId = null;
public static string? readmeFile = null;
public static string? connectionString { private get; set; } = null; public static string? connectionString { private get; set; } = null;
public Startup() public Startup()
{ {
@@ -37,6 +39,14 @@ namespace yaflay.ru
{ {
connectionString = configuration.GetValue<string>("connectionString"); connectionString = configuration.GetValue<string>("connectionString");
} }
if (ownerId == null)
{
ownerId = configuration.GetValue<string>("ownerId");
}
if (readmeFile == null)
{
readmeFile = configuration.GetValue<string>("readmeFile");
}
} }
public void ConfigureServices(IServiceCollection services) public void ConfigureServices(IServiceCollection services)
@@ -54,8 +64,7 @@ namespace yaflay.ru
services services
.AddRouting() .AddRouting()
.AddSingleton(configuration) .AddSingleton(configuration)
.AddDbContext<AppDbContext>(c => c.UseNpgsql(connectionString: connectionString)) .AddDbContext<AppDbContext>(c => c.UseNpgsql(connectionString: connectionString));
.AddCoreAdmin("Admin");
services.AddRazorPages(); services.AddRazorPages();
services.AddCors(k => { k.AddDefaultPolicy(l => { l.AllowAnyHeader(); l.AllowAnyMethod(); l.AllowAnyOrigin(); }); }) services.AddCors(k => { k.AddDefaultPolicy(l => { l.AllowAnyHeader(); l.AllowAnyMethod(); l.AllowAnyOrigin(); }); })
.AddMvc() .AddMvc()
@@ -68,7 +77,9 @@ namespace yaflay.ru
}); });
dbContext = services.BuildServiceProvider().GetRequiredService<AppDbContext>(); dbContext = services.BuildServiceProvider().GetRequiredService<AppDbContext>();
#if DEBUG == true
services.AddCoreAdmin("admin");
#endif
} }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
@@ -86,9 +97,11 @@ namespace yaflay.ru
app.UseRouting(); app.UseRouting();
app.UseAuthentication(); app.UseAuthentication();
app.UseAuthorization(); app.UseAuthorization();
#if DEBUG
app.UseCoreAdminCustomTitle("yawaflua"); app.UseCoreAdminCustomTitle("yawaflua");
app.UseCoreAdminCustomAuth((k) => Task.FromResult(true)); app.UseCoreAdminCustomAuth((k) => Task.FromResult(true));
app.UseCoreAdminCustomUrl("admin/coreadmin"); app.UseCoreAdminCustomUrl("admin/coreadmin");
#endif
app.UseCors(k => { k.AllowAnyMethod(); k.AllowAnyOrigin(); k.AllowAnyHeader(); }); app.UseCors(k => { k.AllowAnyMethod(); k.AllowAnyOrigin(); k.AllowAnyHeader(); });
app.UseEndpoints(endpoints => app.UseEndpoints(endpoints =>
{ {

View File

@@ -1,18 +1,19 @@
let blogId = $("#blogId").text(); let blogId = $("#blogId").text();
function loadComments () { function loadComments() {
fetch(`/api/Blog/${blogId}/comments`) if (document.location.pathname.startsWith("/Blog")) {
.then(response => { fetch(`/api/Blog/${blogId}/comments`)
let data = response.json(); .then(response => {
data.then(k => { let data = response.json();
for (let i = 0; i < k.length; i++) { data.then(k => {
let date = new Date(k[i].dateTime * 1000); for (let i = 0; i < k.length; i++) {
$("#commentBar").after( let date = new Date(k[i].dateTime * 1000);
`<div class="d-flex flex flex-start bg-dark bot-1"> $("#commentBar").after(
`<div class="d-flex flex flex-start bg-dark bot-1">
<div class="container"> <div class="container">
<h6 class="fw-bold mb-1">${k[i].creatorMail}</h6> <h6 class="fw-bold mb-1">${k[i].creatorMail}</h6>
<div class="d-flex align-items-center mb-3"> <div class="d-flex align-items-center mb-3">
<p class="mb-0"> <p class="mb-0">
${date.toLocaleString() } ${date.toLocaleString()}
</p> </p>
</div> </div>
<p class="mb-0"> <p class="mb-0">
@@ -20,10 +21,11 @@ function loadComments () {
</p> </p>
</div> </div>
</div>` </div>`
) )
} }
});
}); });
}); }
} }
$("#postComment").click( $("#postComment").click(
function () { function () {

View File

@@ -2,7 +2,7 @@
"embeds": [ "embeds": [
{ {
"type": "rich", "type": "rich",
"url": "yawaflua.ru", "url": "https://yawaflua.ru/",
"title": "ReadAbout yawaflua", "title": "ReadAbout yawaflua",
"description": "Here you can get info about yawaflua: social networks, programming languages that he knows and his projects.", "description": "Here you can get info about yawaflua: social networks, programming languages that he knows and his projects.",
"thumbnail": { "thumbnail": {