Merge pull request #17 from PI20v/9-auth
Добавляет механизм авторизации и регистрации Fixes #9
This commit is contained in:
commit
f2928f71be
159
Authorization.cs
Normal file
159
Authorization.cs
Normal file
@ -0,0 +1,159 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace AwesomeEmailExtractor
|
||||
{
|
||||
public class Authorization
|
||||
{
|
||||
public static User Login(string login, string password)
|
||||
{
|
||||
SqliteCommand command = new SqliteCommand();
|
||||
command.Connection = Globals.db;
|
||||
command.CommandText = "SELECT * FROM users WHERE login = @login AND password = @password";
|
||||
|
||||
SqliteParameter loginParam = new SqliteParameter("@login", login);
|
||||
command.Parameters.Add(loginParam);
|
||||
|
||||
SqliteParameter passwordParam = new SqliteParameter("@password", EncryptPassword(password));
|
||||
command.Parameters.Add(passwordParam);
|
||||
|
||||
SqliteDataReader reader = command.ExecuteReader();
|
||||
|
||||
while (reader.Read())
|
||||
{
|
||||
return new User(reader.GetInt32(0), reader.GetString(1), (UserRoles)reader.GetInt32(1));
|
||||
}
|
||||
|
||||
throw new Exception("Пользователь не найден!");
|
||||
}
|
||||
|
||||
public static User Register(string login, string password)
|
||||
{
|
||||
SqliteCommand command = new SqliteCommand();
|
||||
command.Connection = Globals.db;
|
||||
command.CommandText = "INSERT INTO users (login, password, role_id) VALUES (@login, @password, 0);";
|
||||
|
||||
SqliteParameter loginParam = new SqliteParameter("@login", login);
|
||||
command.Parameters.Add(loginParam);
|
||||
|
||||
SqliteParameter passwordParam = new SqliteParameter("@password", EncryptPassword(password));
|
||||
command.Parameters.Add(passwordParam);
|
||||
|
||||
try
|
||||
{
|
||||
command.ExecuteNonQuery();
|
||||
} catch (SqliteException e)
|
||||
{
|
||||
if (e.SqliteErrorCode == 19) {
|
||||
throw new Exception("Имя пользователя занятно!");
|
||||
}
|
||||
|
||||
throw new Exception($"Ошибка: {e.Message}");
|
||||
};
|
||||
|
||||
return Login(login, password);
|
||||
}
|
||||
|
||||
public static string EncryptPassword(string password)
|
||||
{
|
||||
using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
|
||||
{
|
||||
UTF8Encoding utf8 = new UTF8Encoding();
|
||||
byte[] data = md5.ComputeHash(utf8.GetBytes(password));
|
||||
return Convert.ToBase64String(data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public enum UserRoles
|
||||
{
|
||||
DEFAULT,
|
||||
ADMIN
|
||||
}
|
||||
public class User
|
||||
{
|
||||
public int ID { get; }
|
||||
public string Login { get; }
|
||||
public UserRoles Role { get; }
|
||||
|
||||
public User(int id, string login, UserRoles role)
|
||||
{
|
||||
ID = id;
|
||||
Login = login;
|
||||
Role = role;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public class AdminUtils
|
||||
{
|
||||
public User User { get; set; }
|
||||
|
||||
public AdminUtils(User user)
|
||||
{
|
||||
User = user;
|
||||
}
|
||||
public void setRole(string login, UserRoles role)
|
||||
{
|
||||
if (User.Role != UserRoles.ADMIN)
|
||||
{
|
||||
throw new Exception("Недостаточно прав!");
|
||||
}
|
||||
|
||||
SqliteCommand command = new SqliteCommand();
|
||||
command.Connection = Globals.db;
|
||||
command.CommandText = "UPDATE users SET role_id = @role WHERE login = @login";
|
||||
|
||||
SqliteParameter roleParam = new SqliteParameter("@role", (int)role);
|
||||
command.Parameters.Add(roleParam);
|
||||
|
||||
SqliteParameter loginParam = new SqliteParameter("@login", login);
|
||||
command.Parameters.Add(loginParam);
|
||||
|
||||
command.ExecuteNonQuery();
|
||||
}
|
||||
|
||||
public void deleteUser(string login)
|
||||
{
|
||||
if (User.Role != UserRoles.ADMIN)
|
||||
{
|
||||
throw new Exception("Недостаточно прав!");
|
||||
}
|
||||
|
||||
SqliteCommand command = new SqliteCommand();
|
||||
command.Connection = Globals.db;
|
||||
command.CommandText = "DELETE FROM users WHERE login = @login";
|
||||
|
||||
SqliteParameter loginParam = new SqliteParameter("@login", login);
|
||||
command.Parameters.Add(loginParam);
|
||||
|
||||
command.ExecuteNonQuery();
|
||||
}
|
||||
public List<User> getAllUsers()
|
||||
{
|
||||
if (User.Role != UserRoles.ADMIN)
|
||||
{
|
||||
throw new Exception("Недостаточно прав!");
|
||||
}
|
||||
|
||||
SqliteCommand command = new SqliteCommand();
|
||||
command.Connection = Globals.db;
|
||||
command.CommandText = "SELECT * FROM users";
|
||||
|
||||
SqliteDataReader reader = command.ExecuteReader();
|
||||
|
||||
List<User> users = new List<User>();
|
||||
|
||||
while (reader.Read())
|
||||
{
|
||||
users.Add(new User(reader.GetInt32(0), reader.GetString(1), (UserRoles)reader.GetInt32(2)));
|
||||
}
|
||||
|
||||
return users;
|
||||
}
|
||||
}
|
||||
}
|
4
AuthorizationForm.Designer.cs
generated
4
AuthorizationForm.Designer.cs
generated
@ -45,6 +45,7 @@
|
||||
this.loginButton.TabIndex = 0;
|
||||
this.loginButton.Text = "Авторизоваться";
|
||||
this.loginButton.UseVisualStyleBackColor = true;
|
||||
this.loginButton.Click += new System.EventHandler(this.loginButton_Click);
|
||||
//
|
||||
// registerButton
|
||||
//
|
||||
@ -90,6 +91,7 @@
|
||||
this.entryPassword.Name = "entryPassword";
|
||||
this.entryPassword.Size = new System.Drawing.Size(195, 20);
|
||||
this.entryPassword.TabIndex = 4;
|
||||
this.entryPassword.UseSystemPasswordChar = true;
|
||||
//
|
||||
// AuthorizationForm
|
||||
//
|
||||
@ -102,6 +104,8 @@
|
||||
this.Controls.Add(this.entryLogin);
|
||||
this.Controls.Add(this.registerButton);
|
||||
this.Controls.Add(this.loginButton);
|
||||
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
|
||||
this.MaximizeBox = false;
|
||||
this.Name = "AuthorizationForm";
|
||||
this.Text = "Авторизоваться";
|
||||
this.ResumeLayout(false);
|
||||
|
@ -17,11 +17,26 @@ namespace AwesomeEmailExtractor
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
private void loginButton_Click(object sender, EventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
Globals.currentUser = Authorization.Login(entryLogin.Text, entryPassword.Text);
|
||||
Logs.Log(Globals.currentUser, Logs.Action.Login, new Dictionary<string, object>());
|
||||
|
||||
var mainForm = FormManager.Current.CreateForm<MainForm>();
|
||||
FormManager.Current.Navigate(this, mainForm);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private void registerButton_Click(object sender, EventArgs e)
|
||||
{
|
||||
this.Close();
|
||||
|
||||
new RegistrationForm().Show();
|
||||
var form = FormManager.Current.CreateForm<RegistrationForm>();
|
||||
FormManager.Current.Navigate(this, form);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -12,6 +12,8 @@
|
||||
<FileAlignment>512</FileAlignment>
|
||||
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
|
||||
<Deterministic>true</Deterministic>
|
||||
<NuGetPackageImportStamp>
|
||||
</NuGetPackageImportStamp>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
@ -33,8 +35,36 @@
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="Microsoft.Data.Sqlite, Version=5.0.3.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
|
||||
<HintPath>packages\Microsoft.Data.Sqlite.Core.5.0.3\lib\netstandard2.0\Microsoft.Data.Sqlite.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="SQLitePCLRaw.batteries_v2, Version=2.0.4.976, Culture=neutral, PublicKeyToken=8226ea5df37bcae9, processorArchitecture=MSIL">
|
||||
<HintPath>packages\SQLitePCLRaw.bundle_e_sqlite3.2.0.4\lib\net461\SQLitePCLRaw.batteries_v2.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="SQLitePCLRaw.core, Version=2.0.4.976, Culture=neutral, PublicKeyToken=1488e028ca7ab535, processorArchitecture=MSIL">
|
||||
<HintPath>packages\SQLitePCLRaw.core.2.0.4\lib\netstandard2.0\SQLitePCLRaw.core.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="SQLitePCLRaw.nativelibrary, Version=2.0.4.976, Culture=neutral, PublicKeyToken=502ed628492ab262, processorArchitecture=MSIL">
|
||||
<HintPath>packages\SQLitePCLRaw.bundle_e_sqlite3.2.0.4\lib\net461\SQLitePCLRaw.nativelibrary.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="SQLitePCLRaw.provider.dynamic_cdecl, Version=2.0.4.976, Culture=neutral, PublicKeyToken=b68184102cba0b3b, processorArchitecture=MSIL">
|
||||
<HintPath>packages\SQLitePCLRaw.provider.dynamic_cdecl.2.0.4\lib\netstandard2.0\SQLitePCLRaw.provider.dynamic_cdecl.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Buffers, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
|
||||
<HintPath>packages\System.Buffers.4.4.0\lib\netstandard2.0\System.Buffers.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.Core" />
|
||||
<Reference Include="System.Memory, Version=4.0.1.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
|
||||
<HintPath>packages\System.Memory.4.5.3\lib\netstandard2.0\System.Memory.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.Numerics" />
|
||||
<Reference Include="System.Numerics.Vectors, Version=4.1.3.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
|
||||
<HintPath>packages\System.Numerics.Vectors.4.4.0\lib\net46\System.Numerics.Vectors.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.Runtime.CompilerServices.Unsafe, Version=4.0.4.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
|
||||
<HintPath>packages\System.Runtime.CompilerServices.Unsafe.4.5.2\lib\netstandard2.0\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.Xml.Linq" />
|
||||
<Reference Include="System.Data.DataSetExtensions" />
|
||||
<Reference Include="Microsoft.CSharp" />
|
||||
@ -46,6 +76,7 @@
|
||||
<Reference Include="System.Xml" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="Authorization.cs" />
|
||||
<Compile Include="AuthorizationForm.cs">
|
||||
<SubType>Form</SubType>
|
||||
</Compile>
|
||||
@ -53,6 +84,9 @@
|
||||
<DependentUpon>AuthorizationForm.cs</DependentUpon>
|
||||
</Compile>
|
||||
<Compile Include="ExtactEmailsAlgorithm.cs" />
|
||||
<Compile Include="FormManager.cs" />
|
||||
<Compile Include="Globals.cs" />
|
||||
<Compile Include="Logs.cs" />
|
||||
<Compile Include="MainForm.cs">
|
||||
<SubType>Form</SubType>
|
||||
</Compile>
|
||||
@ -82,6 +116,7 @@
|
||||
<AutoGen>True</AutoGen>
|
||||
<DependentUpon>Resources.resx</DependentUpon>
|
||||
</Compile>
|
||||
<None Include="packages.config" />
|
||||
<EmbeddedResource Include="RegistrationForm.resx">
|
||||
<DependentUpon>RegistrationForm.cs</DependentUpon>
|
||||
</EmbeddedResource>
|
||||
@ -99,4 +134,11 @@
|
||||
<None Include="App.config" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<Import Project="packages\SQLitePCLRaw.lib.e_sqlite3.2.0.4\build\net461\SQLitePCLRaw.lib.e_sqlite3.targets" Condition="Exists('packages\SQLitePCLRaw.lib.e_sqlite3.2.0.4\build\net461\SQLitePCLRaw.lib.e_sqlite3.targets')" />
|
||||
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
|
||||
<PropertyGroup>
|
||||
<ErrorText>Данный проект ссылается на пакеты NuGet, отсутствующие на этом компьютере. Используйте восстановление пакетов NuGet, чтобы скачать их. Дополнительную информацию см. по адресу: http://go.microsoft.com/fwlink/?LinkID=322105. Отсутствует следующий файл: {0}.</ErrorText>
|
||||
</PropertyGroup>
|
||||
<Error Condition="!Exists('packages\SQLitePCLRaw.lib.e_sqlite3.2.0.4\build\net461\SQLitePCLRaw.lib.e_sqlite3.targets')" Text="$([System.String]::Format('$(ErrorText)', 'packages\SQLitePCLRaw.lib.e_sqlite3.2.0.4\build\net461\SQLitePCLRaw.lib.e_sqlite3.targets'))" />
|
||||
</Target>
|
||||
</Project>
|
46
FormManager.cs
Normal file
46
FormManager.cs
Normal file
@ -0,0 +1,46 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace AwesomeEmailExtractor
|
||||
{
|
||||
public class FormManager : ApplicationContext
|
||||
{
|
||||
private void onFormClosed(object sender, EventArgs e)
|
||||
{
|
||||
if (Application.OpenForms.Count == 0)
|
||||
{
|
||||
if (((Form)sender).Name == currentForm)
|
||||
ExitThread();
|
||||
}
|
||||
}
|
||||
|
||||
public T CreateForm<T>() where T : Form, new()
|
||||
{
|
||||
var ret = new T();
|
||||
ret.FormClosed += onFormClosed;
|
||||
return ret;
|
||||
}
|
||||
|
||||
public void Navigate(Form from, Form to)
|
||||
{
|
||||
currentForm = to.Name;
|
||||
from.Close();
|
||||
to.Show();
|
||||
}
|
||||
|
||||
public string currentForm = "AuthorizationForm";
|
||||
|
||||
private static Lazy<FormManager> _current = new Lazy<FormManager>();
|
||||
public static FormManager Current => _current.Value;
|
||||
|
||||
public FormManager()
|
||||
{
|
||||
var authorization = CreateForm<AuthorizationForm>();
|
||||
authorization.Show();
|
||||
}
|
||||
}
|
||||
}
|
124
Globals.cs
Normal file
124
Globals.cs
Normal file
@ -0,0 +1,124 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.IO;
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
|
||||
namespace AwesomeEmailExtractor
|
||||
{
|
||||
internal class Globals
|
||||
{
|
||||
// Getter and setter for SQLite database connection
|
||||
public static SqliteConnection db { get; set; }
|
||||
public static SqliteConnection logsDb { get; set; }
|
||||
|
||||
public static User currentUser { get; set; }
|
||||
|
||||
public static string getAppDirectory()
|
||||
{
|
||||
return Path.Combine(
|
||||
Environment.GetFolderPath(
|
||||
Environment.SpecialFolder.ApplicationData
|
||||
),
|
||||
"AwesomeEmailExtractor"
|
||||
);
|
||||
}
|
||||
|
||||
public static string getAppDatabase()
|
||||
{
|
||||
return Path.Combine(
|
||||
getAppDirectory(),
|
||||
"database.db"
|
||||
);
|
||||
}
|
||||
|
||||
public static string getDefaultPathAppLogs()
|
||||
{
|
||||
return Path.Combine(
|
||||
getAppDirectory(),
|
||||
"logs.db"
|
||||
);
|
||||
}
|
||||
|
||||
public static string getPathAppLogs()
|
||||
{
|
||||
SqliteCommand command = new SqliteCommand();
|
||||
command.Connection = db;
|
||||
command.CommandText = "SELECT logs_db_path FROM app_settings LIMIT 1";
|
||||
|
||||
SqliteDataReader reader = command.ExecuteReader();
|
||||
while (reader.Read())
|
||||
{
|
||||
return reader["logs_db_path"].ToString();
|
||||
}
|
||||
|
||||
return getDefaultPathAppLogs();
|
||||
}
|
||||
|
||||
public static void CreateLogsTable()
|
||||
{
|
||||
SqliteCommand command = new SqliteCommand();
|
||||
command.Connection = logsDb;
|
||||
|
||||
command.CommandText = "CREATE TABLE IF NOT EXISTS logs_actions (id INTEGER PRIMARY KEY, name TEXT NOT NULL)";
|
||||
command.ExecuteNonQuery();
|
||||
|
||||
command.CommandText = "INSERT OR IGNORE INTO logs_actions (id, name) VALUES (0, 'Выполнение'), (1, 'Вход'), (2, 'Регистрация');";
|
||||
command.ExecuteNonQuery();
|
||||
|
||||
command.CommandText = "CREATE TABLE IF NOT EXISTS logs (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL, date TEXT NOT NULL, action INTEGER NOT NULL, message TEXT NOT NULL, FOREIGN KEY(action) REFERENCES logs_actions(id));";
|
||||
command.ExecuteNonQuery();
|
||||
|
||||
}
|
||||
|
||||
public static void CreateTables()
|
||||
{
|
||||
SqliteCommand command = new SqliteCommand();
|
||||
command.Connection = db;
|
||||
|
||||
// Создать таблицу для хранения ролей
|
||||
command.CommandText = "CREATE TABLE IF NOT EXISTS roles (id INTEGER PRIMARY KEY, name TEXT NOT NULL);";
|
||||
command.ExecuteNonQuery();
|
||||
|
||||
// Добавить роли
|
||||
command.CommandText = "INSERT OR IGNORE INTO roles (id, name) VALUES (0, 'Обычный'), (1, 'Администратор');";
|
||||
command.ExecuteNonQuery();
|
||||
|
||||
// Создать таблицу для хранения настроек (знаю, так плохо, но сойдет)
|
||||
command.CommandText = "CREATE TABLE IF NOT EXISTS app_settings (logs_db_path TEXT);";
|
||||
command.ExecuteNonQuery();
|
||||
|
||||
// Создать таблицу для хранения пользователей
|
||||
command.CommandText = "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, login TEXT NOT NULL UNIQUE, password TEXT NOT NULL, role_id INTEGER NOT NULL, FOREIGN KEY(role_id) REFERENCES roles(id));";
|
||||
command.ExecuteNonQuery();
|
||||
|
||||
// Если таблица пуста - добавить пользователя по умолчанию
|
||||
command.CommandText = "SELECT COUNT(*) FROM users";
|
||||
|
||||
if (Convert.ToInt32(command.ExecuteScalar()) == 0)
|
||||
{
|
||||
command.CommandText = "INSERT INTO users (login, password, role_id) VALUES ('admin', @password, 1);";
|
||||
|
||||
SqliteParameter passwordParam = new SqliteParameter("@password", Authorization.EncryptPassword("admin"));
|
||||
command.Parameters.Add(passwordParam);
|
||||
command.ExecuteNonQuery();
|
||||
command.Parameters.Clear();
|
||||
}
|
||||
|
||||
command.CommandText = "SELECT COUNT(*) FROM app_settings";
|
||||
|
||||
if (Convert.ToInt32(command.ExecuteScalar()) == 0)
|
||||
{
|
||||
command.CommandText = "INSERT INTO app_settings (logs_db_path) VALUES (@logs_db_path);";
|
||||
|
||||
SqliteParameter logsDbPathParam = new SqliteParameter("@logs_db_path", getDefaultPathAppLogs());
|
||||
command.Parameters.Add(logsDbPathParam);
|
||||
command.ExecuteNonQuery();
|
||||
command.Parameters.Clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
125
Logs.cs
Normal file
125
Logs.cs
Normal file
@ -0,0 +1,125 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
namespace AwesomeEmailExtractor
|
||||
{
|
||||
public class Logs
|
||||
{
|
||||
public class LogData {
|
||||
public User user;
|
||||
public string date;
|
||||
public Action action;
|
||||
public string message;
|
||||
}
|
||||
|
||||
public enum Action
|
||||
{
|
||||
Execute,
|
||||
Login,
|
||||
Registration
|
||||
}
|
||||
|
||||
public static void Log(User user, Action action, Dictionary<string, object> options)
|
||||
{
|
||||
SqliteCommand command = new SqliteCommand();
|
||||
command.Connection = Globals.logsDb;
|
||||
|
||||
command.CommandText = "INSERT INTO logs (user_id, date, action, message) VALUES (@user_id, strftime('%Y-%m-%d %H:%M:%S', datetime('now')), @action, @message)";
|
||||
|
||||
command.Parameters.AddWithValue("@user_id", user.ID);
|
||||
command.Parameters.AddWithValue("@action", action);
|
||||
command.Parameters.AddWithValue("@message", GetLogMessage(action, options));
|
||||
|
||||
command.ExecuteNonQuery();
|
||||
}
|
||||
|
||||
public static List<LogData> GetLogs(User user)
|
||||
{
|
||||
SqliteCommand command = new SqliteCommand();
|
||||
command.Connection = Globals.logsDb;
|
||||
|
||||
command.CommandText = "SELECT date, action, message FROM logs WHERE user_id = @user_id ORDER BY date DESC";
|
||||
command.Parameters.AddWithValue("@user_id", user.ID);
|
||||
|
||||
SqliteDataReader reader = command.ExecuteReader();
|
||||
|
||||
List<LogData> logs = new List<LogData>();
|
||||
while (reader.Read())
|
||||
{
|
||||
logs.Add(new LogData()
|
||||
{
|
||||
user = user,
|
||||
date = reader.GetString(0),
|
||||
action = (Action)reader.GetInt32(1),
|
||||
message = reader.GetString(2)
|
||||
});
|
||||
}
|
||||
|
||||
return logs;
|
||||
}
|
||||
|
||||
public static List<LogData> GetLogs()
|
||||
{
|
||||
SqliteCommand command = new SqliteCommand();
|
||||
command.Connection = Globals.logsDb;
|
||||
command.CommandText = "ATTACH DATABASE @dbpath AS appDB";
|
||||
command.Parameters.AddWithValue("@dbpath", Globals.getAppDatabase());
|
||||
command.ExecuteNonQuery();
|
||||
|
||||
command.CommandText = @"
|
||||
SELECT
|
||||
user_id,
|
||||
CASE WHEN appDB.users.login is NULL THEN 'Deleted_' || user_id ELSE appDB.users.login END AS login
|
||||
appDB.users.role,
|
||||
date,
|
||||
action,
|
||||
message
|
||||
from logs LEFT JOIN appDB.users on logs.user_id = appDB.users.id ORDER BY date DESC";
|
||||
|
||||
SqliteDataReader reader = command.ExecuteReader();
|
||||
|
||||
List<LogData> logs = new List<LogData>();
|
||||
while (reader.Read())
|
||||
{
|
||||
logs.Add(new LogData()
|
||||
{
|
||||
user = new User(reader.GetInt32(0), reader.GetString(1), (UserRoles)reader.GetInt32(2)),
|
||||
date = reader.GetString(3),
|
||||
action = (Action)reader.GetInt32(4),
|
||||
message = reader.GetString(5)
|
||||
});
|
||||
}
|
||||
|
||||
return logs;
|
||||
}
|
||||
|
||||
public static string GetLogMessage(Action action, Dictionary<string, object> options)
|
||||
{
|
||||
if (action == Action.Execute)
|
||||
{
|
||||
string sourceText = (string)options["sourceText"];
|
||||
int count = (int)options["count"];
|
||||
List<string> uniqueEmails = options["uniqueEmails"] as List<string>;
|
||||
|
||||
|
||||
return $"Пользователь выполнил поиск email-ов c таким исходным текстом: [ {sourceText}. ]\n" +
|
||||
$"Найдено {count} email-ов.\n" +
|
||||
$"Список уникальных: {String.Join(", ", uniqueEmails)}.";
|
||||
}
|
||||
if (action == Action.Login)
|
||||
{
|
||||
return "Пользователь вошел в систему.";
|
||||
}
|
||||
if (action == Action.Registration)
|
||||
{
|
||||
return "Пользователь зарегистрировался в системе.";
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
21
MainForm.cs
21
MainForm.cs
@ -19,6 +19,15 @@ namespace AwesomeEmailExtractor
|
||||
|
||||
private void executeButton_Click(object sender, EventArgs e)
|
||||
{
|
||||
// Получаем исходный текст из sourceRichTextBox
|
||||
string sourceText = sourceRichTextBox.Text;
|
||||
|
||||
if (sourceText.Length == 0)
|
||||
{
|
||||
MessageBox.Show("Введите текст в поле исходного текста", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
return;
|
||||
}
|
||||
|
||||
// Чистим предыдущий результат
|
||||
toolStripStatusLabel.Text = "";
|
||||
resultCountLabel.Text = "";
|
||||
@ -27,9 +36,6 @@ namespace AwesomeEmailExtractor
|
||||
// Объявляем список уникальных e-mail-ов
|
||||
List<string> uniqueEmails = new List<string>();
|
||||
|
||||
// Получаем исходный текст из sourceRichTextBox
|
||||
string sourceText = sourceRichTextBox.Text;
|
||||
|
||||
// Вызываем метод для извлечения e-mail-ов
|
||||
int count = ExtactEmailsAlgorithm.Extract(sourceText, out uniqueEmails);
|
||||
|
||||
@ -37,6 +43,15 @@ namespace AwesomeEmailExtractor
|
||||
toolStripStatusLabel.Text = "Успех!";
|
||||
resultCountLabel.Text = $"Количество e-mail-ов в тексте: {count}";
|
||||
uniqueListBox.DataSource = uniqueEmails;
|
||||
|
||||
Logs.Log(
|
||||
Globals.currentUser,
|
||||
Logs.Action.Execute,
|
||||
new Dictionary<string, object>() {
|
||||
{ "sourceText", sourceText },
|
||||
{ "count", count },
|
||||
{ "uniqueEmails", uniqueEmails }
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
31
Program.cs
31
Program.cs
@ -3,6 +3,8 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using System.IO;
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
namespace AwesomeEmailExtractor
|
||||
{
|
||||
@ -14,9 +16,36 @@ namespace AwesomeEmailExtractor
|
||||
[STAThread]
|
||||
static void Main()
|
||||
{
|
||||
preMain();
|
||||
|
||||
Application.EnableVisualStyles();
|
||||
Application.SetCompatibleTextRenderingDefault(false);
|
||||
Application.Run(new MainForm());
|
||||
Application.Run(FormManager.Current);
|
||||
|
||||
postMain();
|
||||
}
|
||||
|
||||
static void preMain()
|
||||
{
|
||||
if (!Directory.Exists(Globals.getAppDirectory()))
|
||||
{
|
||||
Directory.CreateDirectory(Globals.getAppDirectory());
|
||||
}
|
||||
|
||||
Globals.db = new SqliteConnection("Data Source=" + Globals.getAppDatabase());
|
||||
Globals.db.Open();
|
||||
|
||||
Globals.CreateTables();
|
||||
|
||||
Globals.logsDb = new SqliteConnection("Data Source=" + Globals.getPathAppLogs());
|
||||
Globals.logsDb.Open();
|
||||
|
||||
Globals.CreateLogsTable();
|
||||
}
|
||||
|
||||
static void postMain()
|
||||
{
|
||||
Globals.db.Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
8
RegistrationForm.Designer.cs
generated
8
RegistrationForm.Designer.cs
generated
@ -55,6 +55,7 @@
|
||||
this.entryPassword.Name = "entryPassword";
|
||||
this.entryPassword.Size = new System.Drawing.Size(195, 20);
|
||||
this.entryPassword.TabIndex = 10;
|
||||
this.entryPassword.UseSystemPasswordChar = true;
|
||||
//
|
||||
// label1
|
||||
//
|
||||
@ -79,9 +80,10 @@
|
||||
this.registerButton.Location = new System.Drawing.Point(14, 135);
|
||||
this.registerButton.Name = "registerButton";
|
||||
this.registerButton.Size = new System.Drawing.Size(364, 23);
|
||||
this.registerButton.TabIndex = 7;
|
||||
this.registerButton.TabIndex = 6;
|
||||
this.registerButton.Text = "Зарегистрироваться";
|
||||
this.registerButton.UseVisualStyleBackColor = true;
|
||||
this.registerButton.Click += new System.EventHandler(this.registerButton_Click);
|
||||
//
|
||||
// loginButton
|
||||
//
|
||||
@ -89,7 +91,7 @@
|
||||
this.loginButton.Location = new System.Drawing.Point(14, 187);
|
||||
this.loginButton.Name = "loginButton";
|
||||
this.loginButton.Size = new System.Drawing.Size(364, 23);
|
||||
this.loginButton.TabIndex = 6;
|
||||
this.loginButton.TabIndex = 7;
|
||||
this.loginButton.Text = "Авторизоваться";
|
||||
this.loginButton.UseVisualStyleBackColor = true;
|
||||
this.loginButton.Click += new System.EventHandler(this.loginButton_Click);
|
||||
@ -121,7 +123,6 @@
|
||||
this.label4.Size = new System.Drawing.Size(178, 18);
|
||||
this.label4.TabIndex = 14;
|
||||
this.label4.Text = "Уже зарегистрированы?";
|
||||
this.label4.Click += new System.EventHandler(this.label4_Click);
|
||||
//
|
||||
// RegistrationForm
|
||||
//
|
||||
@ -140,6 +141,7 @@
|
||||
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
|
||||
this.Name = "RegistrationForm";
|
||||
this.Text = "Зарегистрироваться";
|
||||
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.RegistrationForm_FormClosed);
|
||||
this.ResumeLayout(false);
|
||||
this.PerformLayout();
|
||||
|
||||
|
@ -17,16 +17,37 @@ namespace AwesomeEmailExtractor
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
private void label4_Click(object sender, EventArgs e)
|
||||
private void registerButton_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (!string.Equals(entryPassword.Text, entryRePassword.Text))
|
||||
{
|
||||
MessageBox.Show("Пароли не совпадают!");
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
Globals.currentUser = Authorization.Register(entryLogin.Text, entryPassword.Text);
|
||||
Logs.Log(Globals.currentUser, Logs.Action.Registration, new Dictionary<string, object>());
|
||||
|
||||
var form = FormManager.Current.CreateForm<MainForm>();
|
||||
FormManager.Current.Navigate(this, form);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private void loginButton_Click(object sender, EventArgs e)
|
||||
{
|
||||
this.Close();
|
||||
AuthorizationForm form = FormManager.Current.CreateForm<AuthorizationForm>();
|
||||
FormManager.Current.Navigate(this, form);
|
||||
}
|
||||
|
||||
private void RegistrationForm_FormClosed(object sender, FormClosedEventArgs e)
|
||||
{
|
||||
|
||||
new AuthorizationForm().Show();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
13
packages.config
Normal file
13
packages.config
Normal file
@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<packages>
|
||||
<package id="Microsoft.Data.Sqlite" version="5.0.3" targetFramework="net472" />
|
||||
<package id="Microsoft.Data.Sqlite.Core" version="5.0.3" targetFramework="net472" />
|
||||
<package id="SQLitePCLRaw.bundle_e_sqlite3" version="2.0.4" targetFramework="net472" />
|
||||
<package id="SQLitePCLRaw.core" version="2.0.4" targetFramework="net472" />
|
||||
<package id="SQLitePCLRaw.lib.e_sqlite3" version="2.0.4" targetFramework="net472" />
|
||||
<package id="SQLitePCLRaw.provider.dynamic_cdecl" version="2.0.4" targetFramework="net472" />
|
||||
<package id="System.Buffers" version="4.4.0" targetFramework="net472" />
|
||||
<package id="System.Memory" version="4.5.3" targetFramework="net472" />
|
||||
<package id="System.Numerics.Vectors" version="4.4.0" targetFramework="net472" />
|
||||
<package id="System.Runtime.CompilerServices.Unsafe" version="4.5.2" targetFramework="net472" />
|
||||
</packages>
|
Reference in New Issue
Block a user