ClientFactory.cs 14 KB

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