The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
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.

ManageController.cs 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using IdentityServer4;
  7. using IdentityServer4.EntityFramework.DbContexts;
  8. using IdentityServer4.EntityFramework.Entities;
  9. using IdentityServer4.EntityFramework.Mappers;
  10. using IdentityServer4.Models;
  11. using IdentityServer4.Stores;
  12. using Microsoft.AspNetCore.Authorization;
  13. using Microsoft.AspNetCore.Identity;
  14. using Microsoft.AspNetCore.Mvc;
  15. using Microsoft.EntityFrameworkCore;
  16. using Microsoft.EntityFrameworkCore.Internal;
  17. using Microsoft.Extensions.Caching.Memory;
  18. using Microsoft.Extensions.Logging;
  19. using Newtonsoft.Json.Linq;
  20. using Teknik.Configuration;
  21. using Teknik.IdentityServer.Models;
  22. using Teknik.IdentityServer.Models.Manage;
  23. using Teknik.IdentityServer.Services;
  24. using Teknik.Logging;
  25. using Teknik.Utilities;
  26. namespace Teknik.IdentityServer.Controllers
  27. {
  28. [Authorize(Policy = "Internal", AuthenticationSchemes = "Bearer")]
  29. [Route("[controller]/[action]")]
  30. [ApiController]
  31. public class ManageController : DefaultController
  32. {
  33. private const string _UserInfoCacheKey = "UserInfo";
  34. private readonly UserManager<ApplicationUser> _userManager;
  35. private readonly SignInManager<ApplicationUser> _signInManager;
  36. private readonly IMemoryCache _cache;
  37. public ManageController(
  38. ILogger<Logger> logger,
  39. Config config,
  40. UserManager<ApplicationUser> userManager,
  41. SignInManager<ApplicationUser> signInManager,
  42. IMemoryCache cache) : base(logger, config)
  43. {
  44. _userManager = userManager;
  45. _signInManager = signInManager;
  46. _cache = cache;
  47. }
  48. [HttpPost]
  49. public async Task<IActionResult> CreateUser(NewUserModel model)
  50. {
  51. if (string.IsNullOrEmpty(model.Username))
  52. return new JsonResult(new { success = false, message = "Username is required" });
  53. if (string.IsNullOrEmpty(model.Password))
  54. return new JsonResult(new { success = false, message = "Password is required" });
  55. var identityUser = new ApplicationUser(model.Username)
  56. {
  57. Id = Guid.NewGuid().ToString(),
  58. UserName = model.Username,
  59. AccountStatus = model.AccountStatus,
  60. AccountType = model.AccountType,
  61. Email = model.RecoveryEmail,
  62. EmailConfirmed = model.RecoveryVerified,
  63. PGPPublicKey = model.PGPPublicKey
  64. };
  65. var result = await _userManager.CreateAsync(identityUser, model.Password);
  66. if (result.Succeeded)
  67. {
  68. return new JsonResult(new { success = true });
  69. }
  70. return new JsonResult(new { success = false, message = "Unable to create user.", identityErrors = result.Errors });
  71. }
  72. [HttpPost]
  73. public async Task<IActionResult> DeleteUser(DeleteUserModel model, [FromServices] ConfigurationDbContext configContext)
  74. {
  75. if (string.IsNullOrEmpty(model.Username))
  76. return new JsonResult(new { success = false, message = "Username is required" });
  77. var foundUser = await _userManager.FindByNameAsync(model.Username);
  78. if (foundUser != null)
  79. {
  80. // Find this user's clients
  81. var foundClients = configContext.Clients.Where(c =>
  82. c.Properties.Exists(p =>
  83. p.Key == "username" &&
  84. p.Value.ToLower() == model.Username.ToLower())
  85. ).ToList();
  86. if (foundClients != null)
  87. {
  88. configContext.Clients.RemoveRange(foundClients);
  89. configContext.SaveChanges();
  90. }
  91. var result = await _userManager.DeleteAsync(foundUser);
  92. if (result.Succeeded)
  93. {
  94. RemoveCachedUser(model.Username);
  95. return new JsonResult(new { success = true });
  96. }
  97. else
  98. return new JsonResult(new { success = false, message = "Unable to delete user.", identityErrors = result.Errors });
  99. }
  100. return new JsonResult(new { success = false, message = "User does not exist." });
  101. }
  102. [HttpGet]
  103. public async Task<IActionResult> UserExists(string username)
  104. {
  105. if (string.IsNullOrEmpty(username))
  106. return new JsonResult(new { success = false, message = "Username is required" });
  107. var foundUser = await _userManager.FindByNameAsync(username);
  108. return new JsonResult(new { success = true, data = foundUser != null });
  109. }
  110. [HttpGet]
  111. public async Task<IActionResult> GetUserInfo(string username)
  112. {
  113. if (string.IsNullOrEmpty(username))
  114. return new JsonResult(new { success = false, message = "Username is required" });
  115. var foundUser = await GetCachedUser(username);
  116. if (foundUser != null)
  117. {
  118. return new JsonResult(new { success = true, data = foundUser.ToJson() });
  119. }
  120. return new JsonResult(new { success = false, message = "User does not exist." });
  121. }
  122. [HttpPost]
  123. public async Task<IActionResult> CheckPassword(CheckPasswordModel model)
  124. {
  125. if (string.IsNullOrEmpty(model.Username))
  126. return new JsonResult(new { success = false, message = "Username is required" });
  127. if (string.IsNullOrEmpty(model.Password))
  128. return new JsonResult(new { success = false, message = "Password is required" });
  129. var foundUser = await _userManager.FindByNameAsync(model.Username);
  130. if (foundUser != null)
  131. {
  132. bool valid = await _userManager.CheckPasswordAsync(foundUser, model.Password);
  133. return new JsonResult(new { success = true, data = valid });
  134. }
  135. return new JsonResult(new { success = false, message = "User does not exist." });
  136. }
  137. [HttpPost]
  138. public async Task<IActionResult> GeneratePasswordResetToken(GeneratePasswordResetTokenModel model)
  139. {
  140. if (string.IsNullOrEmpty(model.Username))
  141. return new JsonResult(new { success = false, message = "Username is required" });
  142. var foundUser = await _userManager.FindByNameAsync(model.Username);
  143. if (foundUser != null)
  144. {
  145. string token = await _userManager.GeneratePasswordResetTokenAsync(foundUser);
  146. return new JsonResult(new { success = true, data = token });
  147. }
  148. return new JsonResult(new { success = false, message = "User does not exist." });
  149. }
  150. [HttpPost]
  151. public async Task<IActionResult> ResetPassword(ResetPasswordModel model)
  152. {
  153. if (string.IsNullOrEmpty(model.Username))
  154. return new JsonResult(new { success = false, message = "Username is required" });
  155. if (string.IsNullOrEmpty(model.Token))
  156. return new JsonResult(new { success = false, message = "Token is required" });
  157. if (string.IsNullOrEmpty(model.Password))
  158. return new JsonResult(new { success = false, message = "Password is required" });
  159. var foundUser = await _userManager.FindByNameAsync(model.Username);
  160. if (foundUser != null)
  161. {
  162. var result = await _userManager.ResetPasswordAsync(foundUser, model.Token, model.Password);
  163. if (result.Succeeded)
  164. return new JsonResult(new { success = true });
  165. else
  166. return new JsonResult(new { success = false, message = "Unable to reset password.", identityErrors = result.Errors });
  167. }
  168. return new JsonResult(new { success = false, message = "User does not exist." });
  169. }
  170. [HttpPost]
  171. public async Task<IActionResult> UpdatePassword(UpdatePasswordModel model)
  172. {
  173. if (string.IsNullOrEmpty(model.Username))
  174. return new JsonResult(new { success = false, message = "Username is required" });
  175. if (string.IsNullOrEmpty(model.CurrentPassword))
  176. return new JsonResult(new { success = false, message = "Current Password is required" });
  177. if (string.IsNullOrEmpty(model.NewPassword))
  178. return new JsonResult(new { success = false, message = "New Password is required" });
  179. var foundUser = await _userManager.FindByNameAsync(model.Username);
  180. if (foundUser != null)
  181. {
  182. var result = await _userManager.ChangePasswordAsync(foundUser, model.CurrentPassword, model.NewPassword);
  183. if (result.Succeeded)
  184. return new JsonResult(new { success = true });
  185. else
  186. return new JsonResult(new { success = false, message = "Unable to update password.", identityErrors = result.Errors });
  187. }
  188. return new JsonResult(new { success = false, message = "User does not exist." });
  189. }
  190. [HttpPost]
  191. public async Task<IActionResult> UpdateEmail(UpdateEmailModel model)
  192. {
  193. if (string.IsNullOrEmpty(model.Username))
  194. return new JsonResult(new { success = false, message = "Username is required" });
  195. var foundUser = await _userManager.FindByNameAsync(model.Username);
  196. if (foundUser != null)
  197. {
  198. var result = await _userManager.SetEmailAsync(foundUser, model.Email);
  199. if (result.Succeeded)
  200. {
  201. // Remove the UserInfo Cache
  202. RemoveCachedUser(model.Username);
  203. var token = await _userManager.GenerateEmailConfirmationTokenAsync(foundUser);
  204. return new JsonResult(new { success = true, data = token });
  205. }
  206. else
  207. return new JsonResult(new { success = false, message = "Unable to update email address.", identityErrors = result.Errors });
  208. }
  209. return new JsonResult(new { success = false, message = "User does not exist." });
  210. }
  211. [HttpPost]
  212. public async Task<IActionResult> VerifyEmail(VerifyEmailModel model)
  213. {
  214. if (string.IsNullOrEmpty(model.Username))
  215. return new JsonResult(new { success = false, message = "Username is required" });
  216. if (string.IsNullOrEmpty(model.Token))
  217. return new JsonResult(new { success = false, message = "Token is required" });
  218. var foundUser = await _userManager.FindByNameAsync(model.Username);
  219. if (foundUser != null)
  220. {
  221. // Remove the UserInfo Cache
  222. RemoveCachedUser(model.Username);
  223. var result = await _userManager.ConfirmEmailAsync(foundUser, model.Token);
  224. if (result.Succeeded)
  225. return new JsonResult(new { success = true });
  226. else
  227. return new JsonResult(new { success = false, message = "Unable to verify email address.", identityErrors = result.Errors });
  228. }
  229. return new JsonResult(new { success = false, message = "User does not exist." });
  230. }
  231. [HttpPost]
  232. public async Task<IActionResult> UpdateAccountStatus(UpdateAccountStatusModel model)
  233. {
  234. if (string.IsNullOrEmpty(model.Username))
  235. return new JsonResult(new { success = false, message = "Username is required" });
  236. var foundUser = await _userManager.FindByNameAsync(model.Username);
  237. if (foundUser != null)
  238. {
  239. foundUser.AccountStatus = model.AccountStatus;
  240. var result = await _userManager.UpdateAsync(foundUser);
  241. if (result.Succeeded)
  242. {
  243. // Remove the UserInfo Cache
  244. RemoveCachedUser(model.Username);
  245. return new JsonResult(new { success = true });
  246. }
  247. else
  248. return new JsonResult(new { success = false, message = "Unable to update account status.", identityErrors = result.Errors });
  249. }
  250. return new JsonResult(new { success = false, message = "User does not exist." });
  251. }
  252. [HttpPost]
  253. public async Task<IActionResult> UpdateAccountType(UpdateAccountTypeModel model)
  254. {
  255. if (string.IsNullOrEmpty(model.Username))
  256. return new JsonResult(new { success = false, message = "Username is required" });
  257. var foundUser = await _userManager.FindByNameAsync(model.Username);
  258. if (foundUser != null)
  259. {
  260. foundUser.AccountType = model.AccountType;
  261. var result = await _userManager.UpdateAsync(foundUser);
  262. if (result.Succeeded)
  263. {
  264. // Remove the UserInfo Cache
  265. RemoveCachedUser(model.Username);
  266. return new JsonResult(new { success = true });
  267. }
  268. else
  269. return new JsonResult(new { success = false, message = "Unable to update account type.", identityErrors = result.Errors });
  270. }
  271. return new JsonResult(new { success = false, message = "User does not exist." });
  272. }
  273. [HttpPost]
  274. public async Task<IActionResult> UpdatePGPPublicKey(UpdatePGPPublicKeyModel model)
  275. {
  276. if (string.IsNullOrEmpty(model.Username))
  277. return new JsonResult(new { success = false, message = "Username is required" });
  278. var foundUser = await _userManager.FindByNameAsync(model.Username);
  279. if (foundUser != null)
  280. {
  281. foundUser.PGPPublicKey = model.PGPPublicKey;
  282. var result = await _userManager.UpdateAsync(foundUser);
  283. if (result.Succeeded)
  284. {
  285. // Remove the UserInfo Cache
  286. RemoveCachedUser(model.Username);
  287. return new JsonResult(new { success = true });
  288. }
  289. else
  290. return new JsonResult(new { success = false, message = "Unable to update pgp public key.", identityErrors = result.Errors });
  291. }
  292. return new JsonResult(new { success = false, message = "User does not exist." });
  293. }
  294. [HttpGet]
  295. public async Task<IActionResult> Get2FAKey(string username)
  296. {
  297. if (string.IsNullOrEmpty(username))
  298. return new JsonResult(new { success = false, message = "Username is required" });
  299. var foundUser = await _userManager.FindByNameAsync(username);
  300. if (foundUser != null)
  301. {
  302. string unformattedKey = await _userManager.GetAuthenticatorKeyAsync(foundUser);
  303. return new JsonResult(new { success = true, data = FormatKey(unformattedKey) });
  304. }
  305. return new JsonResult(new { success = false, message = "User does not exist." });
  306. }
  307. [HttpPost]
  308. public async Task<IActionResult> Reset2FAKey(Reset2FAKeyModel model)
  309. {
  310. if (string.IsNullOrEmpty(model.Username))
  311. return new JsonResult(new { success = false, message = "Username is required" });
  312. var foundUser = await _userManager.FindByNameAsync(model.Username);
  313. if (foundUser != null)
  314. {
  315. // Remove the UserInfo Cache
  316. RemoveCachedUser(model.Username);
  317. await _userManager.ResetAuthenticatorKeyAsync(foundUser);
  318. string unformattedKey = await _userManager.GetAuthenticatorKeyAsync(foundUser);
  319. return new JsonResult(new { success = true, data = FormatKey(unformattedKey) });
  320. }
  321. return new JsonResult(new { success = false, message = "User does not exist." });
  322. }
  323. [HttpPost]
  324. public async Task<IActionResult> Enable2FA(Enable2FAModel model)
  325. {
  326. if (string.IsNullOrEmpty(model.Username))
  327. return new JsonResult(new { success = false, message = "Username is required" });
  328. if (string.IsNullOrEmpty(model.Code))
  329. return new JsonResult(new { success = false, message = "Code is required" });
  330. var foundUser = await _userManager.FindByNameAsync(model.Username);
  331. if (foundUser != null)
  332. {
  333. // Strip spaces and hypens
  334. var verificationCode = model.Code.Replace(" ", string.Empty).Replace("-", string.Empty);
  335. var is2faTokenValid = await _userManager.VerifyTwoFactorTokenAsync(
  336. foundUser, _userManager.Options.Tokens.AuthenticatorTokenProvider, verificationCode);
  337. if (is2faTokenValid)
  338. {
  339. var result = await _userManager.SetTwoFactorEnabledAsync(foundUser, true);
  340. if (result.Succeeded)
  341. {
  342. // Remove the UserInfo Cache
  343. RemoveCachedUser(model.Username);
  344. var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(foundUser, 10);
  345. return new JsonResult(new { success = true, data = recoveryCodes.ToArray() });
  346. }
  347. else
  348. return new JsonResult(new { success = false, message = "Unable to set Two-Factor Authentication.", identityErrors = result.Errors });
  349. }
  350. return new JsonResult(new { success = false, message = "Verification code is invalid." });
  351. }
  352. return new JsonResult(new { success = false, message = "User does not exist." });
  353. }
  354. [HttpPost]
  355. public async Task<IActionResult> Disable2FA(Disable2FAModel model)
  356. {
  357. if (string.IsNullOrEmpty(model.Username))
  358. return new JsonResult(new { success = false, message = "Username is required" });
  359. var foundUser = await _userManager.FindByNameAsync(model.Username);
  360. if (foundUser != null)
  361. {
  362. var result = await _userManager.SetTwoFactorEnabledAsync(foundUser, false);
  363. if (result.Succeeded)
  364. {
  365. // Remove the UserInfo Cache
  366. RemoveCachedUser(model.Username);
  367. return new JsonResult(new { success = true });
  368. }
  369. else
  370. return new JsonResult(new { success = false, message = "Unable to disable Two-Factor Authentication.", identityErrors = result.Errors });
  371. }
  372. return new JsonResult(new { success = false, message = "User does not exist." });
  373. }
  374. [HttpPost]
  375. public async Task<IActionResult> GenerateRecoveryCodes(GenerateRecoveryCodesModel model)
  376. {
  377. if (string.IsNullOrEmpty(model.Username))
  378. return new JsonResult(new { success = false, message = "Username is required" });
  379. var foundUser = await _userManager.FindByNameAsync(model.Username);
  380. if (foundUser != null)
  381. {
  382. if (foundUser.TwoFactorEnabled)
  383. {
  384. // Remove the UserInfo Cache
  385. RemoveCachedUser(model.Username);
  386. var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(foundUser, 10);
  387. return new JsonResult(new { success = true, data = recoveryCodes.ToArray() });
  388. }
  389. return new JsonResult(new { success = false, message = "Two-Factor Authentication is not enabled." });
  390. }
  391. return new JsonResult(new { success = false, message = "User does not exist." });
  392. }
  393. [HttpGet]
  394. public async Task<IActionResult> GetClient(string username, string clientId, [FromServices] IClientStore clientStore, [FromServices] ConfigurationDbContext configContext)
  395. {
  396. if (string.IsNullOrEmpty(username))
  397. return new JsonResult(new { success = false, message = "Username is required" });
  398. if (string.IsNullOrEmpty(clientId))
  399. return new JsonResult(new { success = false, message = "Client Id is required" });
  400. var client = configContext.Clients.FirstOrDefault(c =>
  401. c.ClientId == clientId &&
  402. c.Properties.Exists(p =>
  403. p.Key == "username" &&
  404. p.Value.ToLower() == username.ToLower())
  405. );
  406. if (client != null)
  407. {
  408. var foundClient = await clientStore.FindClientByIdAsync(client.ClientId);
  409. return new JsonResult(new { success = true, data = foundClient });
  410. }
  411. return new JsonResult(new { success = false, message = "Client does not exist." });
  412. }
  413. [HttpGet]
  414. public async Task<IActionResult> GetClients(string username, [FromServices] IClientStore clientStore, [FromServices] ConfigurationDbContext configContext)
  415. {
  416. if (string.IsNullOrEmpty(username))
  417. return new JsonResult(new { success = false, message = "Username is required" });
  418. var foundClientIds = configContext.Clients.Where(c =>
  419. c.Properties.Exists(p =>
  420. p.Key == "username" &&
  421. p.Value.ToLower() == username.ToLower())
  422. ).Select(c => c.ClientId);
  423. var clients = new List<IdentityServer4.Models.Client>();
  424. foreach (var clientId in foundClientIds)
  425. {
  426. var foundClient = await clientStore.FindClientByIdAsync(clientId);
  427. if (foundClient != null)
  428. clients.Add(foundClient);
  429. }
  430. return new JsonResult(new { success = true, data = clients });
  431. }
  432. [HttpPost]
  433. public IActionResult CreateClient(CreateClientModel model, [FromServices] ConfigurationDbContext configContext)
  434. {
  435. // Generate a unique client ID
  436. var clientId = StringHelper.RandomString(20, "abcdefghjkmnpqrstuvwxyz1234567890");
  437. while (configContext.Clients.Where(c => c.ClientId == clientId).FirstOrDefault() != null)
  438. {
  439. clientId = StringHelper.RandomString(20, "abcdefghjkmnpqrstuvwxyz1234567890");
  440. }
  441. var clientSecret = StringHelper.RandomString(40, "abcdefghjkmnpqrstuvwxyz1234567890");
  442. // Generate the origin for the callback
  443. Uri redirect = new Uri(model.CallbackUrl);
  444. string origin = redirect.Scheme + "://" + redirect.Host;
  445. var client = new IdentityServer4.Models.Client
  446. {
  447. Properties = new Dictionary<string, string>()
  448. {
  449. { "username", model.Username }
  450. },
  451. ClientId = clientId,
  452. ClientName = model.Name,
  453. ClientUri = model.HomepageUrl,
  454. LogoUri = model.LogoUrl,
  455. AllowedGrantTypes = new List<string>()
  456. {
  457. GrantType.AuthorizationCode,
  458. GrantType.ClientCredentials
  459. },
  460. ClientSecrets =
  461. {
  462. new IdentityServer4.Models.Secret(clientSecret.Sha256())
  463. },
  464. RequireConsent = true,
  465. RedirectUris =
  466. {
  467. model.CallbackUrl
  468. },
  469. AllowedCorsOrigins =
  470. {
  471. origin
  472. },
  473. AllowedScopes = model.AllowedScopes,
  474. AllowOfflineAccess = true
  475. };
  476. configContext.Clients.Add(client.ToEntity());
  477. configContext.SaveChanges();
  478. return new JsonResult(new { success = true, data = new { id = clientId, secret = clientSecret } });
  479. }
  480. [HttpPost]
  481. public IActionResult EditClient(EditClientModel model, [FromServices] ConfigurationDbContext configContext)
  482. {
  483. // Validate it's an actual client
  484. var foundClient = configContext.Clients.Where(c => c.ClientId == model.ClientId).FirstOrDefault();
  485. if (foundClient != null)
  486. {
  487. foundClient.ClientName = model.Name;
  488. foundClient.ClientUri = model.HomepageUrl;
  489. foundClient.LogoUri = model.LogoUrl;
  490. configContext.Entry(foundClient).State = EntityState.Modified;
  491. // Update the redirect URL for this client
  492. var results = configContext.Set<ClientRedirectUri>().Where(c => c.ClientId == foundClient.Id).ToList();
  493. if (results != null)
  494. {
  495. configContext.RemoveRange(results);
  496. }
  497. var newUri = new ClientRedirectUri();
  498. newUri.Client = foundClient;
  499. newUri.ClientId = foundClient.Id;
  500. newUri.RedirectUri = model.CallbackUrl;
  501. configContext.Add(newUri);
  502. // Generate the origin for the callback
  503. Uri redirect = new Uri(model.CallbackUrl);
  504. string origin = redirect.Scheme + "://" + redirect.Host;
  505. // Update the allowed origin for this client
  506. var corsOrigins = configContext.Set<ClientCorsOrigin>().Where(c => c.ClientId == foundClient.Id).ToList();
  507. if (corsOrigins != null)
  508. {
  509. configContext.RemoveRange(corsOrigins);
  510. }
  511. var newOrigin = new ClientCorsOrigin();
  512. newOrigin.Client = foundClient;
  513. newOrigin.ClientId = foundClient.Id;
  514. newOrigin.Origin = origin;
  515. configContext.Add(newUri);
  516. // Save all the changed
  517. configContext.SaveChanges();
  518. return new JsonResult(new { success = true });
  519. }
  520. return new JsonResult(new { success = false, message = "Client does not exist." });
  521. }
  522. [HttpPost]
  523. public IActionResult DeleteClient(DeleteClientModel model, [FromServices] ConfigurationDbContext configContext)
  524. {
  525. var foundClient = configContext.Clients.Where(c => c.ClientId == model.ClientId).FirstOrDefault();
  526. if (foundClient != null)
  527. {
  528. configContext.Clients.Remove(foundClient);
  529. configContext.SaveChanges();
  530. return new JsonResult(new { success = true });
  531. }
  532. return new JsonResult(new { success = false, message = "Client does not exist." });
  533. }
  534. private string FormatKey(string unformattedKey)
  535. {
  536. var result = new StringBuilder();
  537. int currentPosition = 0;
  538. while (currentPosition + 4 < unformattedKey.Length)
  539. {
  540. result.Append(unformattedKey.Substring(currentPosition, 4)).Append(" ");
  541. currentPosition += 4;
  542. }
  543. if (currentPosition < unformattedKey.Length)
  544. {
  545. result.Append(unformattedKey.Substring(currentPosition));
  546. }
  547. return result.ToString().ToLowerInvariant();
  548. }
  549. private async Task<ApplicationUser> GetCachedUser(string username)
  550. {
  551. if (string.IsNullOrEmpty(username))
  552. throw new ArgumentNullException("username");
  553. // Check the cache
  554. string cacheKey = _UserInfoCacheKey + username;
  555. ApplicationUser foundUser;
  556. if (!_cache.TryGetValue(cacheKey, out foundUser))
  557. {
  558. foundUser = await _userManager.FindByNameAsync(username);
  559. if (foundUser != null)
  560. {
  561. _cache.AddToCache(cacheKey, foundUser, new TimeSpan(1, 0, 0));
  562. }
  563. }
  564. return foundUser;
  565. }
  566. private void RemoveCachedUser(string username)
  567. {
  568. if (string.IsNullOrEmpty(username))
  569. throw new ArgumentNullException("username");
  570. string cacheKey = _UserInfoCacheKey + username;
  571. _cache.Remove(cacheKey);
  572. }
  573. }
  574. }