2023-02-16 12:57:06 +00:00
|
|
|
using System.Net.Mail;
|
2023-02-16 14:08:50 +00:00
|
|
|
using System.Text;
|
2023-02-16 12:57:06 +00:00
|
|
|
using Backend.Model;
|
|
|
|
using Backend.Utils;
|
|
|
|
using SQLite;
|
|
|
|
#pragma warning disable CS0472
|
|
|
|
#pragma warning disable CS8602
|
|
|
|
|
|
|
|
namespace Backend.Database;
|
|
|
|
|
|
|
|
public partial class Db
|
|
|
|
{
|
|
|
|
private TableQuery<User> Users => _Db.Table<User>();
|
|
|
|
|
|
|
|
public Int32 NbUsers => Users.Count();
|
|
|
|
|
|
|
|
public User? GetUserById(Int64 id)
|
|
|
|
{
|
|
|
|
return Users.FirstOrDefault(u => u.Id == id);
|
|
|
|
}
|
|
|
|
|
|
|
|
public Boolean IsParentOfChild(User parent, User child)
|
|
|
|
{
|
|
|
|
var parentPointer = child.ParentId;
|
|
|
|
|
|
|
|
if (parent.Id == child.Id)
|
|
|
|
return true;
|
|
|
|
|
|
|
|
while (parentPointer != null && parentPointer != parent.Id)
|
|
|
|
{
|
|
|
|
parentPointer = GetUserById(parentPointer).ParentId;
|
|
|
|
}
|
|
|
|
|
|
|
|
return parentPointer == parent.Id;
|
|
|
|
}
|
|
|
|
|
|
|
|
public User? GetUserByEmail(String email) => Users.FirstOrDefault(u => u.Email == email);
|
|
|
|
|
|
|
|
public Result CreateUser(User user)
|
|
|
|
{
|
|
|
|
if (GetUserByEmail(user.Email) is not null)
|
|
|
|
return Result.Error("User with that email already exists");
|
2023-02-16 14:08:50 +00:00
|
|
|
|
|
|
|
//Salting and Hashing password
|
|
|
|
var salt = Crypto.GenerateSalt();
|
|
|
|
var hashedPassword = Crypto.ComputeHash(Encoding.UTF8.GetBytes(user.Password),
|
|
|
|
Encoding.UTF8.GetBytes(salt + "innovEnergy"));
|
|
|
|
|
|
|
|
user.Salt = salt;
|
|
|
|
user.Password = hashedPassword;
|
2023-02-16 12:57:06 +00:00
|
|
|
|
2023-02-16 14:08:50 +00:00
|
|
|
return Create(user);
|
2023-02-16 12:57:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public Result UpdateUser(User user)
|
|
|
|
{
|
|
|
|
var oldUser = GetUserById(user.Id);
|
|
|
|
if (oldUser == null)
|
|
|
|
return Result.Error("User doesn't exist");
|
|
|
|
|
|
|
|
//Checking for unchangeable things
|
|
|
|
user.Id = oldUser.Id;
|
|
|
|
user.ParentId = oldUser.ParentId;
|
|
|
|
user.Email = oldUser.Email;
|
|
|
|
|
|
|
|
return Update(user);
|
|
|
|
}
|
|
|
|
|
|
|
|
public Result DeleteUser(User user)
|
|
|
|
{
|
|
|
|
User2Folder
|
|
|
|
.Where(u => u.UserId == user.Id)
|
|
|
|
.Delete();
|
|
|
|
User2Installation
|
|
|
|
.Where(u => u.UserId == user.Id)
|
|
|
|
.Delete();
|
|
|
|
|
2023-02-16 14:08:50 +00:00
|
|
|
//Todo check for orphaned Installations/Folders
|
2023-02-16 12:57:06 +00:00
|
|
|
|
|
|
|
return Delete(user);
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// TODO
|
|
|
|
private static Boolean IsValidEmail(String email)
|
|
|
|
{
|
|
|
|
try
|
|
|
|
{
|
|
|
|
var emailAddress = new MailAddress(email);
|
|
|
|
}
|
|
|
|
catch
|
|
|
|
{
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|