diff --git a/Authorization.cs b/Authorization.cs new file mode 100644 index 0000000..561041b --- /dev/null +++ b/Authorization.cs @@ -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 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 users = new List(); + + while (reader.Read()) + { + users.Add(new User(reader.GetInt32(0), reader.GetString(1), (UserRoles)reader.GetInt32(2))); + } + + return users; + } + } +} diff --git a/AuthorizationForm.Designer.cs b/AuthorizationForm.Designer.cs index aef46bc..8902b21 100644 --- a/AuthorizationForm.Designer.cs +++ b/AuthorizationForm.Designer.cs @@ -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); diff --git a/AuthorizationForm.cs b/AuthorizationForm.cs index 85fd7c0..741cb61 100644 --- a/AuthorizationForm.cs +++ b/AuthorizationForm.cs @@ -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()); + + var mainForm = FormManager.Current.CreateForm(); + 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(); + FormManager.Current.Navigate(this, form); } } } diff --git a/AwesomeEmailExtractor.csproj b/AwesomeEmailExtractor.csproj index 546ede3..e634b53 100644 --- a/AwesomeEmailExtractor.csproj +++ b/AwesomeEmailExtractor.csproj @@ -12,6 +12,8 @@ 512 true true + + AnyCPU @@ -33,8 +35,36 @@ 4 + + packages\Microsoft.Data.Sqlite.Core.5.0.3\lib\netstandard2.0\Microsoft.Data.Sqlite.dll + + + packages\SQLitePCLRaw.bundle_e_sqlite3.2.0.4\lib\net461\SQLitePCLRaw.batteries_v2.dll + + + packages\SQLitePCLRaw.core.2.0.4\lib\netstandard2.0\SQLitePCLRaw.core.dll + + + packages\SQLitePCLRaw.bundle_e_sqlite3.2.0.4\lib\net461\SQLitePCLRaw.nativelibrary.dll + + + packages\SQLitePCLRaw.provider.dynamic_cdecl.2.0.4\lib\netstandard2.0\SQLitePCLRaw.provider.dynamic_cdecl.dll + + + packages\System.Buffers.4.4.0\lib\netstandard2.0\System.Buffers.dll + + + packages\System.Memory.4.5.3\lib\netstandard2.0\System.Memory.dll + + + + packages\System.Numerics.Vectors.4.4.0\lib\net46\System.Numerics.Vectors.dll + + + packages\System.Runtime.CompilerServices.Unsafe.4.5.2\lib\netstandard2.0\System.Runtime.CompilerServices.Unsafe.dll + @@ -46,6 +76,7 @@ + Form @@ -53,6 +84,9 @@ AuthorizationForm.cs + + + Form @@ -82,6 +116,7 @@ True Resources.resx + RegistrationForm.cs @@ -99,4 +134,11 @@ + + + + Данный проект ссылается на пакеты NuGet, отсутствующие на этом компьютере. Используйте восстановление пакетов NuGet, чтобы скачать их. Дополнительную информацию см. по адресу: http://go.microsoft.com/fwlink/?LinkID=322105. Отсутствует следующий файл: {0}. + + + \ No newline at end of file diff --git a/FormManager.cs b/FormManager.cs new file mode 100644 index 0000000..39a3473 --- /dev/null +++ b/FormManager.cs @@ -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() 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 _current = new Lazy(); + public static FormManager Current => _current.Value; + + public FormManager() + { + var authorization = CreateForm(); + authorization.Show(); + } + } +} diff --git a/Globals.cs b/Globals.cs new file mode 100644 index 0000000..9ba88dd --- /dev/null +++ b/Globals.cs @@ -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(); + } + } + } +} diff --git a/Logs.cs b/Logs.cs new file mode 100644 index 0000000..9b0a52d --- /dev/null +++ b/Logs.cs @@ -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 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 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 logs = new List(); + 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 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 logs = new List(); + 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 options) + { + if (action == Action.Execute) + { + string sourceText = (string)options["sourceText"]; + int count = (int)options["count"]; + List uniqueEmails = options["uniqueEmails"] as List; + + + return $"Пользователь выполнил поиск email-ов c таким исходным текстом: [ {sourceText}. ]\n" + + $"Найдено {count} email-ов.\n" + + $"Список уникальных: {String.Join(", ", uniqueEmails)}."; + } + if (action == Action.Login) + { + return "Пользователь вошел в систему."; + } + if (action == Action.Registration) + { + return "Пользователь зарегистрировался в системе."; + } + + return ""; + } + } +} diff --git a/MainForm.cs b/MainForm.cs index c66334d..ca6ca5a 100644 --- a/MainForm.cs +++ b/MainForm.cs @@ -16,9 +16,18 @@ namespace AwesomeEmailExtractor { InitializeComponent(); } - + 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 uniqueEmails = new List(); - // Получаем исходный текст из 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() { + { "sourceText", sourceText }, + { "count", count }, + { "uniqueEmails", uniqueEmails } + }); } } } diff --git a/Program.cs b/Program.cs index a06ccf4..e40a3e9 100644 --- a/Program.cs +++ b/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(); } } } diff --git a/RegistrationForm.Designer.cs b/RegistrationForm.Designer.cs index fde80ad..7fe7ef6 100644 --- a/RegistrationForm.Designer.cs +++ b/RegistrationForm.Designer.cs @@ -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(); diff --git a/RegistrationForm.cs b/RegistrationForm.cs index d996d9b..308f39b 100644 --- a/RegistrationForm.cs +++ b/RegistrationForm.cs @@ -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()); + + var form = FormManager.Current.CreateForm(); + 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(); + FormManager.Current.Navigate(this, form); + } - new AuthorizationForm().Show(); + private void RegistrationForm_FormClosed(object sender, FormClosedEventArgs e) + { + } } } diff --git a/packages.config b/packages.config new file mode 100644 index 0000000..277899e --- /dev/null +++ b/packages.config @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file