From 72069508d20a681276a4b6867f50f2804a431cc7 Mon Sep 17 00:00:00 2001 From: Daria Date: Wed, 20 Oct 2021 06:09:18 +0300 Subject: [PATCH] upd Authentification --- SvetoforVKBot/App_Start/WebConfiguration.cs | 91 +++++++++++++++ .../Controllers/ExportDataController.cs | 4 +- SvetoforVKBot/Data/Users.cs | 5 +- .../Commands/Admin/SelectTestNotifyCommand.cs | 2 +- .../ExpertLK/SelectParticipantInfoCommand.cs | 8 +- .../ExpertLK/SelectUpPersonalPlanCommand.cs | 18 +-- .../SelectSubmitConsultationCommand.cs | 7 +- .../Commands/LK/EditData/GetEditFIOCommand.cs | 2 +- .../Commands/LK/SelectEditDataCommand.cs | 10 +- .../Models/Commands/LK/ShowLKCommand.cs | 2 - .../LK/SportsLK/ShowSportsLKCommand.cs | 14 --- .../Commands/Registration/GetFIOCommand.cs | 1 - .../Commands/Registration/GetLoginCommand.cs | 85 ++++++++++++++ .../Registration/GetPincodeCommand.cs | 108 ++++++++++++++++++ .../Registration/SelectParticipateCommand.cs | 45 ++------ .../Registration/SelectRegVkNameCommand.cs | 2 +- .../Models/Commands/Start/StartCommand.cs | 95 +-------------- SvetoforVKBot/Models/Dop/CheckTag.cs | 10 ++ SvetoforVKBot/Models/Dop/GetData.cs | 8 +- SvetoforVKBot/Services/EmailService.cs | 43 +++++++ SvetoforVKBot/Services/PasswordService.cs | 46 ++++++++ SvetoforVKBot/SvetoforVKBot.csproj | 24 +++- SvetoforVKBot/Web.config | 12 +- SvetoforVKBot/packages.config | 6 +- 24 files changed, 457 insertions(+), 191 deletions(-) create mode 100644 SvetoforVKBot/Models/Commands/Registration/GetLoginCommand.cs create mode 100644 SvetoforVKBot/Models/Commands/Registration/GetPincodeCommand.cs create mode 100644 SvetoforVKBot/Services/EmailService.cs create mode 100644 SvetoforVKBot/Services/PasswordService.cs diff --git a/SvetoforVKBot/App_Start/WebConfiguration.cs b/SvetoforVKBot/App_Start/WebConfiguration.cs index 246ae54..abc2f7f 100644 --- a/SvetoforVKBot/App_Start/WebConfiguration.cs +++ b/SvetoforVKBot/App_Start/WebConfiguration.cs @@ -72,5 +72,96 @@ namespace SvetoforVKBot.App_Start this["groupdialoglink"] = value; } } + + [ConfigurationProperty("host", IsRequired = true, DefaultValue = "")] + public string Host + { + get + { + return (string)this["host"]; + } + set + { + this["host"] = value; + } + } + + [ConfigurationProperty("port", IsRequired = true, DefaultValue = "0")] + public int Port + { + get + { + return (int)this["port"]; + } + set + { + this["port"] = value; + } + } + + [ConfigurationProperty("userName", IsRequired = true, DefaultValue = "")] + public string UserName + { + get + { + return (string)this["userName"]; + } + set + { + this["userName"] = value; + } + } + + [ConfigurationProperty("password", IsRequired = true, DefaultValue = "")] + public string Password + { + get + { + return (string)this["password"]; + } + set + { + this["password"] = value; + } + } + + [ConfigurationProperty("sso", IsRequired = true, DefaultValue = "1")] + public int SSO + { + get + { + return (int)this["sso"]; + } + set + { + this["sso"] = value; + } + } + + [ConfigurationProperty("email", IsRequired = true, DefaultValue = "")] + public string Email + { + get + { + return (string)this["email"]; + } + set + { + this["email"] = value; + } + } + + [ConfigurationProperty("fromName", IsRequired = true, DefaultValue = "")] + public string FromName + { + get + { + return (string)this["fromName"]; + } + set + { + this["fromName"] = value; + } + } } } \ No newline at end of file diff --git a/SvetoforVKBot/Controllers/ExportDataController.cs b/SvetoforVKBot/Controllers/ExportDataController.cs index baea733..3e43d91 100644 --- a/SvetoforVKBot/Controllers/ExportDataController.cs +++ b/SvetoforVKBot/Controllers/ExportDataController.cs @@ -137,7 +137,7 @@ namespace SvetoforVKBot.Controllers u.chatId.ToString(), u.firstName.ToString(), u.lastName.ToString(), - u.fio.ToString(), + //u.fio.ToString(), reg, phone, u.birthday.ToShortDateString(), @@ -198,7 +198,7 @@ namespace SvetoforVKBot.Controllers var consultations = db.PersonalConsultations.Join(db.Users, pc => pc.chatId, u => u.chatId, (pc, u) => new PersonalCons{ chatId = pc.chatId, - fio = u.fio, + //fio = u.fio, phone = u.phone, birthdate = u.birthday, question = u.question, diff --git a/SvetoforVKBot/Data/Users.cs b/SvetoforVKBot/Data/Users.cs index 086e237..a7e96ee 100644 --- a/SvetoforVKBot/Data/Users.cs +++ b/SvetoforVKBot/Data/Users.cs @@ -19,7 +19,7 @@ namespace SvetoforVKBot.Data public int admin { get; set; } public string firstName { get; set; } public string lastName { get; set; } - public string fio { get; set; } + //public string fio { get; set; } public int reg { get; set; } public string tag { get; set; } public string voronka { get; set; } @@ -52,5 +52,8 @@ namespace SvetoforVKBot.Data public string choosenProducts { get; set; } public int child { get; set; } public int export { get; set; } + public string login { get; set; } + public string password { get; set; } + public int isAuthorized { get; set; } } } diff --git a/SvetoforVKBot/Models/Commands/Admin/SelectTestNotifyCommand.cs b/SvetoforVKBot/Models/Commands/Admin/SelectTestNotifyCommand.cs index 98be625..c5bfdbd 100644 --- a/SvetoforVKBot/Models/Commands/Admin/SelectTestNotifyCommand.cs +++ b/SvetoforVKBot/Models/Commands/Admin/SelectTestNotifyCommand.cs @@ -53,7 +53,7 @@ namespace SvetoforVKBot.Models.Commands.Admin //-- var user = db.Users.Single(usr => usr.chatId == 59111081); int id = user.id; - string fio = user.fio; + //string fio = user.fio; var birthday = user.birthday; var jsPhones = JsonConvert.DeserializeObject>(user.phone); int choosenTrack = user.track; diff --git a/SvetoforVKBot/Models/Commands/ExpertLK/SelectParticipantInfoCommand.cs b/SvetoforVKBot/Models/Commands/ExpertLK/SelectParticipantInfoCommand.cs index 9b86878..da0b59c 100644 --- a/SvetoforVKBot/Models/Commands/ExpertLK/SelectParticipantInfoCommand.cs +++ b/SvetoforVKBot/Models/Commands/ExpertLK/SelectParticipantInfoCommand.cs @@ -38,12 +38,16 @@ namespace SvetoforVKBot.Models.Commands.ExpertLK var user = db.Users.Single(usr => usr.id == userId); int uChatId = Convert.ToInt32(user.chatId); - string fio = user.fio; + + var idsVk = new long[] { uChatId }; + var userVk = client.Users.Get(idsVk); + + //string fio = user.fio; var birthday = user.birthday; var jsPhones = JsonConvert.DeserializeObject>(user.phone); @params.Message = "Участник:\n\n" + - fio + "\n" + + userVk[0].FirstName + " " + userVk[0].LastName + "\n" + "Дата рождения: " + birthday.ToShortDateString() + "\n" + "Телефон: " + jsPhones[0]; diff --git a/SvetoforVKBot/Models/Commands/ExpertLK/SelectUpPersonalPlanCommand.cs b/SvetoforVKBot/Models/Commands/ExpertLK/SelectUpPersonalPlanCommand.cs index 6b9eb3a..9a5e8ef 100644 --- a/SvetoforVKBot/Models/Commands/ExpertLK/SelectUpPersonalPlanCommand.cs +++ b/SvetoforVKBot/Models/Commands/ExpertLK/SelectUpPersonalPlanCommand.cs @@ -37,27 +37,19 @@ namespace SvetoforVKBot.Models.Commands.ExpertLK string[] payload = update.@object.message.payload.Split('-'); int userId = Convert.ToInt32(regex.Replace(payload[1], "")); //@params.Message = "Выберите участника.\n"; - + var user = db.Users.Single(usr => usr.id == userId); int uChatId = user.chatId; - string fio = user.fio; + + var idsVk = new long[] { uChatId }; + var userVk = client.Users.Get(idsVk); user.personal = 1; db.Entry(db.PersonalConsultations.Where(el => el.chatId == uChatId)).Property("state").CurrentValue = 2; db.SaveChanges(); - //SqlCommand updTag = new SqlCommand("UPDATE Users SET personal = @personal WHERE chatId = @chatId;", Con); - //updTag.Parameters.AddWithValue("@chatId", uChatId); - //updTag.Parameters.AddWithValue("@personal", 1); - //updTag.ExecuteNonQuery(); - - //SqlCommand updState = new SqlCommand("UPDATE PersonalConsultation SET state = @state WHERE chatId = @chatId;", Con); - //updState.Parameters.AddWithValue("@chatId", uChatId); - //updState.Parameters.AddWithValue("@state", 2); - //updState.ExecuteNonQuery(); - - @params.Message = "✅Персональный режим для участника " + fio + " включен"; + @params.Message = "✅Персональный режим для участника " + userVk[0].FirstName + " " + userVk[0].LastName + " включен"; keyboardBuilder //.AddButton("Вкл. персональный режим", "selectPersonalPlan-", KeyboardButtonColor.Positive) diff --git a/SvetoforVKBot/Models/Commands/LK/Consultation/SelectSubmitConsultationCommand.cs b/SvetoforVKBot/Models/Commands/LK/Consultation/SelectSubmitConsultationCommand.cs index 203e1f9..af01d3e 100644 --- a/SvetoforVKBot/Models/Commands/LK/Consultation/SelectSubmitConsultationCommand.cs +++ b/SvetoforVKBot/Models/Commands/LK/Consultation/SelectSubmitConsultationCommand.cs @@ -36,6 +36,9 @@ namespace SvetoforVKBot.Models.Commands.LK.Consultation List ids = new List(); try { + var idsVk = new long[] { chatId }; + var userVk = client.Users.Get(idsVk); + if (db.PersonalConsultations.Where(c => c.chatId == chatId).Count() > 0) { @params.Message = "Ваша заявка уже на рассмотрении. Чтобы вернуться назад, нажмите кнопку \"Личный кабинет\"."; @@ -69,7 +72,7 @@ namespace SvetoforVKBot.Models.Commands.LK.Consultation @params.Message = "📌Ваша заявка:\n\n"; - msg = "ФИО: " + user.fio + + msg = "Имя: " + userVk[0].FirstName + " " + userVk[0].LastName + "\n" + "\n" + "Телефон: " + jsPhones[0] + "\n" + @@ -94,7 +97,7 @@ namespace SvetoforVKBot.Models.Commands.LK.Consultation Thread.Sleep(1000); @params2.Message = "✅Новая заявка на консультацию:\n\n" + - "ФИО: " + user.fio + + "Имя: " + userVk[0].FirstName + " " + userVk[0].LastName + "\n" + "\n" + "Телефон: " + jsPhones[0] + "\n" + diff --git a/SvetoforVKBot/Models/Commands/LK/EditData/GetEditFIOCommand.cs b/SvetoforVKBot/Models/Commands/LK/EditData/GetEditFIOCommand.cs index 5332250..9db0fce 100644 --- a/SvetoforVKBot/Models/Commands/LK/EditData/GetEditFIOCommand.cs +++ b/SvetoforVKBot/Models/Commands/LK/EditData/GetEditFIOCommand.cs @@ -27,7 +27,7 @@ namespace SvetoforVKBot.Models.Commands.LK.EditData var ids = new long[] { chatId }; var user = db.Users.Single(usr => usr.chatId == chatId); - user.fio = update.@object.message.text.Trim(); + //user.fio = update.@object.message.text.Trim(); user.tag = "Личный кабинет - Данные"; db.SaveChanges(); diff --git a/SvetoforVKBot/Models/Commands/LK/SelectEditDataCommand.cs b/SvetoforVKBot/Models/Commands/LK/SelectEditDataCommand.cs index 7f4380e..9e2bc3c 100644 --- a/SvetoforVKBot/Models/Commands/LK/SelectEditDataCommand.cs +++ b/SvetoforVKBot/Models/Commands/LK/SelectEditDataCommand.cs @@ -58,7 +58,7 @@ namespace SvetoforVKBot.Models.Commands.LK int height = user.height; int gender = user.gender; int notifyCount = user.notifyCount; - string fio = user.fio; + //string fio = user.fio; var jsPhones = JsonConvert.DeserializeObject>(user.phone); var birthday = user.birthday; int track = user.track; @@ -74,7 +74,7 @@ namespace SvetoforVKBot.Models.Commands.LK .AddButton("📐Рост: " + height, "selectEditData-2", KeyboardButtonColor.Primary) .AddLine() .AddButton("🔔Уведомления", "selectEditData-3", KeyboardButtonColor.Primary) - .AddButton("✏ФИО", "selectEditData-4", KeyboardButtonColor.Primary) + //.AddButton("✏ФИО", "selectEditData-4", KeyboardButtonColor.Primary) .AddLine() .AddButton("📅Дата рождения", "selectEditData-5", KeyboardButtonColor.Primary) .AddButton("📞Телефон", "selectEditData-6", KeyboardButtonColor.Primary) @@ -116,8 +116,6 @@ namespace SvetoforVKBot.Models.Commands.LK @params.Message = "РЕДАКТИРОВАНИЕ ДАННЫХ" + "\n\n" + - "ФИО: " + fio + - "\n" + "Телефон: " + jsPhones[0] + "\n" + "Дата рождения: " + birthday.ToShortDateString() + @@ -190,7 +188,7 @@ namespace SvetoforVKBot.Models.Commands.LK int height = user.height; int gender = user.gender; int notifyCount = user.notifyCount; - string fio = user.fio; + //string fio = user.fio; var jsPhones = JsonConvert.DeserializeObject>(user.phone); var birthday = user.birthday; int track = user.track; @@ -251,8 +249,6 @@ namespace SvetoforVKBot.Models.Commands.LK @params.Message = "РЕДАКТИРОВАНИЕ ДАННЫХ" + "\n\n" + - "ФИО: " + fio + - "\n" + "Телефон: " + jsPhones[0] + "\n" + "Дата рождения: " + birthday.ToShortDateString() + diff --git a/SvetoforVKBot/Models/Commands/LK/ShowLKCommand.cs b/SvetoforVKBot/Models/Commands/LK/ShowLKCommand.cs index cd7afdc..5eba275 100644 --- a/SvetoforVKBot/Models/Commands/LK/ShowLKCommand.cs +++ b/SvetoforVKBot/Models/Commands/LK/ShowLKCommand.cs @@ -40,8 +40,6 @@ namespace SvetoforVKBot.Models.Commands.LK user.colorId = 0; db.SaveChanges(); - msg += user.fio + "\n\n"; - if ((DateTime.Now.Month >= user.birthday.Month) && (DateTime.Now.Day >= user.birthday.Day)) age = DateTime.Now.Year - user.birthday.Year; else diff --git a/SvetoforVKBot/Models/Commands/LK/SportsLK/ShowSportsLKCommand.cs b/SvetoforVKBot/Models/Commands/LK/SportsLK/ShowSportsLKCommand.cs index 0601502..49d56a9 100644 --- a/SvetoforVKBot/Models/Commands/LK/SportsLK/ShowSportsLKCommand.cs +++ b/SvetoforVKBot/Models/Commands/LK/SportsLK/ShowSportsLKCommand.cs @@ -38,20 +38,6 @@ namespace SvetoforVKBot.Models.Commands.LK.SportsLK user.colorId = 0; db.SaveChanges(); - //SqlCommand getUser = new SqlCommand("SELECT * FROM Users WHERE chatId = @chatId;", Con); - //getUser.Parameters.AddWithValue("@chatId", chatId); - //SqlDataReader rgetUser = getUser.ExecuteReader(); - //rgetUser.Read(); - //string fio = rgetUser["fio"].ToString(); - //int weight = Convert.ToInt32(rgetUser["weight"]); - //int height = Convert.ToInt32(rgetUser["height"]); - //int gender = Convert.ToInt32(rgetUser["gender"]); - //var birthday = DateTime.Parse(rgetUser["birthday"].ToString()); - //int kkal = Convert.ToInt32(rgetUser["kkal"]); - //rgetUser.Close(); - - msg += user.fio + "\n\n"; - age = (DateTime.Today.Year - user.birthday.Year); if (user.gender == 1) diff --git a/SvetoforVKBot/Models/Commands/Registration/GetFIOCommand.cs b/SvetoforVKBot/Models/Commands/Registration/GetFIOCommand.cs index 6f74959..cba106d 100644 --- a/SvetoforVKBot/Models/Commands/Registration/GetFIOCommand.cs +++ b/SvetoforVKBot/Models/Commands/Registration/GetFIOCommand.cs @@ -32,7 +32,6 @@ namespace SvetoforVKBot.Models.Commands.Registration var ids = new long[] { chatId }; var user = db.Users.Single(usr => usr.chatId == chatId); - user.fio = update.@object.message.text.Trim(); user.tag = "Подписчик - Регистрация - ДР - Год"; db.SaveChanges(); diff --git a/SvetoforVKBot/Models/Commands/Registration/GetLoginCommand.cs b/SvetoforVKBot/Models/Commands/Registration/GetLoginCommand.cs new file mode 100644 index 0000000..6bc228f --- /dev/null +++ b/SvetoforVKBot/Models/Commands/Registration/GetLoginCommand.cs @@ -0,0 +1,85 @@ +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Net.Http; +using System.Security.Cryptography; +using System.Text; +using SvetoforVKBot.Models.Updates; +using VkNet; +using VkNet.Enums.SafetyEnums; +using VkNet.Model.Keyboard; +using VkNet.Model.RequestParams; +using System.Linq; +using SvetoforVKBot.Services; + +namespace SvetoforVKBot.Models.Commands.Registration +{ + public class GetLoginCommand + { + public void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db) + { + var chatId = update.@object.message.from_id; + MessagesSendParams @params = new MessagesSendParams(); + var keyboardBuilder = new KeyboardBuilder().Clear(); + + try + { + if (update.@object.message.text.Length > 0 && update.@object.message.text.Length <= 50) + { + var ids = new long[] { chatId }; + string login = update.@object.message.text.Trim(); + string message = ""; + var user = db.Users.Single(usr => usr.chatId == chatId); + string pincode = PasswordService.GeneratePassword(); + string hash = PasswordService.CreateMD5(pincode + chatId.ToString()); + message = $"Ваш код подтверждения: {pincode}"; + + + keyboardBuilder + .AddButton("Отменить", "startPL", KeyboardButtonColor.Default); + @params.Keyboard = keyboardBuilder.Build(); + @params.Message = "На Вашу корпоративную почту отправлено письмо с кодом подтверждения.\n" + + "Введите код в ответ на данное сообщение, чтобы завершить авторизацию."; + @params.UserId = chatId; + @params.RandomId = GetRandomId(); + client.Messages.SendAsync(@params); + + user.login = login; + user.password = hash; + user.tag = "Подписчик - Регистрация - Код"; + db.SaveChanges(); + + EmailService emailService = new EmailService(); + emailService.SendEmailAsync($"{login}@vyatsu.ru", "Код подтверждения", message); + + } + else + { + @params.Message = "Данные введены некорректно 😕 Напишите, пожалуйста, текст длиной до 50 символов."; + @params.UserId = chatId; + @params.RandomId = GetRandomId(); + client.Messages.SendAsync(@params); + } + } + catch (Exception ee) + { + @params.Message = "‼Ошибка в GetFIOCommand: " + ee.Message; + @params.Attachments = null; + @params.Keyboard = null; + @params.UserId = 59111081; + @params.RandomId = GetRandomId(); + client.Messages.SendAsync(@params); + } + } + + private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create(); + public int GetRandomId() + { + var intBytes = new byte[4]; + + Rng.GetBytes(intBytes); + + return BitConverter.ToInt32(intBytes, 0); + } + } +} \ No newline at end of file diff --git a/SvetoforVKBot/Models/Commands/Registration/GetPincodeCommand.cs b/SvetoforVKBot/Models/Commands/Registration/GetPincodeCommand.cs new file mode 100644 index 0000000..a63d90f --- /dev/null +++ b/SvetoforVKBot/Models/Commands/Registration/GetPincodeCommand.cs @@ -0,0 +1,108 @@ +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Net.Http; +using System.Security.Cryptography; +using System.Text; +using SvetoforVKBot.Models.Updates; +using VkNet; +using VkNet.Enums.SafetyEnums; +using VkNet.Model.Keyboard; +using VkNet.Model.RequestParams; +using System.Linq; +using SvetoforVKBot.Services; +using SvetoforVKBot.Models.Commands.LK; + +namespace SvetoforVKBot.Models.Commands.Registration +{ + public class GetPincodeCommand + { + public void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db) + { + var chatId = update.@object.message.from_id; + MessagesSendParams @params = new MessagesSendParams(); + var keyboardBuilder = new KeyboardBuilder().Clear(); + + try + { + if (update.@object.message.text.Length > 0 && update.@object.message.text.Length <= 50) + { + var ids = new long[] { chatId }; + string pincode = update.@object.message.text.Trim(); + var user = db.Users.Single(usr => usr.chatId == chatId); + + string hashCheck = PasswordService.CreateMD5(pincode + chatId.ToString()); + + if (user.password.Equals(hashCheck)) + { + user.isAuthorized = 1; + user.tag = "Подписчик - Регистрация - Пол"; + db.SaveChanges(); + + if (user.reg == 1) + { + ShowLKCommand showLK = new ShowLKCommand(); + showLK.Execute(update, client, db); + } + else + { + + + keyboardBuilder + .AddButton("М", "selectGender-1", KeyboardButtonColor.Primary) + .AddButton("Ж", "selectGender-2", KeyboardButtonColor.Primary) + .AddLine() + .AddButton("Отменить", "startPL", KeyboardButtonColor.Default); + + @params.Keyboard = keyboardBuilder.Build(); + @params.UserId = chatId; + @params.Message = //1 шаг из 4. + "✅ Авторизация прошла успешно.\n" + + "Выберите на клавиатуре внизу или напишите пол в формате \"М\" или \"Ж\""; + @params.RandomId = GetRandomId(); + client.Messages.SendAsync(@params); + } + } + else + { + keyboardBuilder + .AddButton("Отменить", "startPL", KeyboardButtonColor.Default); + + @params.Keyboard = keyboardBuilder.Build(); + @params.Message = "Вы ввели неверный код подтверждения. Попробуйте ещё раз."; + @params.UserId = chatId; + @params.RandomId = GetRandomId(); + client.Messages.SendAsync(@params); + } + + } + else + { + @params.Message = "Данные введены некорректно 😕 Напишите, пожалуйста, текст длиной до 50 символов."; + @params.UserId = chatId; + @params.RandomId = GetRandomId(); + client.Messages.SendAsync(@params); + } + } + catch (Exception ee) + { + @params.Message = "‼Ошибка в GetFIOCommand: " + ee.Message; + @params.Attachments = null; + @params.Keyboard = null; + @params.UserId = 59111081; + @params.RandomId = GetRandomId(); + client.Messages.SendAsync(@params); + } + } + + private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create(); + public int GetRandomId() + { + var intBytes = new byte[4]; + + Rng.GetBytes(intBytes); + + return BitConverter.ToInt32(intBytes, 0); + } + } +} \ No newline at end of file diff --git a/SvetoforVKBot/Models/Commands/Registration/SelectParticipateCommand.cs b/SvetoforVKBot/Models/Commands/Registration/SelectParticipateCommand.cs index b2ef6eb..16ce764 100644 --- a/SvetoforVKBot/Models/Commands/Registration/SelectParticipateCommand.cs +++ b/SvetoforVKBot/Models/Commands/Registration/SelectParticipateCommand.cs @@ -34,44 +34,11 @@ namespace SvetoforVKBot.Models.Commands.Registration { var user = db.Users.Single(usr => usr.chatId == chatId); - List listDoc = new List() + user.tag = "Подписчик - Регистрация - Авторизация"; + db.SaveChanges(); + + if (user.isAuthorized == 0) { - new Document() { Id = 602601883, OwnerId = 59111081 } //59111081_600676073 - }; - - if (user.agree == 0) - { - switch (user.child) - { - case 0: - @params.Message = "Вам уже исполнилось 18 лет? Исходя из возраста, мы сформируем для Вас подходящий документ " + - "согласия на обработку персональных данных.\n\n" + - "Нажмите кнопку на специальной клавиатуре👇"; - - keyboardBuilder - .AddButton("Да", "selectChildAge-2", KeyboardButtonColor.Positive) - .AddButton("Нет", "selectChildAge-1", KeyboardButtonColor.Negative) - .AddLine() - .AddButton("Назад", "startPL", KeyboardButtonColor.Default); - - @params.Keyboard = keyboardBuilder.Build(); - @params.UserId = chatId; - @params.RandomId = GetRandomId(); - client.Messages.SendAsync(@params); - return; - - default: - SelectAgreementCommand selectAgreement = new SelectAgreementCommand(); - selectAgreement.ExecutePL(update, client, db); - return; - } - - } - else - { - user.tag = "Подписчик - Регистрация - Пол"; - db.SaveChanges(); - keyboardBuilder .AddButton("М", "selectGender-1", KeyboardButtonColor.Primary) .AddButton("Ж", "selectGender-2", KeyboardButtonColor.Primary) @@ -81,10 +48,12 @@ namespace SvetoforVKBot.Models.Commands.Registration @params.Keyboard = keyboardBuilder.Build(); @params.UserId = chatId; @params.Message = //1 шаг из 4. - "Выберите на клавиатуре внизу или напишите пол в формате \"М\" или \"Ж\""; + "Для продолжения необходимо авторизоваться. Введите Ваш логин, ипользуемый на портале ВятГУ.\n" + + "Например, stud0000"; @params.RandomId = GetRandomId(); client.Messages.SendAsync(@params); } + } catch (Exception ee) { diff --git a/SvetoforVKBot/Models/Commands/Registration/SelectRegVkNameCommand.cs b/SvetoforVKBot/Models/Commands/Registration/SelectRegVkNameCommand.cs index 85614ea..058f71b 100644 --- a/SvetoforVKBot/Models/Commands/Registration/SelectRegVkNameCommand.cs +++ b/SvetoforVKBot/Models/Commands/Registration/SelectRegVkNameCommand.cs @@ -30,7 +30,7 @@ namespace SvetoforVKBot.Models.Commands.Registration { var user = db.Users.Single(usr => usr.chatId == chatId); user.tag = "Регистрация - Возраст"; - user.fio = user.firstName + " " + user.lastName; + //user.fio = user.firstName + " " + user.lastName; db.SaveChanges(); @params.Message = "2 шаг из 4. Напиши возраст одним числом, например, 19. \n"; diff --git a/SvetoforVKBot/Models/Commands/Start/StartCommand.cs b/SvetoforVKBot/Models/Commands/Start/StartCommand.cs index 14d2181..03c8cfc 100644 --- a/SvetoforVKBot/Models/Commands/Start/StartCommand.cs +++ b/SvetoforVKBot/Models/Commands/Start/StartCommand.cs @@ -15,6 +15,7 @@ using SvetoforVKBot.Models.Commands.LK; using SvetoforVKBot.Models.Commands.LK.SportsLK; using System.Collections.ObjectModel; using System.Linq; +using SvetoforVKBot.Models.Commands.Registration; namespace SvetoforVKBot.Models.Commands { @@ -36,89 +37,7 @@ namespace SvetoforVKBot.Models.Commands var user = client.Users.Get(ids, ProfileFields.Sex); var gender = Convert.ToInt32(user[0].Sex); var listButtons = new List>(); - Uri URL = new Uri("https://www.vyatsu.ru/"); - #region UTM - /* - utm = update.@object.message.@ref; - - if (utm != "" && utm != null) - { - if (int.TryParse(utm, out int refer)) - { - if (refer != chatId) - { - int referId = 1; - - //Проверяем приглашали ли этого пользователя раннее - getUser = new SqlCommand("SELECT referId FROM Users WHERE chatId = @chatId;", Con); - getUser.Parameters.AddWithValue("@chatId", chatId); - rgetUser = getUser.ExecuteReader(); - rgetUser.Read(); - int uReferId = Convert.ToInt32(rgetUser["referId"]); - rgetUser.Close(); - - if (uReferId == 0) // 0 - не приглашали - { - //Ищем пользователя, который пригласил - SqlCommand getRefer = new SqlCommand("SELECT chatId FROM Users WHERE chatId = @refer;", Con); - getRefer.Parameters.AddWithValue("@refer", refer); - SqlDataReader rgetRefer = getRefer.ExecuteReader(); - if (rgetRefer.HasRows) // если пользователь существует - { - rgetRefer.Close(); - - SqlCommand updReferId = new SqlCommand("UPDATE Users SET referId = @referId WHERE chatId = @chatId;", Con); - updReferId.Parameters.AddWithValue("@chatId", chatId); - updReferId.Parameters.AddWithValue("@referId", refer); - updReferId.ExecuteNonQuery(); - - selectQuestRoom.ExecutePL(update, client, Con); - return; - } - else - rgetRefer.Close(); - } - else - { - selectQuestRoom.ExecutePL(update, client, Con); - return; - } - } - else - { - selectQuestRoom.ExecutePL(update, client, Con); - return; - } - } - - SourceUpdate sourceUpdate = new SourceUpdate(); - sourceUpdate.Execute(update, client, Con); - - switch (utm) - { - case "afisha": - SelectEventsCommand selectEvents = new SelectEventsCommand(); - selectEvents.ExecutePL(update, client, Con); - return; - - case "quest": - selectQuestRoom.ExecutePL(update, client, Con); - return; - - case "project": - SelectProjectOfficeCommand selectProjectOffice = new SelectProjectOfficeCommand(); - selectProjectOffice.ExecutePL(update, client, Con); - return; - - case "faq": - SelectOSCommand selectOS = new SelectOSCommand(); - selectOS.ExecutePL(update, client, Con); - return; - } - - } - */ - #endregion UTM + Uri URL = new Uri("https://www.vyatsu.ru/"); var getUser = db.Users.Single(usr => usr.chatId == chatId); int reg = getUser.reg; @@ -130,17 +49,15 @@ namespace SvetoforVKBot.Models.Commands switch (reg) { case 1: - if (activityKind == 2 || activityKind == 3) + if (getUser.isAuthorized == 1) { ShowLKCommand showLK = new ShowLKCommand(); showLK.Execute(update, client, db); } - else // спортсмены + else { - ShowLKCommand showLK = new ShowLKCommand(); - showLK.Execute(update, client, db); - //ShowSportsLKCommand showSportsLK = new ShowSportsLKCommand(); - //showSportsLK.Execute(update, client, Con); + SelectParticipateCommand selectParticipate = new SelectParticipateCommand(); + selectParticipate.ExecutePL(update, client, db); } return; diff --git a/SvetoforVKBot/Models/Dop/CheckTag.cs b/SvetoforVKBot/Models/Dop/CheckTag.cs index 9f77921..ee7f810 100644 --- a/SvetoforVKBot/Models/Dop/CheckTag.cs +++ b/SvetoforVKBot/Models/Dop/CheckTag.cs @@ -40,6 +40,16 @@ namespace SvetoforVKBot.Models.Dop getGender.Execute(update, client, db); return; + case "Подписчик - Регистрация - Авторизация": + GetLoginCommand getLogin = new GetLoginCommand(); + getLogin.Execute(update, client, db); + return; + + case "Подписчик - Регистрация - Код": + GetPincodeCommand getPincode = new GetPincodeCommand(); + getPincode.Execute(update, client, db); + return; + case "Регистрация - Корпус": GetKorpusCommand getKorpus = new GetKorpusCommand(); getKorpus.Execute(update, client, db); diff --git a/SvetoforVKBot/Models/Dop/GetData.cs b/SvetoforVKBot/Models/Dop/GetData.cs index 0951be9..288ce95 100644 --- a/SvetoforVKBot/Models/Dop/GetData.cs +++ b/SvetoforVKBot/Models/Dop/GetData.cs @@ -28,16 +28,16 @@ namespace SvetoforVKBot.Models.Dop var checkUser = db.Users.FirstOrDefault(u => u.chatId == chatId); if(checkUser!=null) { - checkUser.firstName = firstName; - checkUser.lastName = lastName; + //checkUser.firstName = firstName; + //checkUser.lastName = lastName; } else { db.Users.Add(new Data.Users() { chatId = chatId, - firstName = firstName, - lastName = lastName, + //firstName = firstName, + //lastName = lastName, sourse = JsonConvert.SerializeObject(new Sourses() { sourses = new List() { new Sourse() { name = "main", dateTime = DateTime.Now } } diff --git a/SvetoforVKBot/Services/EmailService.cs b/SvetoforVKBot/Services/EmailService.cs new file mode 100644 index 0000000..9448503 --- /dev/null +++ b/SvetoforVKBot/Services/EmailService.cs @@ -0,0 +1,43 @@ +using MimeKit; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using MailKit.Net.Smtp; +using System.Configuration; +using SvetoforVKBot.App_Start; + +namespace SvetoforVKBot.Services +{ + public class EmailService + { + public async Task SendEmailAsync(string email, string subject, string message) + { + var emailMessage = new MimeMessage(); + + emailMessage.From.Add(new MailboxAddress( + ((WebConfiguration)ConfigurationManager.GetSection("smtpClient")).FromName, + ((WebConfiguration)ConfigurationManager.GetSection("smtpClient")).Email)); + emailMessage.To.Add(new MailboxAddress("", email)); + emailMessage.Subject = subject; + emailMessage.Body = new TextPart(MimeKit.Text.TextFormat.Html) + { + Text = message + }; + + using (var client = new SmtpClient()) + { + //await client.ConnectAsync("mail.hosting.reg.ru", 465); + await client.ConnectAsync( + ((WebConfiguration)ConfigurationManager.GetSection("smtpClient")).Host, + ((WebConfiguration)ConfigurationManager.GetSection("smtpClient")).Port, + (MailKit.Security.SecureSocketOptions)((WebConfiguration)ConfigurationManager.GetSection("smtpClient")).SSO); + await client.AuthenticateAsync( + ((WebConfiguration)ConfigurationManager.GetSection("smtpClient")).UserName, + ((WebConfiguration)ConfigurationManager.GetSection("smtpClient")).Password); + await client.SendAsync(emailMessage); + await client.DisconnectAsync(true); + } + } + } +} \ No newline at end of file diff --git a/SvetoforVKBot/Services/PasswordService.cs b/SvetoforVKBot/Services/PasswordService.cs new file mode 100644 index 0000000..62fc828 --- /dev/null +++ b/SvetoforVKBot/Services/PasswordService.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SvetoforVKBot.Services +{ + public class PasswordService + { + public static string GeneratePassword() + { + + int length = 6; + + StringBuilder password = new StringBuilder(); + Random random = new Random(); + + while (password.Length < length) + { + int c = random.Next(0, 9); + password.Append(c); + } + + return password.ToString(); + } + + public static string CreateMD5(string input) + { + // Use input string to calculate MD5 hash + using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create()) + { + byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input); + byte[] hashBytes = md5.ComputeHash(inputBytes); + + // Convert the byte array to hexadecimal string + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < hashBytes.Length; i++) + { + sb.Append(hashBytes[i].ToString("X2")); + } + return sb.ToString().ToLower(); + } + } + } +} \ No newline at end of file diff --git a/SvetoforVKBot/SvetoforVKBot.csproj b/SvetoforVKBot/SvetoforVKBot.csproj index cc6d1ad..dde67df 100644 --- a/SvetoforVKBot/SvetoforVKBot.csproj +++ b/SvetoforVKBot/SvetoforVKBot.csproj @@ -1,6 +1,5 @@  - Debug @@ -46,11 +45,14 @@ 4 + + ..\packages\Portable.BouncyCastle.1.8.10\lib\net40\BouncyCastle.Crypto.dll + - ..\packages\EntityFramework.6.4.4\lib\net45\EntityFramework.dll + ..\packages\EntityFramework.6.2.0\lib\net45\EntityFramework.dll - ..\packages\EntityFramework.6.4.4\lib\net45\EntityFramework.SqlServer.dll + ..\packages\EntityFramework.6.2.0\lib\net45\EntityFramework.SqlServer.dll ..\packages\Google.Apis.1.54.0\lib\net45\Google.Apis.dll @@ -73,6 +75,9 @@ ..\packages\HtmlAgilityPack.1.11.36\lib\Net45\HtmlAgilityPack.dll + + ..\packages\MailKit.2.15.0\lib\net47\MailKit.dll + ..\packages\Microsoft.Bcl.AsyncInterfaces.5.0.0\lib\net461\Microsoft.Bcl.AsyncInterfaces.dll @@ -89,10 +94,16 @@ ..\packages\Microsoft.Extensions.Logging.Abstractions.5.0.0\lib\net461\Microsoft.Extensions.Logging.Abstractions.dll + + ..\packages\MimeKit.2.15.1\lib\net47\MimeKit.dll + ..\packages\Newtonsoft.Json.13.0.1\lib\net45\Newtonsoft.Json.dll + + ..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll + @@ -280,10 +291,12 @@ + + @@ -327,6 +340,8 @@ True Settings.settings + + @@ -461,11 +476,8 @@ Данный проект ссылается на пакеты NuGet, отсутствующие на этом компьютере. Используйте восстановление пакетов NuGet, чтобы скачать их. Дополнительную информацию см. по адресу: http://go.microsoft.com/fwlink/?LinkID=322105. Отсутствует следующий файл: {0}. - - - -
-
+
+
+ @@ -83,6 +84,7 @@ + @@ -93,8 +95,6 @@ - + + \ No newline at end of file diff --git a/SvetoforVKBot/packages.config b/SvetoforVKBot/packages.config index e90b278..797053d 100644 --- a/SvetoforVKBot/packages.config +++ b/SvetoforVKBot/packages.config @@ -2,7 +2,7 @@ - + @@ -11,6 +11,7 @@ + @@ -30,8 +31,11 @@ + + +