From fb13e5a20a751b3a251c2ac64d9b0c9be8ca1275 Mon Sep 17 00:00:00 2001 From: Debug_pro <63473508+Debug-pro-dev@users.noreply.github.com> Date: Sun, 7 Jun 2026 18:19:53 +0300 Subject: [PATCH] upload --- .gitattributes | 63 +++ .gitignore | 363 ++++++++++++++++++ App.xaml | 12 + App.xaml.cs | 13 + AssemblyInfo.cs | 10 + Data/AppDbContext.cs | 103 +++++ Data/AppDbContextFactory.cs | 14 + Data/DbInitializer.cs | 12 + .../20260422203506_InitialCreate.Designer.cs | 125 ++++++ Migrations/20260422203506_InitialCreate.cs | 89 +++++ Migrations/AppDbContextModelSnapshot.cs | 122 ++++++ Models/Article.cs | 15 + Models/User.cs | 19 + Services/EmailService.cs | 41 ++ Services/InputValidator.cs | 66 ++++ Services/MarkdownService.cs | 67 ++++ Services/PasswordHasher.cs | 77 ++++ Services/SessionService.cs | 8 + Services/SlugHelper.cs | 34 ++ Settings/SmtpSettings.cs | 13 + SimpleWiki.csproj | 30 ++ SimpleWiki.sln | 25 ++ Themes/CatppuccinMocha.xaml | 241 ++++++++++++ Views/ArticleEditorWindow.xaml | 66 ++++ Views/ArticleEditorWindow.xaml.cs | 147 +++++++ Views/ForgotPasswordWindow.xaml | 35 ++ Views/ForgotPasswordWindow.xaml.cs | 116 ++++++ Views/LoginWindow.xaml | 39 ++ Views/LoginWindow.xaml.cs | 53 +++ Views/MainWindow.xaml | 93 +++++ Views/MainWindow.xaml.cs | 173 +++++++++ Views/RegisterWindow.xaml | 37 ++ Views/RegisterWindow.xaml.cs | 61 +++ 33 files changed, 2382 insertions(+) create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 App.xaml create mode 100644 App.xaml.cs create mode 100644 AssemblyInfo.cs create mode 100644 Data/AppDbContext.cs create mode 100644 Data/AppDbContextFactory.cs create mode 100644 Data/DbInitializer.cs create mode 100644 Migrations/20260422203506_InitialCreate.Designer.cs create mode 100644 Migrations/20260422203506_InitialCreate.cs create mode 100644 Migrations/AppDbContextModelSnapshot.cs create mode 100644 Models/Article.cs create mode 100644 Models/User.cs create mode 100644 Services/EmailService.cs create mode 100644 Services/InputValidator.cs create mode 100644 Services/MarkdownService.cs create mode 100644 Services/PasswordHasher.cs create mode 100644 Services/SessionService.cs create mode 100644 Services/SlugHelper.cs create mode 100644 Settings/SmtpSettings.cs create mode 100644 SimpleWiki.csproj create mode 100644 SimpleWiki.sln create mode 100644 Themes/CatppuccinMocha.xaml create mode 100644 Views/ArticleEditorWindow.xaml create mode 100644 Views/ArticleEditorWindow.xaml.cs create mode 100644 Views/ForgotPasswordWindow.xaml create mode 100644 Views/ForgotPasswordWindow.xaml.cs create mode 100644 Views/LoginWindow.xaml create mode 100644 Views/LoginWindow.xaml.cs create mode 100644 Views/MainWindow.xaml create mode 100644 Views/MainWindow.xaml.cs create mode 100644 Views/RegisterWindow.xaml create mode 100644 Views/RegisterWindow.xaml.cs diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..1ff0c42 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,63 @@ +############################################################################### +# Set default behavior to automatically normalize line endings. +############################################################################### +* text=auto + +############################################################################### +# Set default behavior for command prompt diff. +# +# This is need for earlier builds of msysgit that does not have it on by +# default for csharp files. +# Note: This is only used by command line +############################################################################### +#*.cs diff=csharp + +############################################################################### +# Set the merge driver for project and solution files +# +# Merging from the command prompt will add diff markers to the files if there +# are conflicts (Merging from VS is not affected by the settings below, in VS +# the diff markers are never inserted). Diff markers may cause the following +# file extensions to fail to load in VS. An alternative would be to treat +# these files as binary and thus will always conflict and require user +# intervention with every merge. To do so, just uncomment the entries below +############################################################################### +#*.sln merge=binary +#*.csproj merge=binary +#*.vbproj merge=binary +#*.vcxproj merge=binary +#*.vcproj merge=binary +#*.dbproj merge=binary +#*.fsproj merge=binary +#*.lsproj merge=binary +#*.wixproj merge=binary +#*.modelproj merge=binary +#*.sqlproj merge=binary +#*.wwaproj merge=binary + +############################################################################### +# behavior for image files +# +# image files are treated as binary by default. +############################################################################### +#*.jpg binary +#*.png binary +#*.gif binary + +############################################################################### +# diff behavior for common document formats +# +# Convert binary document formats to text before diffing them. This feature +# is only available from the command line. Turn it on by uncommenting the +# entries below. +############################################################################### +#*.doc diff=astextplain +#*.DOC diff=astextplain +#*.docx diff=astextplain +#*.DOCX diff=astextplain +#*.dot diff=astextplain +#*.DOT diff=astextplain +#*.pdf diff=astextplain +#*.PDF diff=astextplain +#*.rtf diff=astextplain +#*.RTF diff=astextplain diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9491a2f --- /dev/null +++ b/.gitignore @@ -0,0 +1,363 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Oo]ut/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd \ No newline at end of file diff --git a/App.xaml b/App.xaml new file mode 100644 index 0000000..871877f --- /dev/null +++ b/App.xaml @@ -0,0 +1,12 @@ + + + + + + + + + diff --git a/App.xaml.cs b/App.xaml.cs new file mode 100644 index 0000000..4dbf1d2 --- /dev/null +++ b/App.xaml.cs @@ -0,0 +1,13 @@ +using System.Windows; +using SimpleWiki.Data; + +namespace SimpleWiki; + +public partial class App : Application +{ + protected override void OnStartup(StartupEventArgs e) + { + DbInitializer.Initialize(); + base.OnStartup(e); + } +} diff --git a/AssemblyInfo.cs b/AssemblyInfo.cs new file mode 100644 index 0000000..b0ec827 --- /dev/null +++ b/AssemblyInfo.cs @@ -0,0 +1,10 @@ +using System.Windows; + +[assembly: ThemeInfo( + ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located + //(used if a resource is not found in the page, + // or application resource dictionaries) + ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located + //(used if a resource is not found in the page, + // app, or any theme specific resource dictionaries) +)] diff --git a/Data/AppDbContext.cs b/Data/AppDbContext.cs new file mode 100644 index 0000000..1e133dd --- /dev/null +++ b/Data/AppDbContext.cs @@ -0,0 +1,103 @@ +using Microsoft.EntityFrameworkCore; +using SimpleWiki.Models; + +namespace SimpleWiki.Data; + +public class AppDbContext : DbContext +{ + public AppDbContext() + { + } + + public AppDbContext(DbContextOptions options) : base(options) + { + } + + public DbSet Users => Set(); + public DbSet
Articles => Set
(); + + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + if (!optionsBuilder.IsConfigured) + { + optionsBuilder.UseSqlite("Data Source=simplewiki.db"); + } + } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.Entity(entity => + { + entity.ToTable("users"); + + entity.HasKey(x => x.Id); + entity.Property(x => x.Id) + .ValueGeneratedOnAdd(); + + entity.Property(x => x.FullName) + .IsRequired() + .HasMaxLength(100); + + entity.Property(x => x.Email) + .IsRequired() + .HasMaxLength(256); + + entity.Property(x => x.PasswordHash) + .IsRequired() + .HasMaxLength(512); + + entity.Property(x => x.Role) + .IsRequired() + .HasMaxLength(16); + + entity.Property(x => x.CreatedAt) + .IsRequired(); + + entity.HasIndex(x => x.Email) + .IsUnique(); + + entity.HasMany(x => x.Articles) + .WithOne(x => x.Author) + .HasForeignKey(x => x.AuthorId) + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity
(entity => + { + entity.ToTable("articles"); + + entity.HasKey(x => x.Id); + entity.Property(x => x.Id) + .ValueGeneratedOnAdd(); + + entity.Property(x => x.Title) + .IsRequired() + .HasMaxLength(150); + + entity.Property(x => x.Slug) + .IsRequired() + .HasMaxLength(180); + + entity.Property(x => x.Summary) + .IsRequired() + .HasMaxLength(400); + + entity.Property(x => x.MarkdownContent) + .IsRequired() + .HasMaxLength(20000); + + entity.Property(x => x.CreatedAt) + .IsRequired(); + + entity.Property(x => x.UpdatedAt) + .IsRequired(false); + + entity.HasIndex(x => x.Slug) + .IsUnique(); + + entity.HasIndex(x => x.Title); + }); + + base.OnModelCreating(modelBuilder); + } +} diff --git a/Data/AppDbContextFactory.cs b/Data/AppDbContextFactory.cs new file mode 100644 index 0000000..eda19c1 --- /dev/null +++ b/Data/AppDbContextFactory.cs @@ -0,0 +1,14 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Design; + +namespace SimpleWiki.Data; + +public class AppDbContextFactory : IDesignTimeDbContextFactory +{ + public AppDbContext CreateDbContext(string[] args) + { + var optionsBuilder = new DbContextOptionsBuilder(); + optionsBuilder.UseSqlite("Data Source=simplewiki.db"); + return new AppDbContext(optionsBuilder.Options); + } +} diff --git a/Data/DbInitializer.cs b/Data/DbInitializer.cs new file mode 100644 index 0000000..0edfeb0 --- /dev/null +++ b/Data/DbInitializer.cs @@ -0,0 +1,12 @@ +using Microsoft.EntityFrameworkCore; + +namespace SimpleWiki.Data; + +public static class DbInitializer +{ + public static void Initialize() + { + using var db = new AppDbContext(); + db.Database.Migrate(); + } +} diff --git a/Migrations/20260422203506_InitialCreate.Designer.cs b/Migrations/20260422203506_InitialCreate.Designer.cs new file mode 100644 index 0000000..65d5048 --- /dev/null +++ b/Migrations/20260422203506_InitialCreate.Designer.cs @@ -0,0 +1,125 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using SimpleWiki.Data; + +#nullable disable + +namespace SimpleWiki.Migrations +{ + [DbContext(typeof(AppDbContext))] + [Migration("20260422203506_InitialCreate")] + partial class InitialCreate + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "8.0.26"); + + modelBuilder.Entity("SimpleWiki.Models.Article", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AuthorId") + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("MarkdownContent") + .IsRequired() + .HasMaxLength(20000) + .HasColumnType("TEXT"); + + b.Property("Slug") + .IsRequired() + .HasMaxLength(180) + .HasColumnType("TEXT"); + + b.Property("Summary") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("TEXT"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(150) + .HasColumnType("TEXT"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("AuthorId"); + + b.HasIndex("Slug") + .IsUnique(); + + b.HasIndex("Title"); + + b.ToTable("articles", (string)null); + }); + + modelBuilder.Entity("SimpleWiki.Models.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("FullName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("PasswordHash") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Email") + .IsUnique(); + + b.ToTable("users", (string)null); + }); + + modelBuilder.Entity("SimpleWiki.Models.Article", b => + { + b.HasOne("SimpleWiki.Models.User", "Author") + .WithMany("Articles") + .HasForeignKey("AuthorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Author"); + }); + + modelBuilder.Entity("SimpleWiki.Models.User", b => + { + b.Navigation("Articles"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Migrations/20260422203506_InitialCreate.cs b/Migrations/20260422203506_InitialCreate.cs new file mode 100644 index 0000000..ab7ddf2 --- /dev/null +++ b/Migrations/20260422203506_InitialCreate.cs @@ -0,0 +1,89 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SimpleWiki.Migrations +{ + /// + public partial class InitialCreate : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "users", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + FullName = table.Column(type: "TEXT", maxLength: 100, nullable: false), + Email = table.Column(type: "TEXT", maxLength: 256, nullable: false), + PasswordHash = table.Column(type: "TEXT", maxLength: 512, nullable: false), + Role = table.Column(type: "TEXT", maxLength: 16, nullable: false), + CreatedAt = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_users", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "articles", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Title = table.Column(type: "TEXT", maxLength: 150, nullable: false), + Slug = table.Column(type: "TEXT", maxLength: 180, nullable: false), + Summary = table.Column(type: "TEXT", maxLength: 400, nullable: false), + MarkdownContent = table.Column(type: "TEXT", maxLength: 20000, nullable: false), + CreatedAt = table.Column(type: "TEXT", nullable: false), + UpdatedAt = table.Column(type: "TEXT", nullable: true), + AuthorId = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_articles", x => x.Id); + table.ForeignKey( + name: "FK_articles_users_AuthorId", + column: x => x.AuthorId, + principalTable: "users", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + }); + + migrationBuilder.CreateIndex( + name: "IX_articles_AuthorId", + table: "articles", + column: "AuthorId"); + + migrationBuilder.CreateIndex( + name: "IX_articles_Slug", + table: "articles", + column: "Slug", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_articles_Title", + table: "articles", + column: "Title"); + + migrationBuilder.CreateIndex( + name: "IX_users_Email", + table: "users", + column: "Email", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "articles"); + + migrationBuilder.DropTable( + name: "users"); + } + } +} diff --git a/Migrations/AppDbContextModelSnapshot.cs b/Migrations/AppDbContextModelSnapshot.cs new file mode 100644 index 0000000..18a7882 --- /dev/null +++ b/Migrations/AppDbContextModelSnapshot.cs @@ -0,0 +1,122 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using SimpleWiki.Data; + +#nullable disable + +namespace SimpleWiki.Migrations +{ + [DbContext(typeof(AppDbContext))] + partial class AppDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "8.0.26"); + + modelBuilder.Entity("SimpleWiki.Models.Article", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AuthorId") + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("MarkdownContent") + .IsRequired() + .HasMaxLength(20000) + .HasColumnType("TEXT"); + + b.Property("Slug") + .IsRequired() + .HasMaxLength(180) + .HasColumnType("TEXT"); + + b.Property("Summary") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("TEXT"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(150) + .HasColumnType("TEXT"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("AuthorId"); + + b.HasIndex("Slug") + .IsUnique(); + + b.HasIndex("Title"); + + b.ToTable("articles", (string)null); + }); + + modelBuilder.Entity("SimpleWiki.Models.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("FullName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("PasswordHash") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Email") + .IsUnique(); + + b.ToTable("users", (string)null); + }); + + modelBuilder.Entity("SimpleWiki.Models.Article", b => + { + b.HasOne("SimpleWiki.Models.User", "Author") + .WithMany("Articles") + .HasForeignKey("AuthorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Author"); + }); + + modelBuilder.Entity("SimpleWiki.Models.User", b => + { + b.Navigation("Articles"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Models/Article.cs b/Models/Article.cs new file mode 100644 index 0000000..dd84bf7 --- /dev/null +++ b/Models/Article.cs @@ -0,0 +1,15 @@ +namespace SimpleWiki.Models; + +public class Article +{ + public int Id { get; set; } + public string Title { get; set; } = string.Empty; + public string Slug { get; set; } = string.Empty; + public string Summary { get; set; } = string.Empty; + public string MarkdownContent { get; set; } = string.Empty; + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; + public DateTime? UpdatedAt { get; set; } + + public int AuthorId { get; set; } + public User? Author { get; set; } +} diff --git a/Models/User.cs b/Models/User.cs new file mode 100644 index 0000000..679dfb2 --- /dev/null +++ b/Models/User.cs @@ -0,0 +1,19 @@ +namespace SimpleWiki.Models; + +public class User +{ + public int Id { get; set; } + public string FullName { get; set; } = string.Empty; + public string Email { get; set; } = string.Empty; + public string PasswordHash { get; set; } = string.Empty; + public string Role { get; set; } = Roles.User; + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; + + public ICollection
Articles { get; set; } = new List
(); +} + +public static class Roles +{ + public const string Admin = "Admin"; + public const string User = "User"; +} diff --git a/Services/EmailService.cs b/Services/EmailService.cs new file mode 100644 index 0000000..45a36b9 --- /dev/null +++ b/Services/EmailService.cs @@ -0,0 +1,41 @@ +using System.Net; +using System.Net.Mail; +using System.Text; +using System.Security.Cryptography; +using SimpleWiki.Settings; + +namespace SimpleWiki.Services; + +public static class EmailService +{ + public static string SendPasswordResetCode(string toEmail) + { + if (!SmtpSettings.IsConfigured) + { + throw new InvalidOperationException("SMTP не настроен. Заполни Settings/SmtpSettings.cs."); + } + + var code = RandomNumberGenerator.GetInt32(100000, 999999).ToString(); + + using var client = new SmtpClient(SmtpSettings.Host, SmtpSettings.Port) + { + EnableSsl = SmtpSettings.EnableSsl, + Credentials = new NetworkCredential(SmtpSettings.Email, SmtpSettings.Password) + }; + + using var message = new MailMessage + { + From = new MailAddress(SmtpSettings.Email, SmtpSettings.DisplayName), + Subject = "Код подтверждения для смены пароля", + Body = $"

Код подтверждения: {code}

Если это были не вы, просто проигнорируйте письмо.

", + IsBodyHtml = true, + BodyEncoding = Encoding.UTF8, + SubjectEncoding = Encoding.UTF8 + }; + + message.To.Add(toEmail); + client.Send(message); + + return code; + } +} diff --git a/Services/InputValidator.cs b/Services/InputValidator.cs new file mode 100644 index 0000000..c7dcdd2 --- /dev/null +++ b/Services/InputValidator.cs @@ -0,0 +1,66 @@ +using System.Text.RegularExpressions; + +namespace SimpleWiki.Services; + +public static class InputValidator +{ + private static readonly Regex EmailRegex = new(@"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$", RegexOptions.Compiled); + private static readonly Regex FullNameRegex = new(@"^[A-Za-zА-Яа-яЁё\-\s]{2,100}$", RegexOptions.Compiled); + private static readonly Regex PasswordRegex = new(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^A-Za-z\d]).{8,64}$", RegexOptions.Compiled); + private static readonly Regex CodeRegex = new(@"^\d{6}$", RegexOptions.Compiled); + + public static string? ValidateFullName(string? value) + { + if (string.IsNullOrWhiteSpace(value)) return "ФИО обязательно."; + if (!FullNameRegex.IsMatch(value.Trim())) return "ФИО: только буквы, пробелы и дефис, от 2 до 100 символов."; + return null; + } + + public static string? ValidateEmail(string? value) + { + if (string.IsNullOrWhiteSpace(value)) return "Email обязателен."; + if (value.Length > 256) return "Email слишком длинный."; + if (!EmailRegex.IsMatch(value.Trim())) return "Некорректный email."; + return null; + } + + public static string? ValidatePassword(string? value) + { + if (string.IsNullOrWhiteSpace(value)) return "Пароль обязателен."; + if (!PasswordRegex.IsMatch(value)) return "Пароль: 8-64 символа, минимум 1 строчная, 1 заглавная, 1 цифра и 1 спецсимвол."; + return null; + } + + public static string? ValidateResetCode(string? value) + { + if (string.IsNullOrWhiteSpace(value)) return "Код подтверждения обязателен."; + if (!CodeRegex.IsMatch(value.Trim())) return "Код должен состоять из 6 цифр."; + return null; + } + + public static string? ValidateArticleTitle(string? value) + { + if (string.IsNullOrWhiteSpace(value)) return "Заголовок обязателен."; + if (value.Trim().Length < 3 || value.Trim().Length > 150) return "Заголовок: от 3 до 150 символов."; + return null; + } + + public static string? ValidateArticleSummary(string? value) + { + if (string.IsNullOrWhiteSpace(value)) return "Краткое описание обязательно."; + if (value.Trim().Length < 10 || value.Trim().Length > 400) return "Краткое описание: от 10 до 400 символов."; + return null; + } + + public static string? ValidateArticleMarkdown(string? value) + { + if (string.IsNullOrWhiteSpace(value)) return "Текст статьи обязателен."; + if (value.Trim().Length < 20 || value.Trim().Length > 20000) return "Текст статьи: от 20 до 20000 символов."; + return null; + } + + public static string JoinErrors(params string?[] errors) + { + return string.Join(Environment.NewLine, errors.Where(x => !string.IsNullOrWhiteSpace(x))); + } +} diff --git a/Services/MarkdownService.cs b/Services/MarkdownService.cs new file mode 100644 index 0000000..bf8f8d2 --- /dev/null +++ b/Services/MarkdownService.cs @@ -0,0 +1,67 @@ +using Markdig; + +namespace SimpleWiki.Services; + +public static class MarkdownService +{ + private static readonly MarkdownPipeline Pipeline = new MarkdownPipelineBuilder() + .UseAdvancedExtensions() + .Build(); + + public static string ToHtmlDocument(string title, string markdown) + { + var htmlBody = Markdown.ToHtml(markdown ?? string.Empty, Pipeline); + + return $@" + + + + + + +{System.Net.WebUtility.HtmlEncode(title)} + + +
+{htmlBody} +
+ +"; + } +} diff --git a/Services/PasswordHasher.cs b/Services/PasswordHasher.cs new file mode 100644 index 0000000..c0b74ac --- /dev/null +++ b/Services/PasswordHasher.cs @@ -0,0 +1,77 @@ +using System.Security.Cryptography; +using System.Text; +using Konscious.Security.Cryptography; + +namespace SimpleWiki.Services; + +public static class PasswordHasher +{ + private const int Iterations = 3; + private const int MemorySizeKb = 65536; + private const int Parallelism = 1; + private const int SaltLength = 16; + private const int HashLength = 32; + + public static string HashPassword(string password) + { + if (string.IsNullOrWhiteSpace(password)) + { + throw new ArgumentException("Пароль пустой."); + } + + var salt = RandomNumberGenerator.GetBytes(SaltLength); + + using var argon2 = new Argon2id(Encoding.UTF8.GetBytes(password)) + { + Salt = salt, + Iterations = Iterations, + DegreeOfParallelism = Parallelism, + MemorySize = MemorySizeKb + }; + + var hash = argon2.GetBytes(HashLength); + var combined = new byte[SaltLength + HashLength]; + + Buffer.BlockCopy(salt, 0, combined, 0, SaltLength); + Buffer.BlockCopy(hash, 0, combined, SaltLength, HashLength); + + return Convert.ToBase64String(combined); + } + + public static bool VerifyPassword(string password, string hashPassword) + { + if (string.IsNullOrWhiteSpace(password) || string.IsNullOrWhiteSpace(hashPassword)) + { + return false; + } + + byte[] combined; + try + { + combined = Convert.FromBase64String(hashPassword); + } + catch + { + return false; + } + + if (combined.Length < SaltLength + HashLength) + { + return false; + } + + var salt = combined.Take(SaltLength).ToArray(); + var originalHash = combined.Skip(SaltLength).Take(HashLength).ToArray(); + + using var argon2 = new Argon2id(Encoding.UTF8.GetBytes(password)) + { + Salt = salt, + Iterations = Iterations, + DegreeOfParallelism = Parallelism, + MemorySize = MemorySizeKb + }; + + var newHash = argon2.GetBytes(HashLength); + return CryptographicOperations.FixedTimeEquals(originalHash, newHash); + } +} diff --git a/Services/SessionService.cs b/Services/SessionService.cs new file mode 100644 index 0000000..d6a42a3 --- /dev/null +++ b/Services/SessionService.cs @@ -0,0 +1,8 @@ +using SimpleWiki.Models; + +namespace SimpleWiki.Services; + +public static class SessionService +{ + public static User? CurrentUser { get; set; } +} diff --git a/Services/SlugHelper.cs b/Services/SlugHelper.cs new file mode 100644 index 0000000..ad1019d --- /dev/null +++ b/Services/SlugHelper.cs @@ -0,0 +1,34 @@ +using System.Text; +using System.Text.RegularExpressions; + +namespace SimpleWiki.Services; + +public static class SlugHelper +{ + public static string Generate(string title) + { + if (string.IsNullOrWhiteSpace(title)) + { + return string.Empty; + } + + var normalized = title.Trim().ToLowerInvariant(); + normalized = normalized.Replace('ё', 'е'); + + var sb = new StringBuilder(); + foreach (var ch in normalized) + { + if (char.IsLetterOrDigit(ch)) + { + sb.Append(ch); + } + else if (char.IsWhiteSpace(ch) || ch == '-' || ch == '_') + { + sb.Append('-'); + } + } + + var slug = Regex.Replace(sb.ToString(), "-+", "-").Trim('-'); + return string.IsNullOrWhiteSpace(slug) ? $"article-{DateTime.UtcNow:yyyyMMddHHmmss}" : slug; + } +} diff --git a/Settings/SmtpSettings.cs b/Settings/SmtpSettings.cs new file mode 100644 index 0000000..6a1b2fc --- /dev/null +++ b/Settings/SmtpSettings.cs @@ -0,0 +1,13 @@ +namespace SimpleWiki.Settings; + +public static class SmtpSettings +{ + public const string Host = "smtp.gmail.com"; + public const int Port = 587; + public const bool EnableSsl = true; + public const string Email = "debugprodevoff@gmail.com"; + public const string Password = "eihaxsdqbdkcnllf"; + public const string DisplayName = "Simple Wiki"; + + public static bool IsConfigured => true; +} diff --git a/SimpleWiki.csproj b/SimpleWiki.csproj new file mode 100644 index 0000000..462c324 --- /dev/null +++ b/SimpleWiki.csproj @@ -0,0 +1,30 @@ + + + WinExe + net8.0-windows + enable + enable + true + SimpleWiki + SimpleWiki + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + diff --git a/SimpleWiki.sln b/SimpleWiki.sln new file mode 100644 index 0000000..8c05c53 --- /dev/null +++ b/SimpleWiki.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.14.36429.23 d17.14 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimpleWiki", "SimpleWiki.csproj", "{E64D570E-DCB3-476B-A1FC-DF698F57B88E}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {E64D570E-DCB3-476B-A1FC-DF698F57B88E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E64D570E-DCB3-476B-A1FC-DF698F57B88E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E64D570E-DCB3-476B-A1FC-DF698F57B88E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E64D570E-DCB3-476B-A1FC-DF698F57B88E}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {882902AD-0410-4888-8F85-BFA5CC71128F} + EndGlobalSection +EndGlobal diff --git a/Themes/CatppuccinMocha.xaml b/Themes/CatppuccinMocha.xaml new file mode 100644 index 0000000..ebc3a01 --- /dev/null +++ b/Themes/CatppuccinMocha.xaml @@ -0,0 +1,241 @@ + + + #FF1E1E2E + #FF181825 + #FF11111B + #FF313244 + #FF45475A + #FF585B70 + #FFCDD6F4 + #FFA6ADC8 + #FF89B4FA + #FFB4BEFE + #FFA6E3A1 + #FFF9E2AF + #FFF38BA8 + #FFF5E0DC + #FFFAB387 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Views/ArticleEditorWindow.xaml b/Views/ArticleEditorWindow.xaml new file mode 100644 index 0000000..05e8812 --- /dev/null +++ b/Views/ArticleEditorWindow.xaml @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + +