Code
·
52 lines
·
1661 bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52using LiteDB;
using MailSharp.MailClient.Models;
namespace MailSharp.MailClient.Services;
public interface IAccountStore
{
Account Add(Account account, string plainPassword);
Account? Get(int id);
List<Account> GetAll();
void Remove(int id);
void Update(Account account);
string GetPlainPassword(Account account);
}
// Holds a single long-lived LiteDatabase connection for the app's lifetime (registered as a
// singleton). LiteDatabase is thread-safe for concurrent operations; opening/closing a new
// connection per call instead would race on the OS file lock under concurrent requests.
public class LiteDbAccountStore : IAccountStore, IDisposable
{
private readonly LiteDatabase _db;
private readonly IPasswordProtector _protector;
public LiteDbAccountStore(IWebHostEnvironment env, IPasswordProtector protector)
{
_protector = protector;
var dir = Path.Combine(env.ContentRootPath, "App_Data");
Directory.CreateDirectory(dir);
_db = new LiteDatabase(Path.Combine(dir, "accounts.db"));
}
private ILiteCollection<Account> Accounts => _db.GetCollection<Account>("accounts");
public Account Add(Account account, string plainPassword)
{
account.ProtectedPassword = _protector.Protect(plainPassword);
Accounts.Insert(account);
return account;
}
public Account? Get(int id) => Accounts.FindById(id);
public List<Account> GetAll() => [.. Accounts.FindAll()];
public void Remove(int id) => Accounts.Delete(id);
public void Update(Account account) => Accounts.Update(account);
public string GetPlainPassword(Account account) => _protector.Unprotect(account.ProtectedPassword);
public void Dispose() => _db.Dispose();
}