ClientFactory.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using InABox.Core;
  6. using InABox.Core.Notifications;
  7. using InABox.Mail;
  8. namespace InABox.Clients
  9. {
  10. public class BypassSession : IDisposable
  11. {
  12. public BypassSession()
  13. {
  14. ClientFactory.SetBypass();
  15. }
  16. public void Dispose()
  17. {
  18. ClientFactory.UnsetBypass();
  19. }
  20. }
  21. public static class ClientFactory
  22. {
  23. private static Type? _type;
  24. private static object[] _params;
  25. private static IEnumerable<string>? SupportedTypes;
  26. private static Type ClientType => _type ?? throw new Exception("Client type has not been set!");
  27. public static Dictionary<EmailType, Type> MailerTypes = new Dictionary<EmailType, Type>();
  28. //public static Type _mailer;
  29. //private static User CurrentUser = null;
  30. public static Guid UserGuid { get; private set; }
  31. public static string UserID { get; private set; }
  32. public static Guid UserSecurityID { get; private set; }
  33. public static Guid SessionID { get; set; }
  34. public static string Platform { get; private set; }
  35. public static string Version { get; private set; }
  36. public static string? Recipient2FA { get; private set; }
  37. public static DateTime PasswordExpiration { get; private set; }
  38. public static int PINLength { get; } = 4;
  39. public static Notifications Notifications { get; set; } = new Notifications();
  40. public delegate void RequestErrorHandler(RequestException e);
  41. public static event RequestErrorHandler? OnRequestError;
  42. public static void RaiseRequestError(RequestException e)
  43. {
  44. OnRequestError?.Invoke(e);
  45. }
  46. private static bool IsSupported(Type t)
  47. {
  48. return true;
  49. //if (SupportedTypes == null)
  50. //{
  51. // try
  52. // {
  53. // SupportedTypes = new Client<User>().SupportedTypes();
  54. // }
  55. // catch (Exception e)
  56. // {
  57. // SupportedTypes = new String[] { };
  58. // }
  59. //}
  60. //return SupportedTypes.Contains(t.EntityName().Replace(".", "_"));
  61. }
  62. public static bool IsSupported<T>() where T : Entity, new()
  63. {
  64. return IsSupported(typeof(T));
  65. }
  66. public static bool IsSupported<T1, T2>() where T1 : Entity, new() where T2 : Entity, new()
  67. {
  68. return IsSupported<T1>() && IsSupported<T2>();
  69. }
  70. public static bool IsSupported<T1, T2, T3>() where T1 : Entity, new() where T2 : Entity, new() where T3 : Entity, new()
  71. {
  72. return IsSupported<T1>() && IsSupported<T2>() && IsSupported<T3>();
  73. }
  74. public static bool IsSupported<T1, T2, T3, T4>() where T1 : Entity, new()
  75. where T2 : Entity, new()
  76. where T3 : Entity, new()
  77. where T4 : Entity, new()
  78. {
  79. return IsSupported<T1>() && IsSupported<T2>() && IsSupported<T3>() && IsSupported<T4>();
  80. }
  81. public static bool IsSupported<T1, T2, T3, T4, T5>() where T1 : Entity, new()
  82. where T2 : Entity, new()
  83. where T3 : Entity, new()
  84. where T4 : Entity, new()
  85. where T5 : Entity, new()
  86. {
  87. return IsSupported<T1>() && IsSupported<T2>() && IsSupported<T3>() && IsSupported<T4>() && IsSupported<T4>();
  88. }
  89. public static bool IsSupported(params Type[] types)
  90. {
  91. return true;
  92. //if (SupportedTypes == null)
  93. // SupportedTypes = new Client<User>().SupportedTypes();
  94. //bool result = true;
  95. //foreach (var type in types)
  96. // result = result && SupportedTypes.Contains(type.EntityName().Replace(".", "_"));
  97. //return result;
  98. }
  99. public static void SetClientType(Type type, string platform, string version, params object[] parameters)
  100. {
  101. _type = type;
  102. Platform = platform == null ? Platform : platform;
  103. Version = version == null ? Version : version;
  104. _params = parameters == null ? _params : parameters;
  105. SupportedTypes = parameters == null ? SupportedTypes : null;
  106. }
  107. public static void ClearClientType()
  108. {
  109. _type = null;
  110. }
  111. public static Type? GetClientType()
  112. {
  113. return _type;
  114. }
  115. // override the need to provide credentials when configuring the database
  116. public static void SetBypass()
  117. {
  118. UserGuid = CoreUtils.FullGuid;
  119. UserID = "";
  120. Request.BeforeRequest = request =>
  121. {
  122. if(request is ValidateRequest validate)
  123. {
  124. var ticks = DateTime.Now.ToUniversalTime().Ticks.ToString();
  125. validate.UserID = Encryption.Encrypt(ticks, "wCq9rryEJEuHIifYrxRjxg", true);
  126. validate.Password = Encryption.Encrypt(ticks, "7mhvLnqMwkCAzN+zNGlyyg", true);
  127. }
  128. };
  129. var result = Validate("", "");
  130. if (result != ValidationResult.VALID)
  131. {
  132. Logger.Send(LogType.Error, "", "Bypass login failed");
  133. }
  134. //Load up the data model, including Custom Properties
  135. //var props = CreateClient<CustomProperty>().Load();
  136. //DatabaseSchema.Load(props);
  137. }
  138. public static void UnsetBypass()
  139. {
  140. Request.BeforeRequest = null;
  141. UserGuid = Guid.Empty;
  142. }
  143. public static ValidationResult Validate(string userid, string password, Guid session = default)
  144. {
  145. InvalidateUser();
  146. var result = Client.Validate(userid, password, session);
  147. if (result.Status != ValidationResult.INVALID)
  148. {
  149. UserGuid = result.UserGuid;
  150. UserID = result.UserID;
  151. UserSecurityID = result.SecurityID;
  152. Recipient2FA = result.Recipient2FA;
  153. SessionID = result.SessionID;
  154. PasswordExpiration = result.PasswordExpiration;
  155. if(result.Status == ValidationResult.VALID)
  156. {
  157. OnValidLogin();
  158. }
  159. return result.Status;
  160. }
  161. return result.Status;
  162. }
  163. public static ValidationResult Validate(string pin, Guid session = default)
  164. {
  165. InvalidateUser();
  166. var result = Client.Validate(pin, session);
  167. if (result.Status != ValidationResult.INVALID)
  168. {
  169. UserGuid = result.UserGuid;
  170. UserID = result.UserID;
  171. UserSecurityID = result.SecurityID;
  172. Recipient2FA = result.Recipient2FA;
  173. SessionID = result.SessionID;
  174. PasswordExpiration = result.PasswordExpiration;
  175. if (result.Status == ValidationResult.VALID)
  176. {
  177. OnValidLogin();
  178. }
  179. return result.Status;
  180. }
  181. return result.Status;
  182. }
  183. public static ValidationResult Validate(Guid session)
  184. {
  185. InvalidateUser();
  186. var result = Client.Validate(session);
  187. if (result.Status != ValidationResult.INVALID)
  188. {
  189. UserGuid = result.UserGuid;
  190. UserID = result.UserID;
  191. UserSecurityID = result.SecurityID;
  192. Recipient2FA = result.Recipient2FA;
  193. SessionID = result.SessionID;
  194. PasswordExpiration = result.PasswordExpiration;
  195. if (result.Status == ValidationResult.VALID)
  196. {
  197. OnValidLogin();
  198. }
  199. return result.Status;
  200. }
  201. return result.Status;
  202. }
  203. public static bool ValidateUser(string userid, string password)
  204. {
  205. InvalidateUser();
  206. var result = Client.Validate(userid, password);
  207. if (result.Status == ValidationResult.VALID)
  208. {
  209. UserGuid = result.UserGuid;
  210. UserID = result.UserID;
  211. UserSecurityID = result.SecurityID;
  212. Recipient2FA = result.Recipient2FA;
  213. SessionID = result.SessionID;
  214. PasswordExpiration = result.PasswordExpiration;
  215. if (result.Status == ValidationResult.VALID)
  216. {
  217. OnValidLogin();
  218. }
  219. return true;
  220. }
  221. return false;
  222. }
  223. public static bool ValidatePIN(string pin)
  224. {
  225. InvalidateUser();
  226. var result = Client.Validate(pin);
  227. if (result.Status == ValidationResult.VALID)
  228. {
  229. UserGuid = result.UserGuid;
  230. UserID = result.UserID;
  231. UserSecurityID = result.SecurityID;
  232. Recipient2FA = result.Recipient2FA;
  233. SessionID = result.SessionID;
  234. PasswordExpiration = result.PasswordExpiration;
  235. if (result.Status == ValidationResult.VALID)
  236. {
  237. OnValidLogin();
  238. }
  239. return true;
  240. }
  241. return false;
  242. }
  243. public static bool Check2FA(string code, Guid? session = null)
  244. {
  245. var result = Client.Check2FA(code, session);
  246. if (result)
  247. {
  248. OnValidLogin();
  249. }
  250. return result;
  251. }
  252. public static void OnValidLogin()
  253. {
  254. //Load up the data model, including Custom Properties
  255. var props = new Client<CustomProperty>().Load();
  256. DatabaseSchema.Load(props);
  257. }
  258. public static void InvalidateUser()
  259. {
  260. //CurrentUser = null;
  261. UserGuid = Guid.Empty;
  262. UserID = "";
  263. UserSecurityID = Guid.Empty;
  264. SessionID = Guid.Empty;
  265. Security.Reset();
  266. }
  267. public static event LogEvent? OnLog;
  268. public static IClient<TEntity> CreateClient<TEntity>() where TEntity : Entity, new()
  269. {
  270. var type = ClientType.MakeGenericType(typeof(TEntity));
  271. var client = (IClient<TEntity>)Activator.CreateInstance(type, _params);
  272. //client.UserID = UserID;
  273. //client.Password = Password;
  274. //client.Platform = Platform;
  275. //client.Version = Version;
  276. client.OnLog += OnLog;
  277. return client;
  278. }
  279. public static IClient CreateClient(Type t)
  280. {
  281. var type = ClientType.MakeGenericType(t);
  282. var client = (IClient)Activator.CreateInstance(type, _params);
  283. //client.UserID = UserID;
  284. //client.Password = Password;
  285. //client.Platform = Platform;
  286. //client.Version = Version;
  287. client.OnLog += OnLog;
  288. return client;
  289. }
  290. public static CoreTable[] MultiQuery(params IQueryDef[] queries)
  291. {
  292. var tasks = new Dictionary<object, Task<CoreTable>>();
  293. for (var i = 0; i < queries.Length; i++)
  294. {
  295. var def = queries[i];
  296. var task = Task.Run(() => { return CreateClient(def.Type).Query(def.Filter, def.Columns, def.SortOrder); });
  297. tasks[i] = task;
  298. }
  299. Task.WaitAll(tasks.Values.ToArray());
  300. var results = new List<CoreTable>();
  301. for (var i = 0; i < queries.Length; i++)
  302. results.Add(tasks[i].Result);
  303. return results.ToArray();
  304. }
  305. public static void MultiQuery(IQueryDef[] queries, Action<CoreTable[]> OnResults)
  306. {
  307. Task.Run(() =>
  308. {
  309. var tasks = new Dictionary<object, Task<CoreTable>>();
  310. for (var i = 0; i < queries.Length; i++)
  311. {
  312. var def = queries[i];
  313. var task = Task.Run(() => { return CreateClient(def.Type).Query(def.Filter, def.Columns, def.SortOrder); });
  314. tasks[i] = task;
  315. }
  316. Task.WaitAll(tasks.Values.ToArray());
  317. var results = new List<CoreTable>();
  318. for (var i = 0; i < queries.Length; i++)
  319. results.Add(tasks[i].Result);
  320. OnResults.Invoke(results.ToArray());
  321. });
  322. }
  323. public static void RegisterMailer(EmailType type, Type mailer)
  324. {
  325. MailerTypes[type] = mailer;
  326. }
  327. public static ICoreMailer? CreateMailer()
  328. {
  329. var row = new Client<User>().Query(
  330. new Filter<User>(x => x.ID).IsEqualTo(UserGuid),
  331. new Columns<User>(
  332. x => x.EmailType,
  333. x => x.EmailHost,
  334. x => x.EmailPort,
  335. x => x.EmailDomain,
  336. x => x.EmailUserID,
  337. x => x.EmailPassword,
  338. x => x.SMTPHost,
  339. x => x.SMPTPort,
  340. x => x.SMTPUserName,
  341. x => x.SMTPPassword
  342. )
  343. ).Rows.FirstOrDefault();
  344. if (row == null)
  345. return null;
  346. var type = row.Get<User, EmailType>(x => x.EmailType);
  347. if (type == EmailType.None)
  348. return null;
  349. var result = (Activator.CreateInstance(MailerTypes[type]) as ICoreMailer)!;
  350. result.MailboxHost = row.Get<User, string>(x => x.EmailHost);
  351. result.MailboxPort = row.Get<User, int>(x => x.EmailPort);
  352. result.MailboxDomain = row.Get<User, string>(x => x.EmailDomain);
  353. result.MailboxUserName = row.Get<User, string>(x => x.EmailUserID);
  354. result.MailboxPassword = row.Get<User, string>(x => x.EmailPassword);
  355. result.SMTPHost = row.Get<User, string>(x => x.SMTPHost);
  356. result.SMTPPort = row.Get<User, int>(x => x.SMPTPort);
  357. result.SMTPUserName = row.Get<User, string>(x => x.SMTPUserName);
  358. result.SMTPPassword = row.Get<User, string>(x => x.SMTPPassword);
  359. return result;
  360. }
  361. }
  362. }