upd Authentification

This commit is contained in:
Daria
2021-10-20 06:09:18 +03:00
parent eab3081ec2
commit 72069508d2
24 changed files with 457 additions and 191 deletions

View File

@@ -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;
}
}
}
}

View File

@@ -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,

View File

@@ -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; }
}
}

View File

@@ -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<List<string>>(user.phone);
int choosenTrack = user.track;

View File

@@ -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<List<string>>(user.phone);
@params.Message = "Участник:\n\n" +
fio + "\n" +
userVk[0].FirstName + " " + userVk[0].LastName + "\n" +
"Дата рождения: " + birthday.ToShortDateString() + "\n" +
"Телефон: " + jsPhones[0];

View File

@@ -41,23 +41,15 @@ namespace SvetoforVKBot.Models.Commands.ExpertLK
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)

View File

@@ -36,6 +36,9 @@ namespace SvetoforVKBot.Models.Commands.LK.Consultation
List<int> ids = new List<int>();
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" +

View File

@@ -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();

View File

@@ -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<List<string>>(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<List<string>>(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() +

View File

@@ -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

View File

@@ -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)

View File

@@ -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();

View File

@@ -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);
}
}
}

View File

@@ -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);
}
}
}

View File

@@ -34,44 +34,11 @@ namespace SvetoforVKBot.Models.Commands.Registration
{
var user = db.Users.Single(usr => usr.chatId == chatId);
List<MediaAttachment> listDoc = new List<MediaAttachment>()
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)
{

View File

@@ -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";

View File

@@ -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
{
@@ -37,88 +38,6 @@ namespace SvetoforVKBot.Models.Commands
var gender = Convert.ToInt32(user[0].Sex);
var listButtons = new List<ReadOnlyCollection<MessageKeyboardButton>>();
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
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;

View File

@@ -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);

View File

@@ -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<Sourse>() { new Sourse() { name = "main", dateTime = DateTime.Now } }

View File

@@ -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);
}
}
}
}

View File

@@ -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();
}
}
}
}

View File

@@ -1,6 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\packages\EntityFramework.6.4.4\build\EntityFramework.props" Condition="Exists('..\packages\EntityFramework.6.4.4\build\EntityFramework.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@@ -46,11 +45,14 @@
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="BouncyCastle.Crypto, Version=1.8.10.0, Culture=neutral, PublicKeyToken=0e99375e54769942, processorArchitecture=MSIL">
<HintPath>..\packages\Portable.BouncyCastle.1.8.10\lib\net40\BouncyCastle.Crypto.dll</HintPath>
</Reference>
<Reference Include="EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
<HintPath>..\packages\EntityFramework.6.4.4\lib\net45\EntityFramework.dll</HintPath>
<HintPath>..\packages\EntityFramework.6.2.0\lib\net45\EntityFramework.dll</HintPath>
</Reference>
<Reference Include="EntityFramework.SqlServer, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
<HintPath>..\packages\EntityFramework.6.4.4\lib\net45\EntityFramework.SqlServer.dll</HintPath>
<HintPath>..\packages\EntityFramework.6.2.0\lib\net45\EntityFramework.SqlServer.dll</HintPath>
</Reference>
<Reference Include="Google.Apis, Version=1.54.0.0, Culture=neutral, PublicKeyToken=4b01fa6e34db77ab, processorArchitecture=MSIL">
<HintPath>..\packages\Google.Apis.1.54.0\lib\net45\Google.Apis.dll</HintPath>
@@ -73,6 +75,9 @@
<Reference Include="HtmlAgilityPack, Version=1.11.36.0, Culture=neutral, PublicKeyToken=bd319b19eaf3b43a, processorArchitecture=MSIL">
<HintPath>..\packages\HtmlAgilityPack.1.11.36\lib\Net45\HtmlAgilityPack.dll</HintPath>
</Reference>
<Reference Include="MailKit, Version=2.15.0.0, Culture=neutral, PublicKeyToken=4e064fe7c44a8f1b, processorArchitecture=MSIL">
<HintPath>..\packages\MailKit.2.15.0\lib\net47\MailKit.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Bcl.AsyncInterfaces, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Bcl.AsyncInterfaces.5.0.0\lib\net461\Microsoft.Bcl.AsyncInterfaces.dll</HintPath>
</Reference>
@@ -89,10 +94,16 @@
<Reference Include="Microsoft.Extensions.Logging.Abstractions, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Logging.Abstractions.5.0.0\lib\net461\Microsoft.Extensions.Logging.Abstractions.dll</HintPath>
</Reference>
<Reference Include="MimeKit, Version=2.15.0.0, Culture=neutral, PublicKeyToken=bede1c8a46c66814, processorArchitecture=MSIL">
<HintPath>..\packages\MimeKit.2.15.1\lib\net47\MimeKit.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.13.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Buffers, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll</HintPath>
</Reference>
<Reference Include="System.Data" />
<Reference Include="System.Drawing" />
<Reference Include="System.Net.Http.Formatting, Version=5.2.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
@@ -280,10 +291,12 @@
<Compile Include="Models\Commands\LK\Tracks\SelectTrackCommand.cs" />
<Compile Include="Models\Commands\Registration\GetGenderCommand.cs" />
<Compile Include="Models\Commands\Registration\GetKorpusCommand.cs" />
<Compile Include="Models\Commands\Registration\GetLoginCommand.cs" />
<Compile Include="Models\Commands\Registration\GetPhoneCommand.cs" />
<Compile Include="Models\Commands\Registration\GetAgeCommand.cs" />
<Compile Include="Models\Commands\Registration\Date\GetDRYearCommand.cs" />
<Compile Include="Models\Commands\Registration\GetFIOCommand.cs" />
<Compile Include="Models\Commands\Registration\GetPincodeCommand.cs" />
<Compile Include="Models\Commands\Registration\SelectAcceptPDCommand.cs" />
<Compile Include="Models\Commands\Registration\SelectActivityCoefCommand.cs" />
<Compile Include="Models\Commands\Registration\SelectActivityCommand.cs" />
@@ -327,6 +340,8 @@
<DesignTimeSharedInput>True</DesignTimeSharedInput>
<DependentUpon>Settings.settings</DependentUpon>
</Compile>
<Compile Include="Services\EmailService.cs" />
<Compile Include="Services\PasswordService.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="Content\bootstrap-grid.css" />
@@ -461,11 +476,8 @@
<PropertyGroup>
<ErrorText>Данный проект ссылается на пакеты NuGet, отсутствующие на этом компьютере. Используйте восстановление пакетов NuGet, чтобы скачать их. Дополнительную информацию см. по адресу: http://go.microsoft.com/fwlink/?LinkID=322105. Отсутствует следующий файл: {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\EntityFramework.6.4.4\build\EntityFramework.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\EntityFramework.6.4.4\build\EntityFramework.props'))" />
<Error Condition="!Exists('..\packages\EntityFramework.6.4.4\build\EntityFramework.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\EntityFramework.6.4.4\build\EntityFramework.targets'))" />
<Error Condition="!Exists('..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.3.6.0\build\net472\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.3.6.0\build\net472\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.targets'))" />
</Target>
<Import Project="..\packages\EntityFramework.6.4.4\build\EntityFramework.targets" Condition="Exists('..\packages\EntityFramework.6.4.4\build\EntityFramework.targets')" />
<Import Project="..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.3.6.0\build\net472\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.targets" Condition="Exists('..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.3.6.0\build\net472\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.targets')" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.

View File

@@ -5,9 +5,10 @@
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<section name="VKApi" type="SvetoforVKBot.App_Start.VKApiConfiguration"/>
<section name="VKApi" type="SvetoforVKBot.App_Start.VKApiConfiguration" />
<section name="SmtpClient" type="SvetoforVKBot.App_Start.SmtpClientCofiguration" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
@@ -83,6 +84,7 @@
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
<system.codedom>
<compilers>
@@ -93,8 +95,6 @@
<connectionStrings>
<add name="SvetoforVKBotEntities" connectionString="metadata=res://*/Data.VKBot.csdl|res://*/Data.VKBot.ssdl|res://*/Data.VKBot.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=31.31.198.169;initial catalog=u1118637_SvetoforVKBot;persist security info=True;user id=u1118637_SvetoforVKUser;password=c8y7V@aGl6;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
</connectionStrings>
<VKApi name="Production"
token ="6920e1e63500e43e9449ac83811b6651f2a965ae8a09014189b2b1b4a8794e5cc7377bfb21a812bd5b445"
secret="84kPsAWgIFmo8s8Hz9ck7AQxmOXIQiJFOvWi2OTWJt5hJI1yDY"
confirmation="d19cc043"/>
<VKApi name="Production" token="6920e1e63500e43e9449ac83811b6651f2a965ae8a09014189b2b1b4a8794e5cc7377bfb21a812bd5b445" secret="84kPsAWgIFmo8s8Hz9ck7AQxmOXIQiJFOvWi2OTWJt5hJI1yDY" confirmation="d19cc043" />
<SmtpClient host="" port="0" userName="" password="" sso="1" email="" fromName="" />
</configuration>

View File

@@ -2,7 +2,7 @@
<packages>
<package id="Antlr" version="3.5.0.2" targetFramework="net472" />
<package id="bootstrap" version="5.1.0" targetFramework="net472" />
<package id="EntityFramework" version="6.4.4" targetFramework="net472" />
<package id="EntityFramework" version="6.2.0" targetFramework="net472" />
<package id="EntityFramework.ru" version="6.2.0" targetFramework="net472" />
<package id="Google.Apis" version="1.54.0" targetFramework="net472" />
<package id="Google.Apis.Auth" version="1.54.0" targetFramework="net472" />
@@ -11,6 +11,7 @@
<package id="HtmlAgilityPack" version="1.11.36" targetFramework="net472" />
<package id="jQuery" version="3.6.0" targetFramework="net472" />
<package id="jQuery.Validation" version="1.19.3" targetFramework="net472" />
<package id="MailKit" version="2.15.0" targetFramework="net472" />
<package id="Microsoft.AspNet.Mvc" version="5.2.7" targetFramework="net472" />
<package id="Microsoft.AspNet.Mvc.ru" version="5.2.7" targetFramework="net472" />
<package id="Microsoft.AspNet.Razor" version="3.2.7" targetFramework="net472" />
@@ -30,8 +31,11 @@
<package id="Microsoft.Extensions.Logging.Abstractions" version="5.0.0" targetFramework="net472" />
<package id="Microsoft.jQuery.Unobtrusive.Validation" version="3.2.12" targetFramework="net472" />
<package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net472" />
<package id="MimeKit" version="2.15.1" targetFramework="net472" />
<package id="Modernizr" version="2.8.3" targetFramework="net472" />
<package id="Newtonsoft.Json" version="13.0.1" targetFramework="net472" />
<package id="Portable.BouncyCastle" version="1.8.10" targetFramework="net472" />
<package id="System.Buffers" version="4.5.1" targetFramework="net472" />
<package id="System.Runtime.CompilerServices.Unsafe" version="5.0.0" targetFramework="net472" />
<package id="System.Text.Encoding.CodePages" version="5.0.0" targetFramework="net472" />
<package id="System.Threading.Tasks.Extensions" version="4.5.4" targetFramework="net472" />