Backend for the Teso project written in 2022
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

198 lines
9.5 KiB

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Net.Mime;
using System.Threading.Tasks;
using Teso_API.Models;
namespace Teso_API.AuthControllers
{
[AllowAnonymous, Route("resetpassword")]
[ApiController]
public class ResetPasswordController : ControllerBase
{
public IConfiguration _configuration;
private readonly TESOContext _context;
private readonly IWebHostEnvironment webHostEnvironemt;
public ResetPasswordController(TESOContext context, IConfiguration config, IWebHostEnvironment _webHostEnvironment)
{
_context = context;
_configuration = config;
this.webHostEnvironemt = _webHostEnvironment;
}
[Route("request"), HttpPost]
public async Task<ActionResult> RequestReset([FromBody] string email)
{
email.Trim();
try
{
if (UserAuthExists(email))
{
string userid = _context.TesoUserDetails.AsQueryable().Where(e => e.Email == email).Select(t => t.UserGUID).FirstOrDefault();
string firstname = _context.TesoUserDetails.AsQueryable().Where(e => e.Email == email).Select(t => t.Firstname).FirstOrDefault();
ResetPasswords passwordsReset = new ResetPasswords();
passwordsReset.ResetCode = int.Parse(String.Format("{0:d6}", (DateTime.Now.Ticks / 10) % 100000));
passwordsReset.DateGenerated = DateTime.Now;
passwordsReset.UserGuid = userid;
passwordsReset.ResetGuid = email + String.Format("{0:d6}", (DateTime.Now.Ticks / 10) % 100000);
_context.ResetPasswords.Add(passwordsReset);
await _context.SaveChangesAsync();
activationCode(firstname, passwordsReset.ResetGuid, email, passwordsReset.ResetCode);
return Ok("sent");
}
else
{
return Ok(UserAccountType(email));
}
}
catch
{
return BadRequest();
}
}
[Route("reset"), HttpPost]
public async Task<ActionResult> ResetPassword(ResetClass reset)
{
try
{
if (!String.IsNullOrEmpty(reset.resetGuid))
{
string userid = await _context.ResetPasswords.AsQueryable().Where(id => id.ResetGuid == reset.resetGuid).Select(i => i.UserGuid).FirstOrDefaultAsync();
DateTime generated = await _context.ResetPasswords.AsQueryable().Where(d => d.ResetGuid == reset.resetGuid).Select(d => d.DateGenerated).FirstOrDefaultAsync();
TimeSpan diff1 = DateTime.Now.Subtract(generated);
if (diff1.Minutes < 30)
{
UserAuth userAuth = await _context.UserAuths.AsQueryable().Where(uid => uid.UserGUID == userid).FirstOrDefaultAsync();
userAuth.Password = passwordEncryption.Encrypt(reset.password);
_context.Entry(userAuth).State = EntityState.Modified;
await _context.SaveChangesAsync();
return Ok();
}
else
{
return BadRequest("Expired");
}
}
else
{
string userid = await _context.ResetPasswords.AsQueryable().Where(id => id.ResetCode == reset.resetcode).Select(i => i.UserGuid).FirstOrDefaultAsync();
DateTime generated = await _context.ResetPasswords.AsQueryable().Where(d => d.ResetCode == reset.resetcode && d.UserGuid == userid).Select(d => d.DateGenerated).FirstOrDefaultAsync();
TimeSpan diff1 = DateTime.Now.Subtract(generated);
if (diff1.Minutes < 30)
{
UserAuth userAuth = await _context.UserAuths.AsQueryable().Where(uid => uid.UserGUID == userid).FirstOrDefaultAsync();
userAuth.Password = passwordEncryption.Encrypt(reset.password);
_context.Entry(userAuth).State = EntityState.Modified;
await _context.SaveChangesAsync();
return Ok();
}
else
{
return BadRequest("Expired");
}
}
}
catch
{
return BadRequest();
}
}
private AlternateView GetEmbeddedImage(string firstname, string guid, int code)
{
string filePath = Path.Combine(this.webHostEnvironemt.ContentRootPath, "teso.png");
LinkedResource res = new LinkedResource(filePath, MediaTypeNames.Image.Jpeg);
res.ContentId = Guid.NewGuid().ToString();
string htmlBody = "<html>" +
@"<body style=""padding:20px;"">" +
@"<div style=""padding:20px;"">" +
@"<center><img src = 'cid:" + res.ContentId + @"' /> <br>" +
"<b><h1> TESO </h1><b>" +
"<hr/>" +
"</center>" +
@"<p style=""font-size:18px; color:#003445;""> Hello " + firstname + ",</p><br/>" +
@"<center> <h1 style=""font-size:24px; color:#003445;font-weight:bold;""> <b> We received a request to reset the password for your account.<b> </h1> <br/>" +
@"<center><p style=""font-size:18px; color:#003445;"">" +
"We received a request to reset the password for your account. Click the button below to reset your password <br/>" +
@"<a href='" + ServerLocation.dynamiclink1 + ServerLocation.location + "resetpassword/page?resetguid=" + guid + ServerLocation.dynamiclink2 + "'> <br/>" +
@"<button style=""height: 60px; color: white; font-size:18px; background-color:#fd0a35;font-weight:bold;padding:10px;cursor:pointer;"">Reset My Password</button></a> <br/>" +
$"Alternatively, you can enter this {code} code in your app. <br/>" +
"A password reset request can be made by anyone, and while it does not indicate that your account is in any danger of being accessed by someone else, we do recommend that you " +
"ensure that you are using a secure and unique password to protect your Teso account. We also suggest using a different password for every online account that you have." +
"If it wasn't you, someone must have mistakenly typed in your email. Then no other action is needed at this moment, the link expires 30 minutes after this mail was sent you.</p> <br/>" +
@"<h2 style=""font-size:18px; color:#003445;"">Regards, <br/>" +
"<b>TESO TEAM <b></h2>" +
"</center>" +
"</div>" +
"</body>" +
"</html>";
AlternateView alternateView = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);
alternateView.LinkedResources.Add(res);
return alternateView;
}
public string UserAccountType(string email)
{
string userid = _context.TesoUserDetails.AsQueryable().Where(e => e.Email == email).Select(t => t.UserGUID).FirstOrDefault();
string typeCode = _context.UserAuths.AsQueryable().Where(e => e.UserGUID == userid).Select(a => a.AccountType).FirstOrDefault();
return _context.AccountTypes.AsQueryable().Where(e => e.TypeCode == typeCode).Select(a => a.TypeName).FirstOrDefault();
}
private bool UserAuthExists(string email)
{
string userid = _context.TesoUserDetails.AsQueryable().Where(e => e.Email == email).Select(t => t.UserGUID).FirstOrDefault();
string account = _context.AccountTypes.AsQueryable().Where(at => at.TypeName == "email").Select(e => e.TypeCode).FirstOrDefault();
return _context.UserAuths.Any(e => e.UserGUID == userid && e.AccountType == account);
}
private int activationCode(string tesoUser, string verificationCode, string email, int code)
{
try
{
MailMessage mail = new MailMessage();
string client = "mail.privateemail.com";
string clientPort = "587";
string username = "support@tesoapp.com";
string password = "Konstantinovich96";
SmtpClient smtpClient = new SmtpClient(client);
mail.From = new MailAddress(username);
mail.To.Add(email);
mail.Subject = "Reset Account Password";
mail.AlternateViews.Add(GetEmbeddedImage(tesoUser, verificationCode, code));
mail.IsBodyHtml = true;
smtpClient.Port = int.Parse(clientPort);
smtpClient.Credentials = new System.Net.NetworkCredential(username, password);
smtpClient.EnableSsl = true;
//smtpClient.Timeout = 10000;
smtpClient.Send(mail);
return 1;
}
catch
{
return 0;
}
}
}
}