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.

291 lines
14 KiB

3 months ago
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 Google.Apis.Auth.OAuth2;
using Google.Cloud.Firestore;
using Grpc.Auth;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Teso_API.Methods.Controllers;
using Teso_API.Models;
namespace Teso_API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UserAuthsController : ControllerBase
{
private readonly TESOContext _context;
private readonly IWebHostEnvironment webHostEnvironemt;
private FirestoreDb db;
public UserAuthsController(TESOContext context, IWebHostEnvironment _webHostEnvironment)
{
_context = context;
this.webHostEnvironemt = _webHostEnvironment;
db = new FirestoreDbBuilder
{
ProjectId = ServerLocation.credentials.project_id,
ChannelCredentials = GoogleCredential.FromJson(JsonConvert.SerializeObject(ServerLocation.credentials)).ToChannelCredentials(),
}.Build();
}
[HttpGet("{id}")]
public async Task<ActionResult<UserAuth>> GetUserAuth(string id)
{
var userAuth = await _context.UserAuths.FindAsync(id);
if (userAuth == null)
{
return NotFound();
}
return userAuth;
}
[HttpPost]
public async Task<ActionResult> PostUserAuth(Registrar userAuth)
{
string id = userAuth.user.Username + String.Format("{0:d9}", (DateTime.Now.Ticks / 10) % 10000000);
userAuth.authentication.Password = passwordEncryption.Encrypt(userAuth.authentication.Password);
userAuth.authentication.UserGUID = id;
userAuth.user.UserGUID = id;
userAuth.user.DateOfBirth = null;
ActivationCodes activation = new ActivationCodes();
activation.UserGuid = id;
activation.CodeGuid = Guid.NewGuid().ToString();
activation.DateGenerated = DateTime.Now;
activation.Code = int.Parse(String.Format("{0:d6}", (DateTime.Now.Ticks / 10) % 100000));
WriteBatch batch = db.StartBatch();
if (String.IsNullOrEmpty(userAuth.referral) || (!String.IsNullOrEmpty(userAuth.referral) && (_context.Referrals.AsQueryable().Where(r => r.Referrer == userAuth.referral &&
r.Datejoined.Value.Date == DateTime.Now.Date).Count()) >= 50))
{
UserFinance finance = new UserFinance();
finance.Gold = 0;
finance.Silver = 52;
finance.UserGUID = userAuth.user.UserGUID;
UserTransaction transaction = new UserTransaction();
transaction.RealCash = 0;
transaction.CoinType = await _context.CoinTypes.AsQueryable().Where(c => c.TypeName.ToLower().Contains("silver")).Select(s => s.TypeCode).AsNoTracking().FirstOrDefaultAsync();
transaction.Comments = "Welcome bonus";
transaction.CoinAmount = 52;
transaction.Timestamp = DateTime.Now;
transaction.TransactionID = String.Format("{0:d9}", (DateTime.Now.Ticks / 10) % 10000000) + userAuth.user.UserGUID;
transaction.UserGUID = userAuth.user.UserGUID;
transaction.TransactionType = await _context.TransactionTypes.AsQueryable().Where(c => c.TypeName.ToLower().Contains("silver credit")).Select(c => c.TypeCode).AsNoTracking().FirstOrDefaultAsync();
_context.UserTransactions.Add(transaction);
bool possible = await SilverBankOperations.WithdrawFromBank(52, _context);
if (!possible)
return StatusCode(500);
if (!String.IsNullOrEmpty(userAuth.referral))
{
_context.Referrals.Add(new Referral
{
Datejoined = DateTime.Now,
Referred = userAuth.user.UserGUID,
Referrer = userAuth.referral,
Rewarded = false,
});
}
_context.UserFinances.Add(finance);
DocumentReference docRef = db.Collection(ServerLocation.user_notifications).Document(userAuth.user.UserGUID).Collection(userAuth.user.UserGUID).Document();
Dictionary<string, object> user = new Dictionary<string, object>
{
{ "notificationType", "welcome" },
{ "timestamp", new DateTimeOffset(DateTimeOffset.UtcNow.DateTime).ToUnixTimeMilliseconds()},
{ "message", "Welcome to Teso App, as your welcome package you have been gifted 52 Silvers Coins for free. You may use them to acquire discount and freebie coupons!!!" },
{ "recipient", userAuth.user.UserGUID },
};
batch.Set(docRef, user);
}
else
{
List<UserFinance> finances = new List<UserFinance>{
new UserFinance
{
Gold = 0,
Silver = 52,
UserGUID = userAuth.user.UserGUID,
},
new UserFinance
{
Gold = 0,
Silver = 10,
UserGUID = userAuth.referral,
},
};
List<UserTransaction> transactions = new List<UserTransaction>() {
new UserTransaction
{
RealCash = 0,
CoinType = await _context.CoinTypes.AsQueryable().Where(c => c.TypeName.ToLower().Contains("silver")).Select(s => s.TypeCode).AsNoTracking().FirstOrDefaultAsync(),
Comments = "Welcome bonus",
CoinAmount = 52,
Timestamp = DateTime.Now,
TransactionID = String.Format("{0:d9}", (DateTime.Now.Ticks / 10) % 10000000) + userAuth.user.UserGUID,
UserGUID = userAuth.user.UserGUID,
TransactionType = await _context.TransactionTypes.AsQueryable().Where(c => c.TypeName.ToLower().Contains("silver credit")).Select(c => c.TypeCode).AsNoTracking().FirstOrDefaultAsync(),
},
new UserTransaction
{
RealCash = 0,
CoinType = await _context.CoinTypes.AsQueryable().Where(c => c.TypeName.ToLower().Contains("silver")).Select(s => s.TypeCode).AsNoTracking().FirstOrDefaultAsync(),
Comments = "Referral bonus",
CoinAmount = 10,
Timestamp = DateTime.Now,
TransactionID = String.Format("{0:d9}", (DateTime.Now.Ticks / 10) % 10000000) + userAuth.user.UserGUID,
UserGUID = userAuth.referral,
TransactionType = await _context.TransactionTypes.AsQueryable().Where(c => c.TypeName.ToLower().Contains("silver credit")).Select(c => c.TypeCode).AsNoTracking().FirstOrDefaultAsync(),
},
};
bool possible = await SilverBankOperations.WithdrawFromBank(62, _context);
if (!possible)
return StatusCode(500);
DocumentReference docRef = db.Collection(ServerLocation.user_notifications).Document(userAuth.user.UserGUID).Collection(userAuth.user.UserGUID).Document();
Dictionary<string, object> user = new Dictionary<string, object>
{
{ "notificationType", "welcome" },
{ "timestamp", new DateTimeOffset(DateTimeOffset.UtcNow.DateTime).ToUnixTimeMilliseconds()},
{ "message", "Welcome to Teso App, as your welcome package we have gifted 52 Silvers Coins for free. You may use them to acquire discount and freebie coupons!!!" },
{ "recipient", userAuth.user.UserGUID },
};
batch.Set(docRef, user);
DocumentReference docRef2 = db.Collection(ServerLocation.user_notifications).Document(userAuth.referral).Collection(userAuth.referral).Document();
Dictionary<string, object> user2 = new Dictionary<string, object>
{
{ "notificationType", "referral" },
{ "timestamp", new DateTimeOffset(DateTimeOffset.UtcNow.DateTime).ToUnixTimeMilliseconds()},
{ "message", "You just earned 10 Silver coins as your referral link was used!!!" },
{ "recipient", userAuth.user.UserGUID },
};
batch.Set(docRef2, user2);
_context.UserFinances.AddRange(finances);
_context.UserTransactions.AddRange(transactions);
_context.Referrals.Add(new Referral
{
Datejoined = DateTime.Now,
Referred = userAuth.user.UserGUID,
Referrer = userAuth.referral,
Rewarded = true,
});
}
_context.UserAuths.Add(userAuth.authentication);
_context.TesoUserDetails.Add(userAuth.user);
_context.ActivationCodes.Add(activation);
try
{
int result = activationCode(userAuth.user, activation.Code, activation.CodeGuid);
if (result == 1)
{
await _context.SaveChangesAsync();
await batch.CommitAsync();
}
else
{
return BadRequest();
}
}
catch (DbUpdateException)
{
if (UserAuthExists(userAuth.authentication.Username))
{
return Conflict();
}
else
{
throw;
}
}
return Ok();
}
private bool UserAuthExists(string id)
{
return _context.UserAuths.Any(e => e.Username == id);
}
private AlternateView GetEmbeddedImage(int code, string firstname, string guid)
{
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:50px;"">" +
@"<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> Your verification code is <br/> " + code + "<b> </h1> <br/>" +
@"<p style=""font-size:18px; color:#003445;"">" +
"Enter this code in the TESO app to activate your account. <br/>" +
"You could also click the button below to confirm your email address: <br/>" +
@"<a href='" + ServerLocation.location + "api/activationhandler/" + guid + "'>" +
@"<button style=""height: 60px; color: white; font-size:18px; background-color:#fd0a35;font-weight:bold;padding:10px;cursor:pointer;"">Activate Account</button></a> <br/>" +
"If it wasn't you, someone must have mistakenly typed in your email. Keep this code to yourself; no other action is needed at this moment </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;
}
private int activationCode(TesoUserDetail tesoUser, int Code, string verificationCode)
{
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(tesoUser.Email);
mail.Subject = "Verification Code";
mail.AlternateViews.Add(GetEmbeddedImage(Code, tesoUser.Username, verificationCode));
mail.IsBodyHtml = true;
smtpClient.Port = int.Parse(clientPort);
smtpClient.Credentials = new System.Net.NetworkCredential(username, password);
smtpClient.EnableSsl = true;
smtpClient.Timeout = 1000000;
smtpClient.Send(mail);
return 1;
}
catch
{
return 0;
}
}
}
}