The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

UserController.cs 57KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using Teknik.Areas.Users.Models;
  5. using Teknik.Areas.Users.ViewModels;
  6. using Teknik.Controllers;
  7. using Teknik.Utilities;
  8. using Teknik.Areas.Users.Utility;
  9. using Teknik.Filters;
  10. using QRCoder;
  11. using TwoStepsAuthenticator;
  12. using Teknik.Attributes;
  13. using Teknik.Utilities.Cryptography;
  14. using Microsoft.Extensions.Logging;
  15. using Teknik.Configuration;
  16. using Teknik.Data;
  17. using Microsoft.AspNetCore.Authorization;
  18. using Microsoft.AspNetCore.Mvc;
  19. using Microsoft.EntityFrameworkCore;
  20. using System.Net;
  21. using Microsoft.AspNetCore.Mvc.ViewEngines;
  22. using System.Threading.Tasks;
  23. using Teknik.Logging;
  24. using System.Security.Claims;
  25. using Microsoft.AspNetCore.Authentication.Cookies;
  26. using Microsoft.AspNetCore.Authentication;
  27. using IdentityServer4.Services;
  28. using Microsoft.AspNetCore.Identity;
  29. using IdentityModel.Client;
  30. using System.Net.Http;
  31. using Newtonsoft.Json.Linq;
  32. using Teknik.Security;
  33. using Microsoft.IdentityModel.Tokens;
  34. using IdentityModel;
  35. using System.Security.Cryptography;
  36. using System.IdentityModel.Tokens.Jwt;
  37. using Microsoft.AspNetCore.Http;
  38. using IdentityServer4.Models;
  39. namespace Teknik.Areas.Users.Controllers
  40. {
  41. [Authorize]
  42. [Area("User")]
  43. public class UserController : DefaultController
  44. {
  45. private static readonly UsedCodesManager usedCodesManager = new UsedCodesManager();
  46. private const string _AuthSessionKey = "AuthenticatedUser";
  47. private readonly IHttpContextAccessor _httpContextAccessor;
  48. private ISession _session => _httpContextAccessor.HttpContext.Session;
  49. private readonly LogoutSessionManager _logoutSessions;
  50. public UserController(ILogger<Logger> logger, Config config, TeknikEntities dbContext, LogoutSessionManager logoutSessions, IHttpContextAccessor httpContextAccessor) : base(logger, config, dbContext)
  51. {
  52. _logoutSessions = logoutSessions;
  53. _httpContextAccessor = httpContextAccessor;
  54. }
  55. [HttpGet]
  56. public IActionResult Index()
  57. {
  58. return Redirect(Url.SubRouteUrl("www", "Home.Index"));
  59. }
  60. [HttpGet]
  61. public IActionResult Login(string returnUrl)
  62. {
  63. // Let's double check their email and git accounts to make sure they exist
  64. string email = UserHelper.GetUserEmailAddress(_config, User.Identity.Name);
  65. if (_config.EmailConfig.Enabled && !UserHelper.UserEmailExists(_config, email))
  66. {
  67. //UserHelper.AddUserEmail(_config, email, model.Password);
  68. }
  69. if (_config.GitConfig.Enabled && !UserHelper.UserGitExists(_config, User.Identity.Name))
  70. {
  71. //UserHelper.AddUserGit(_config, User.Identity.Name, model.Password);
  72. }
  73. if (!string.IsNullOrEmpty(returnUrl))
  74. {
  75. return Redirect(returnUrl);
  76. }
  77. return Redirect(Url.SubRouteUrl("www", "Home.Index"));
  78. }
  79. [HttpGet]
  80. public async Task Logout()
  81. {
  82. // these are the sub & sid to signout
  83. //var sub = User.FindFirst("sub")?.Value;
  84. //var sid = User.FindFirst("sid")?.Value;
  85. await HttpContext.SignOutAsync("Cookies");
  86. await HttpContext.SignOutAsync("oidc");
  87. //_logoutSessions.Add(sub, sid);
  88. }
  89. [AllowAnonymous]
  90. public IActionResult GetPremium()
  91. {
  92. ViewBag.Title = "Get a Premium Account";
  93. GetPremiumViewModel model = new GetPremiumViewModel();
  94. return View(model);
  95. }
  96. [HttpGet]
  97. [AllowAnonymous]
  98. public IActionResult Register(string inviteCode, string ReturnUrl)
  99. {
  100. RegisterViewModel model = new RegisterViewModel();
  101. model.InviteCode = inviteCode;
  102. model.ReturnUrl = ReturnUrl;
  103. return View("/Areas/User/Views/User/ViewRegistration.cshtml", model);
  104. }
  105. [HttpOptions]
  106. [HttpPost]
  107. [AllowAnonymous]
  108. public async Task<IActionResult> Register([Bind(Prefix = "Register")]RegisterViewModel model)
  109. {
  110. model.Error = false;
  111. model.ErrorMessage = string.Empty;
  112. if (ModelState.IsValid)
  113. {
  114. if (_config.UserConfig.RegistrationEnabled)
  115. {
  116. if (!model.Error && !UserHelper.ValidUsername(_config, model.Username))
  117. {
  118. model.Error = true;
  119. model.ErrorMessage = "That username is not valid";
  120. }
  121. if (!model.Error && !(await UserHelper.UsernameAvailable(_dbContext, _config, model.Username)))
  122. {
  123. model.Error = true;
  124. model.ErrorMessage = "That username is not available";
  125. }
  126. if (!model.Error && model.Password != model.ConfirmPassword)
  127. {
  128. model.Error = true;
  129. model.ErrorMessage = "Passwords must match";
  130. }
  131. // Validate the Invite Code
  132. if (!model.Error && _config.UserConfig.InviteCodeRequired && string.IsNullOrEmpty(model.InviteCode))
  133. {
  134. model.Error = true;
  135. model.ErrorMessage = "An Invite Code is required to register";
  136. }
  137. if (!model.Error && !string.IsNullOrEmpty(model.InviteCode) && _dbContext.InviteCodes.Where(c => c.Code == model.InviteCode && c.Active && c.ClaimedUser == null).FirstOrDefault() == null)
  138. {
  139. model.Error = true;
  140. model.ErrorMessage = "Invalid Invite Code";
  141. }
  142. if (!model.Error)
  143. {
  144. try
  145. {
  146. await UserHelper.CreateAccount(_dbContext, _config, Url, model.Username, model.Password, model.RecoveryEmail, model.InviteCode);
  147. }
  148. catch (Exception ex)
  149. {
  150. model.Error = true;
  151. model.ErrorMessage = ex.GetFullMessage(true);
  152. }
  153. if (!model.Error)
  154. {
  155. // Let's log them in
  156. return GenerateActionResult(new { success = true, redirectUrl = Url.SubRouteUrl("account", "User.Login", new { returnUrl = model.ReturnUrl }) }, Redirect(Url.SubRouteUrl("account", "User.Login", new { returnUrl = model.ReturnUrl })));
  157. }
  158. }
  159. }
  160. if (!model.Error)
  161. {
  162. model.Error = true;
  163. model.ErrorMessage = "User Registration is Disabled";
  164. }
  165. }
  166. else
  167. {
  168. model.Error = true;
  169. model.ErrorMessage = "Missing Required Fields";
  170. }
  171. return GenerateActionResult(new { error = model.ErrorMessage }, View("/Areas/User/Views/User/ViewRegistration.cshtml", model));
  172. }
  173. // GET: Profile/Profile
  174. [AllowAnonymous]
  175. public async Task<IActionResult> ViewProfile(string username)
  176. {
  177. if (string.IsNullOrEmpty(username))
  178. {
  179. username = User.Identity.Name;
  180. }
  181. ProfileViewModel model = new ProfileViewModel();
  182. ViewBag.Title = "User Does Not Exist";
  183. ViewBag.Description = "The User does not exist";
  184. try
  185. {
  186. User user = UserHelper.GetUser(_dbContext, username);
  187. if (user != null)
  188. {
  189. ViewBag.Title = username + "'s Profile";
  190. ViewBag.Description = "Viewing " + username + "'s Profile";
  191. model.UserID = user.UserId;
  192. model.Username = user.Username;
  193. if (_config.EmailConfig.Enabled)
  194. {
  195. model.Email = string.Format("{0}@{1}", user.Username, _config.EmailConfig.Domain);
  196. }
  197. // Get the user claims for this user
  198. model.IdentityUserInfo = await IdentityHelper.GetIdentityUserInfo(_config, user.Username);
  199. model.LastSeen = UserHelper.GetLastAccountActivity(_dbContext, _config, user.Username, model.IdentityUserInfo);
  200. model.UserSettings = user.UserSettings;
  201. model.BlogSettings = user.BlogSettings;
  202. model.UploadSettings = user.UploadSettings;
  203. model.Uploads = _dbContext.Uploads.Where(u => u.UserId == user.UserId).OrderByDescending(u => u.DateUploaded).ToList();
  204. model.Pastes = _dbContext.Pastes.Where(u => u.UserId == user.UserId).OrderByDescending(u => u.DatePosted).ToList();
  205. model.ShortenedUrls = _dbContext.ShortenedUrls.Where(s => s.UserId == user.UserId).OrderByDescending(s => s.DateAdded).ToList();
  206. model.Vaults = _dbContext.Vaults.Where(v => v.UserId == user.UserId).OrderByDescending(v => v.DateCreated).ToList();
  207. return View(model);
  208. }
  209. model.Error = true;
  210. model.ErrorMessage = "The user does not exist";
  211. }
  212. catch (Exception ex)
  213. {
  214. model.Error = true;
  215. model.ErrorMessage = ex.GetFullMessage(true);
  216. }
  217. return View(model);
  218. }
  219. public IActionResult ViewServiceData()
  220. {
  221. string username = User.Identity.Name;
  222. ViewServiceDataViewModel model = new ViewServiceDataViewModel();
  223. ViewBag.Title = "User Does Not Exist";
  224. ViewBag.Description = "The User does not exist";
  225. try
  226. {
  227. User user = UserHelper.GetUser(_dbContext, username);
  228. if (user != null)
  229. {
  230. ViewBag.Title = "Service Data";
  231. ViewBag.Description = "Viewing all of your service data";
  232. model.Uploads = _dbContext.Uploads.Where(u => u.UserId == user.UserId).OrderByDescending(u => u.DateUploaded).ToList();
  233. model.Pastes = _dbContext.Pastes.Where(u => u.UserId == user.UserId).OrderByDescending(u => u.DatePosted).ToList();
  234. model.ShortenedUrls = _dbContext.ShortenedUrls.Where(s => s.UserId == user.UserId).OrderByDescending(s => s.DateAdded).ToList();
  235. model.Vaults = _dbContext.Vaults.Where(v => v.UserId == user.UserId).OrderByDescending(v => v.DateCreated).ToList();
  236. return View(model);
  237. }
  238. model.Error = true;
  239. model.ErrorMessage = "The user does not exist";
  240. }
  241. catch (Exception ex)
  242. {
  243. model.Error = true;
  244. model.ErrorMessage = ex.GetFullMessage(true);
  245. }
  246. return View(model);
  247. }
  248. public IActionResult Settings()
  249. {
  250. return Redirect(Url.SubRouteUrl("account", "User.ProfileSettings"));
  251. }
  252. public IActionResult ProfileSettings()
  253. {
  254. string username = User.Identity.Name;
  255. User user = UserHelper.GetUser(_dbContext, username);
  256. if (user != null)
  257. {
  258. ViewBag.Title = "Profile Settings";
  259. ViewBag.Description = "Your " + _config.Title + " Profile Settings";
  260. ProfileSettingsViewModel model = new ProfileSettingsViewModel();
  261. model.Page = "Profile";
  262. model.UserID = user.UserId;
  263. model.Username = user.Username;
  264. model.About = user.UserSettings.About;
  265. model.Quote = user.UserSettings.Quote;
  266. model.Website = user.UserSettings.Website;
  267. return View("/Areas/User/Views/User/Settings/ProfileSettings.cshtml", model);
  268. }
  269. return new StatusCodeResult(StatusCodes.Status403Forbidden);
  270. }
  271. public IActionResult AccountSettings()
  272. {
  273. string username = User.Identity.Name;
  274. User user = UserHelper.GetUser(_dbContext, username);
  275. if (user != null)
  276. {
  277. ViewBag.Title = "Account Settings";
  278. ViewBag.Description = "Your " + _config.Title + " Account Settings";
  279. AccountSettingsViewModel model = new AccountSettingsViewModel();
  280. model.Page = "Account";
  281. model.UserID = user.UserId;
  282. model.Username = user.Username;
  283. return View("/Areas/User/Views/User/Settings/AccountSettings.cshtml", model);
  284. }
  285. return new StatusCodeResult(StatusCodes.Status403Forbidden);
  286. }
  287. public async Task<IActionResult> SecuritySettings()
  288. {
  289. string username = User.Identity.Name;
  290. User user = UserHelper.GetUser(_dbContext, username);
  291. if (user != null)
  292. {
  293. ViewBag.Title = "Security Settings";
  294. ViewBag.Description = "Your " + _config.Title + " Security Settings";
  295. SecuritySettingsViewModel model = new SecuritySettingsViewModel();
  296. model.Page = "Security";
  297. model.UserID = user.UserId;
  298. model.Username = user.Username;
  299. // Get the user secure info
  300. IdentityUserInfo userInfo = await IdentityHelper.GetIdentityUserInfo(_config, user.Username);
  301. //model.TrustedDeviceCount = user.TrustedDevices.Count;
  302. //model.AuthTokens = new List<AuthTokenViewModel>();
  303. //foreach (AuthToken token in user.AuthTokens)
  304. //{
  305. // AuthTokenViewModel tokenModel = new AuthTokenViewModel();
  306. // tokenModel.AuthTokenId = token.AuthTokenId;
  307. // tokenModel.Name = token.Name;
  308. // tokenModel.LastDateUsed = token.LastDateUsed;
  309. // model.AuthTokens.Add(tokenModel);
  310. //}
  311. model.PgpPublicKey = userInfo.PGPPublicKey;
  312. model.RecoveryEmail = userInfo.RecoveryEmail;
  313. if (userInfo.RecoveryVerified.HasValue)
  314. model.RecoveryVerified = userInfo.RecoveryVerified.Value;
  315. if (userInfo.TwoFactorEnabled.HasValue)
  316. model.TwoFactorEnabled = userInfo.TwoFactorEnabled.Value;
  317. return View("/Areas/User/Views/User/Settings/SecuritySettings.cshtml", model);
  318. }
  319. return new StatusCodeResult(StatusCodes.Status403Forbidden);
  320. }
  321. public async Task<IActionResult> DeveloperSettings()
  322. {
  323. string username = User.Identity.Name;
  324. User user = UserHelper.GetUser(_dbContext, username);
  325. if (user != null)
  326. {
  327. ViewBag.Title = "Developer Settings";
  328. ViewBag.Description = "Your " + _config.Title + " Developer Settings";
  329. DeveloperSettingsViewModel model = new DeveloperSettingsViewModel();
  330. model.Page = "Developer";
  331. model.UserID = user.UserId;
  332. model.Username = user.Username;
  333. model.AuthTokens = new List<AuthTokenViewModel>();
  334. model.Clients = new List<ClientViewModel>();
  335. //foreach (AuthToken token in user.AuthTokens)
  336. //{
  337. // AuthTokenViewModel tokenModel = new AuthTokenViewModel();
  338. // tokenModel.AuthTokenId = token.AuthTokenId;
  339. // tokenModel.Name = token.Name;
  340. // tokenModel.LastDateUsed = token.LastDateUsed;
  341. // model.AuthTokens.Add(tokenModel);
  342. //}
  343. Client[] clients = await IdentityHelper.GetClients(_config, username);
  344. foreach (Client client in clients)
  345. {
  346. model.Clients.Add(new ClientViewModel()
  347. {
  348. Id = client.ClientId,
  349. Name = client.ClientName,
  350. HomepageUrl = client.ClientUri,
  351. LogoUrl = client.LogoUri,
  352. CallbackUrl = string.Join(',', client.RedirectUris),
  353. AllowedScopes = client.AllowedScopes
  354. });
  355. }
  356. return View("/Areas/User/Views/User/Settings/DeveloperSettings.cshtml", model);
  357. }
  358. return new StatusCodeResult(StatusCodes.Status403Forbidden);
  359. }
  360. public IActionResult InviteSettings()
  361. {
  362. string username = User.Identity.Name;
  363. User user = UserHelper.GetUser(_dbContext, username);
  364. if (user != null)
  365. {
  366. ViewBag.Title = "Invite Settings";
  367. ViewBag.Description = "Your " + _config.Title + " Invite Settings";
  368. InviteSettingsViewModel model = new InviteSettingsViewModel();
  369. model.Page = "Invite";
  370. model.UserID = user.UserId;
  371. model.Username = user.Username;
  372. List<InviteCodeViewModel> availableCodes = new List<InviteCodeViewModel>();
  373. List<InviteCodeViewModel> claimedCodes = new List<InviteCodeViewModel>();
  374. if (user.OwnedInviteCodes != null)
  375. {
  376. foreach (InviteCode inviteCode in user.OwnedInviteCodes.Where(c => c.Active))
  377. {
  378. InviteCodeViewModel inviteCodeViewModel = new InviteCodeViewModel();
  379. inviteCodeViewModel.ClaimedUser = inviteCode.ClaimedUser;
  380. inviteCodeViewModel.Active = inviteCode.Active;
  381. inviteCodeViewModel.Code = inviteCode.Code;
  382. inviteCodeViewModel.InviteCodeId = inviteCode.InviteCodeId;
  383. inviteCodeViewModel.Owner = inviteCode.Owner;
  384. if (inviteCode.ClaimedUser == null)
  385. availableCodes.Add(inviteCodeViewModel);
  386. if (inviteCode.ClaimedUser != null)
  387. claimedCodes.Add(inviteCodeViewModel);
  388. }
  389. }
  390. model.AvailableCodes = availableCodes;
  391. model.ClaimedCodes = claimedCodes;
  392. return View("/Areas/User/Views/User/Settings/InviteSettings.cshtml", model);
  393. }
  394. return new StatusCodeResult(StatusCodes.Status403Forbidden);
  395. }
  396. public IActionResult BlogSettings()
  397. {
  398. string username = User.Identity.Name;
  399. User user = UserHelper.GetUser(_dbContext, username);
  400. if (user != null)
  401. {
  402. ViewBag.Title = "Blog Settings";
  403. ViewBag.Description = "Your " + _config.Title + " Blog Settings";
  404. BlogSettingsViewModel model = new BlogSettingsViewModel();
  405. model.Page = "Blog";
  406. model.UserID = user.UserId;
  407. model.Username = user.Username;
  408. model.Title = user.BlogSettings.Title;
  409. model.Description = user.BlogSettings.Description;
  410. return View("/Areas/User/Views/User/Settings/BlogSettings.cshtml", model);
  411. }
  412. return new StatusCodeResult(StatusCodes.Status403Forbidden);
  413. }
  414. public IActionResult UploadSettings()
  415. {
  416. string username = User.Identity.Name;
  417. User user = UserHelper.GetUser(_dbContext, username);
  418. if (user != null)
  419. {
  420. ViewBag.Title = "Upload Settings";
  421. ViewBag.Description = "Your " + _config.Title + " Upload Settings";
  422. UploadSettingsViewModel model = new UploadSettingsViewModel();
  423. model.Page = "Upload";
  424. model.UserID = user.UserId;
  425. model.Username = user.Username;
  426. model.Encrypt = user.UploadSettings.Encrypt;
  427. model.ExpirationLength = user.UploadSettings.ExpirationLength;
  428. model.ExpirationUnit = user.UploadSettings.ExpirationUnit;
  429. return View("/Areas/User/Views/User/Settings/UploadSettings.cshtml", model);
  430. }
  431. return new StatusCodeResult(StatusCodes.Status403Forbidden);
  432. }
  433. [HttpGet]
  434. [AllowAnonymous]
  435. public async Task<IActionResult> ViewRawPGP(string username)
  436. {
  437. ViewBag.Title = username + "'s Public Key";
  438. ViewBag.Description = "The PGP public key for " + username;
  439. IdentityUserInfo userClaims = await IdentityHelper.GetIdentityUserInfo(_config, username);
  440. if (!string.IsNullOrEmpty(userClaims.PGPPublicKey))
  441. {
  442. return Content(userClaims.PGPPublicKey, "text/plain");
  443. }
  444. return new StatusCodeResult(StatusCodes.Status404NotFound);
  445. }
  446. [HttpPost]
  447. [ValidateAntiForgeryToken]
  448. public IActionResult EditBlog(BlogSettingsViewModel settings)
  449. {
  450. if (ModelState.IsValid)
  451. {
  452. try
  453. {
  454. User user = UserHelper.GetUser(_dbContext, User.Identity.Name);
  455. if (user != null)
  456. {
  457. // Blogs
  458. user.BlogSettings.Title = settings.Title;
  459. user.BlogSettings.Description = settings.Description;
  460. UserHelper.EditAccount(_dbContext, _config, user);
  461. return Json(new { result = true });
  462. }
  463. return Json(new { error = "User does not exist" });
  464. }
  465. catch (Exception ex)
  466. {
  467. return Json(new { error = ex.GetFullMessage(true) });
  468. }
  469. }
  470. return Json(new { error = "Invalid Parameters" });
  471. }
  472. [HttpPost]
  473. [ValidateAntiForgeryToken]
  474. public IActionResult EditProfile(ProfileSettingsViewModel settings)
  475. {
  476. if (ModelState.IsValid)
  477. {
  478. try
  479. {
  480. User user = UserHelper.GetUser(_dbContext, User.Identity.Name);
  481. if (user != null)
  482. {
  483. // Profile Info
  484. user.UserSettings.Website = settings.Website;
  485. user.UserSettings.Quote = settings.Quote;
  486. user.UserSettings.About = settings.About;
  487. UserHelper.EditAccount(_dbContext, _config, user);
  488. return Json(new { result = true });
  489. }
  490. return Json(new { error = "User does not exist" });
  491. }
  492. catch (Exception ex)
  493. {
  494. return Json(new { error = ex.GetFullMessage(true) });
  495. }
  496. }
  497. return Json(new { error = "Invalid Parameters" });
  498. }
  499. [HttpPost]
  500. [ValidateAntiForgeryToken]
  501. public async Task<IActionResult> EditSecurity(SecuritySettingsViewModel settings)
  502. {
  503. if (ModelState.IsValid)
  504. {
  505. try
  506. {
  507. User user = UserHelper.GetUser(_dbContext, User.Identity.Name);
  508. if (user != null)
  509. {
  510. // PGP Key valid?
  511. if (!string.IsNullOrEmpty(settings.PgpPublicKey) && !PGP.IsPublicKey(settings.PgpPublicKey))
  512. {
  513. return Json(new { error = "Invalid PGP Public Key" });
  514. }
  515. // Get the user secure info
  516. IdentityUserInfo userInfo = await IdentityHelper.GetIdentityUserInfo(_config, user.Username);
  517. if (userInfo.PGPPublicKey != settings.PgpPublicKey)
  518. {
  519. var result = await IdentityHelper.UpdatePGPPublicKey(_config, user.Username, settings.PgpPublicKey);
  520. if (!result.Success)
  521. return Json(new { error = result.Message });
  522. }
  523. if (userInfo.RecoveryEmail != settings.RecoveryEmail)
  524. {
  525. var token = await IdentityHelper.UpdateRecoveryEmail(_config, user.Username, settings.RecoveryEmail);
  526. // If they have a recovery email, let's send a verification
  527. if (!string.IsNullOrEmpty(settings.RecoveryEmail))
  528. {
  529. string resetUrl = Url.SubRouteUrl("account", "User.ResetPassword", new { Username = user.Username });
  530. string verifyUrl = Url.SubRouteUrl("account", "User.VerifyRecoveryEmail", new { Username = user.Username, Code = WebUtility.UrlEncode(token) });
  531. UserHelper.SendRecoveryEmailVerification(_config, user.Username, settings.RecoveryEmail, resetUrl, verifyUrl);
  532. }
  533. }
  534. //if (!settings.TwoFactorEnabled && (!userInfo.TwoFactorEnabled.HasValue || userInfo.TwoFactorEnabled.Value))
  535. //{
  536. // var result = await IdentityHelper.Disable2FA(_config, user.Username);
  537. // if (!result.Success)
  538. // return Json(new { error = result.Message });
  539. //}
  540. //UserHelper.EditAccount(_dbContext, _config, user, changePass, settings.NewPassword);
  541. //if (!oldTwoFactor && settings.TwoFactorEnabled)
  542. //{
  543. // return Json(new { result = new { checkAuth = true, key = newKey, qrUrl = Url.SubRouteUrl("account", "User.Action", new { action = "GenerateAuthQrCode", key = newKey }) } });
  544. //}
  545. return Json(new { result = true });
  546. }
  547. return Json(new { error = "User does not exist" });
  548. }
  549. catch (Exception ex)
  550. {
  551. return Json(new { error = ex.GetFullMessage(true) });
  552. }
  553. }
  554. return Json(new { error = "Invalid Parameters" });
  555. }
  556. [HttpPost]
  557. [ValidateAntiForgeryToken]
  558. public IActionResult EditUpload(UploadSettingsViewModel settings)
  559. {
  560. if (ModelState.IsValid)
  561. {
  562. try
  563. {
  564. User user = UserHelper.GetUser(_dbContext, User.Identity.Name);
  565. if (user != null)
  566. {
  567. // Profile Info
  568. user.UploadSettings.Encrypt = settings.Encrypt;
  569. user.UploadSettings.ExpirationUnit = settings.ExpirationUnit;
  570. user.UploadSettings.ExpirationLength = settings.ExpirationLength;
  571. UserHelper.EditAccount(_dbContext, _config, user);
  572. return Json(new { result = true });
  573. }
  574. return Json(new { error = "User does not exist" });
  575. }
  576. catch (Exception ex)
  577. {
  578. return Json(new { error = ex.GetFullMessage(true) });
  579. }
  580. }
  581. return Json(new { error = "Invalid Parameters" });
  582. }
  583. public async Task<IActionResult> ChangePassword(AccountSettingsViewModel settings)
  584. {
  585. if (ModelState.IsValid)
  586. {
  587. try
  588. {
  589. User user = UserHelper.GetUser(_dbContext, User.Identity.Name);
  590. if (user != null)
  591. {
  592. // Did they enter their old password
  593. if (string.IsNullOrEmpty(settings.CurrentPassword))
  594. return Json(new { error = "You must enter your current password" });
  595. // Did they enter a new password
  596. if (string.IsNullOrEmpty(settings.NewPassword) || string.IsNullOrEmpty(settings.NewPasswordConfirm))
  597. return Json(new { error = "You must enter your new password" });
  598. // Old Password Valid?
  599. if (!(await UserHelper.UserPasswordCorrect(_config, user.Username, settings.CurrentPassword)))
  600. return Json(new { error = "Invalid Original Password" });
  601. // The New Password Match?
  602. if (settings.NewPassword != settings.NewPasswordConfirm)
  603. return Json(new { error = "New Password must match confirmation" });
  604. // Are password resets enabled?
  605. if (!_config.UserConfig.PasswordResetEnabled)
  606. return Json(new { error = "Password resets are disabled" });
  607. // Change their password
  608. await UserHelper.ChangeAccountPassword(_dbContext, _config, user.Username, settings.CurrentPassword, settings.NewPassword);
  609. return Json(new { result = true });
  610. }
  611. return Json(new { error = "User does not exist" });
  612. }
  613. catch (Exception ex)
  614. {
  615. return Json(new { error = ex.GetFullMessage(true) });
  616. }
  617. }
  618. return Json(new { error = "Invalid Parameters" });
  619. }
  620. [HttpPost]
  621. [ValidateAntiForgeryToken]
  622. public async Task<IActionResult> Delete()
  623. {
  624. if (ModelState.IsValid)
  625. {
  626. try
  627. {
  628. User user = UserHelper.GetUser(_dbContext, User.Identity.Name);
  629. if (user != null)
  630. {
  631. await UserHelper.DeleteAccount(_dbContext, _config, user);
  632. // Sign Out
  633. await HttpContext.SignOutAsync("Cookies");
  634. await HttpContext.SignOutAsync("oidc");
  635. return Json(new { result = true });
  636. }
  637. }
  638. catch (Exception ex)
  639. {
  640. return Json(new { error = ex.GetFullMessage(true) });
  641. }
  642. }
  643. return Json(new { error = "Unable to delete user" });
  644. }
  645. [HttpGet]
  646. public async Task<IActionResult> VerifyRecoveryEmail(string username, string code)
  647. {
  648. bool verified = true;
  649. if (string.IsNullOrEmpty(code))
  650. verified &= false;
  651. // Is there a code?
  652. if (verified)
  653. {
  654. var result = await IdentityHelper.VerifyRecoveryEmail(_config, username, WebUtility.UrlDecode(code));
  655. verified &= result.Success;
  656. }
  657. RecoveryEmailVerificationViewModel model = new RecoveryEmailVerificationViewModel();
  658. model.Success = verified;
  659. return View("/Areas/User/Views/User/ViewRecoveryEmailVerification.cshtml", model);
  660. }
  661. [HttpPost]
  662. [ValidateAntiForgeryToken]
  663. public async Task<IActionResult> ResendVerifyRecoveryEmail()
  664. {
  665. if (ModelState.IsValid)
  666. {
  667. try
  668. {
  669. IdentityUserInfo userInfo = await IdentityHelper.GetIdentityUserInfo(_config, User.Identity.Name);
  670. User user = UserHelper.GetUser(_dbContext, User.Identity.Name);
  671. if (user != null)
  672. {
  673. //If they have a recovery email, let's send a verification
  674. if (!string.IsNullOrEmpty(userInfo.RecoveryEmail))
  675. {
  676. if (!userInfo.RecoveryVerified.HasValue || !userInfo.RecoveryVerified.Value)
  677. {
  678. var token = await IdentityHelper.UpdateRecoveryEmail(_config, user.Username, userInfo.RecoveryEmail);
  679. string resetUrl = Url.SubRouteUrl("account", "User.ResetPassword", new { Username = user.Username });
  680. string verifyUrl = Url.SubRouteUrl("account", "User.VerifyRecoveryEmail", new { Username = user.Username, Code = WebUtility.UrlEncode(token) });
  681. UserHelper.SendRecoveryEmailVerification(_config, user.Username, userInfo.RecoveryEmail, resetUrl, verifyUrl);
  682. return Json(new { result = true });
  683. }
  684. return Json(new { error = "The recovery email is already verified" });
  685. }
  686. }
  687. }
  688. catch (Exception ex)
  689. {
  690. return Json(new { error = ex.GetFullMessage(true) });
  691. }
  692. }
  693. return Json(new { error = "Unable to resend verification" });
  694. }
  695. [HttpGet]
  696. [AllowAnonymous]
  697. public IActionResult ResetPassword(string username)
  698. {
  699. ResetPasswordViewModel model = new ResetPasswordViewModel();
  700. model.Username = username;
  701. return View("/Areas/User/Views/User/ResetPassword.cshtml", model);
  702. }
  703. [HttpPost]
  704. [AllowAnonymous]
  705. [ValidateAntiForgeryToken]
  706. public async Task<IActionResult> SendResetPasswordVerification(string username)
  707. {
  708. if (ModelState.IsValid)
  709. {
  710. try
  711. {
  712. User user = UserHelper.GetUser(_dbContext, username);
  713. if (user != null)
  714. {
  715. IdentityUserInfo userClaims = await IdentityHelper.GetIdentityUserInfo(_config, User.Identity.Name);
  716. // If they have a recovery email, let's send a verification
  717. if (!string.IsNullOrEmpty(userClaims.RecoveryEmail) && userClaims.RecoveryVerified.HasValue && userClaims.RecoveryVerified.Value)
  718. {
  719. string verifyCode = await IdentityHelper.GeneratePasswordResetToken(_config, User.Identity.Name);
  720. string resetUrl = Url.SubRouteUrl("account", "User.VerifyResetPassword", new { Username = user.Username, Code = WebUtility.UrlEncode(verifyCode) });
  721. UserHelper.SendResetPasswordVerification(_config, user.Username, userClaims.RecoveryEmail, resetUrl);
  722. return Json(new { result = true });
  723. }
  724. return Json(new { error = "The user doesn't have a recovery email specified, or has not been verified." });
  725. }
  726. return Json(new { error = "The username is not valid" });
  727. }
  728. catch (Exception ex)
  729. {
  730. return Json(new { error = ex.GetFullMessage(true) });
  731. }
  732. }
  733. return Json(new { error = "Unable to send reset link" });
  734. }
  735. [HttpGet]
  736. [AllowAnonymous]
  737. public async Task<IActionResult> VerifyResetPassword(string username, string code)
  738. {
  739. bool verified = true;
  740. if (string.IsNullOrEmpty(code))
  741. verified &= false;
  742. // Is there a code?
  743. if (verified)
  744. {
  745. // The password reset code is valid, let's get their user account for this session
  746. User user = UserHelper.GetUser(_dbContext, username);
  747. _session.SetString(_AuthSessionKey, user.Username);
  748. _session.SetString("AuthCode", WebUtility.UrlDecode(code));
  749. await _session.CommitAsync();
  750. }
  751. ResetPasswordVerificationViewModel model = new ResetPasswordVerificationViewModel();
  752. model.Success = verified;
  753. return View("/Areas/User/Views/User/ResetPasswordVerification.cshtml", model);
  754. }
  755. [HttpPost]
  756. [AllowAnonymous]
  757. [ValidateAntiForgeryToken]
  758. public async Task<IActionResult> SetUserPassword(SetPasswordViewModel passwordViewModel)
  759. {
  760. if (ModelState.IsValid)
  761. {
  762. try
  763. {
  764. await _session.LoadAsync();
  765. string code = _session.GetString("AuthCode");
  766. if (!string.IsNullOrEmpty(code))
  767. {
  768. string username = _session.GetString(_AuthSessionKey);
  769. if (!string.IsNullOrEmpty(username))
  770. {
  771. if (string.IsNullOrEmpty(passwordViewModel.Password))
  772. {
  773. return Json(new { error = "Password must not be empty" });
  774. }
  775. if (passwordViewModel.Password != passwordViewModel.PasswordConfirm)
  776. {
  777. return Json(new { error = "Passwords must match" });
  778. }
  779. try
  780. {
  781. await UserHelper.ResetAccountPassword(_dbContext, _config, username, code, passwordViewModel.Password);
  782. _session.Remove(_AuthSessionKey);
  783. _session.Remove("AuthCode");
  784. return Json(new { result = true });
  785. }
  786. catch (Exception ex)
  787. {
  788. return Json(new { error = ex.Message });
  789. }
  790. }
  791. return Json(new { error = "User does not exist" });
  792. }
  793. return Json(new { error = "Invalid Code" });
  794. }
  795. catch (Exception ex)
  796. {
  797. return Json(new { error = ex.GetFullMessage(true) });
  798. }
  799. }
  800. return Json(new { error = "Unable to reset user password" });
  801. }
  802. [HttpPost]
  803. [ValidateAntiForgeryToken]
  804. public async Task<IActionResult> Generate2FA()
  805. {
  806. User user = UserHelper.GetUser(_dbContext, User.Identity.Name);
  807. if (user != null)
  808. {
  809. // Get User Identity Info
  810. var userInfo = await IdentityHelper.GetIdentityUserInfo(_config, User.Identity.Name);
  811. if (userInfo.TwoFactorEnabled.HasValue && !userInfo.TwoFactorEnabled.Value)
  812. {
  813. // Validate the code with the identity server
  814. var key = await IdentityHelper.Reset2FAKey(_config, user.Username);
  815. if (!string.IsNullOrEmpty(key))
  816. {
  817. return Json(new { result = true, key = key, qrUrl = Url.SubRouteUrl("account", "User.Action", new { action = "GenerateAuthQrCode", key = key }) });
  818. }
  819. return Json(new { error = "Unable to generate Two Factor Authentication key" });
  820. }
  821. return Json(new { error = "User already has Two Factor Authentication enabled" });
  822. }
  823. return Json(new { error = "User does not exist" });
  824. }
  825. [HttpPost]
  826. [ValidateAntiForgeryToken]
  827. public async Task<IActionResult> VerifyAuthenticatorCode(string code)
  828. {
  829. User user = UserHelper.GetUser(_dbContext, User.Identity.Name);
  830. if (user != null)
  831. {
  832. // Get User Identity Info
  833. var userInfo = await IdentityHelper.GetIdentityUserInfo(_config, User.Identity.Name);
  834. if (userInfo.TwoFactorEnabled.HasValue && !userInfo.TwoFactorEnabled.Value)
  835. {
  836. // Validate the code with the identity server
  837. var result = await IdentityHelper.Enable2FA(_config, user.Username, code);
  838. if (result.Any())
  839. {
  840. return Json(new { result = true, recoveryCodes = result });
  841. }
  842. return Json(new { error = "Invalid Authentication Code" });
  843. }
  844. return Json(new { error = "User already has Two Factor Authentication enabled" });
  845. }
  846. return Json(new { error = "User does not exist" });
  847. }
  848. [HttpPost]
  849. [ValidateAntiForgeryToken]
  850. public async Task<IActionResult> ResetRecoveryCodes()
  851. {
  852. User user = UserHelper.GetUser(_dbContext, User.Identity.Name);
  853. if (user != null)
  854. {
  855. // Get User Identity Info
  856. var userInfo = await IdentityHelper.GetIdentityUserInfo(_config, User.Identity.Name);
  857. if (userInfo.TwoFactorEnabled.HasValue && userInfo.TwoFactorEnabled.Value)
  858. {
  859. // Regenerate the recovery codes
  860. var result = await IdentityHelper.GenerateRecoveryCodes(_config, user.Username);
  861. if (result.Any())
  862. {
  863. return Json(new { result = true, recoveryCodes = result });
  864. }
  865. return Json(new { error = "Invalid Authentication Code" });
  866. }
  867. return Json(new { error = "User doesn't have Two Factor Authentication enabled" });
  868. }
  869. return Json(new { error = "User does not exist" });
  870. }
  871. [HttpPost]
  872. [ValidateAntiForgeryToken]
  873. public async Task<IActionResult> Disable2FA()
  874. {
  875. User user = UserHelper.GetUser(_dbContext, User.Identity.Name);
  876. if (user != null)
  877. {
  878. // Get User Identity Info
  879. var userInfo = await IdentityHelper.GetIdentityUserInfo(_config, User.Identity.Name);
  880. if (userInfo.TwoFactorEnabled.HasValue && userInfo.TwoFactorEnabled.Value)
  881. {
  882. // Validate the code with the identity server
  883. var result = await IdentityHelper.Disable2FA(_config, user.Username);
  884. if (result.Success)
  885. {
  886. return Json(new { result = true });
  887. }
  888. return Json(new { error = result.Message });
  889. }
  890. return Json(new { error = "User doesn't have Two Factor Authentication enabled" });
  891. }
  892. return Json(new { error = "User does not exist" });
  893. }
  894. [HttpGet]
  895. public IActionResult GenerateAuthQrCode(string key)
  896. {
  897. var ProvisionUrl = string.Format("otpauth://totp/{0}:{1}?secret={2}", _config.Title, User.Identity.Name, key);
  898. QRCodeGenerator qrGenerator = new QRCodeGenerator();
  899. QRCodeData qrCodeData = qrGenerator.CreateQrCode(ProvisionUrl, QRCodeGenerator.ECCLevel.Q);
  900. PngByteQRCode qrCode = new PngByteQRCode(qrCodeData);
  901. return File(qrCode.GetGraphic(20), "image/png");
  902. }
  903. [HttpPost]
  904. [ValidateAntiForgeryToken]
  905. public IActionResult ClearTrustedDevices()
  906. {
  907. try
  908. {
  909. User user = UserHelper.GetUser(_dbContext, User.Identity.Name);
  910. if (user != null)
  911. {
  912. //if (user.SecuritySettings.AllowTrustedDevices)
  913. //{
  914. // // let's clear the trusted devices
  915. // user.TrustedDevices.Clear();
  916. // List<TrustedDevice> foundDevices = _dbContext.TrustedDevices.Where(d => d.UserId == user.UserId).ToList();
  917. // if (foundDevices != null)
  918. // {
  919. // foreach (TrustedDevice device in foundDevices)
  920. // {
  921. // _dbContext.TrustedDevices.Remove(device);
  922. // }
  923. // }
  924. // _dbContext.Entry(user).State = EntityState.Modified;
  925. // _dbContext.SaveChanges();
  926. // return Json(new { result = true });
  927. //}
  928. return Json(new { error = "User does not allow trusted devices" });
  929. }
  930. return Json(new { error = "User does not exist" });
  931. }
  932. catch (Exception ex)
  933. {
  934. return Json(new { error = ex.GetFullMessage(true) });
  935. }
  936. }
  937. [HttpPost]
  938. [ValidateAntiForgeryToken]
  939. public async Task<IActionResult> GenerateToken(string name, [FromServices] ICompositeViewEngine viewEngine)
  940. {
  941. try
  942. {
  943. User user = UserHelper.GetUser(_dbContext, User.Identity.Name);
  944. if (user != null)
  945. {
  946. //string newTokenStr = UserHelper.GenerateAuthToken(_dbContext, user.Username);
  947. //if (!string.IsNullOrEmpty(newTokenStr))
  948. //{
  949. // AuthToken token = new AuthToken();
  950. // token.UserId = user.UserId;
  951. // token.HashedToken = SHA256.Hash(newTokenStr);
  952. // token.Name = name;
  953. // _dbContext.AuthTokens.Add(token);
  954. // _dbContext.SaveChanges();
  955. // AuthTokenViewModel model = new AuthTokenViewModel();
  956. // model.AuthTokenId = token.AuthTokenId;
  957. // model.Name = token.Name;
  958. // model.LastDateUsed = token.LastDateUsed;
  959. // string renderedView = await RenderPartialViewToString(viewEngine, "~/Areas/User/Views/User/Settings/AuthToken.cshtml", model);
  960. // return Json(new { result = new { token = newTokenStr, html = renderedView } });
  961. //}
  962. return Json(new { error = "Unable to generate Auth Token" });
  963. }
  964. return Json(new { error = "User does not exist" });
  965. }
  966. catch (Exception ex)
  967. {
  968. return Json(new { error = ex.GetFullMessage(true) });
  969. }
  970. }
  971. [HttpPost]
  972. [ValidateAntiForgeryToken]
  973. public IActionResult RevokeAllTokens()
  974. {
  975. try
  976. {
  977. User user = UserHelper.GetUser(_dbContext, User.Identity.Name);
  978. if (user != null)
  979. {
  980. //user.AuthTokens.Clear();
  981. //List<AuthToken> foundTokens = _dbContext.AuthTokens.Where(d => d.UserId == user.UserId).ToList();
  982. //if (foundTokens != null)
  983. //{
  984. // foreach (AuthToken token in foundTokens)
  985. // {
  986. // _dbContext.AuthTokens.Remove(token);
  987. // }
  988. //}
  989. _dbContext.Entry(user).State = EntityState.Modified;
  990. _dbContext.SaveChanges();
  991. return Json(new { result = true });
  992. }
  993. return Json(new { error = "User does not exist" });
  994. }
  995. catch (Exception ex)
  996. {
  997. return Json(new { error = ex.GetFullMessage(true) });
  998. }
  999. }
  1000. [HttpPost]
  1001. [ValidateAntiForgeryToken]
  1002. public IActionResult EditTokenName(int tokenId, string name)
  1003. {
  1004. try
  1005. {
  1006. User user = UserHelper.GetUser(_dbContext, User.Identity.Name);
  1007. if (user != null)
  1008. {
  1009. //AuthToken foundToken = _dbContext.AuthTokens.Where(d => d.UserId == user.UserId && d.AuthTokenId == tokenId).FirstOrDefault();
  1010. //if (foundToken != null)
  1011. //{
  1012. // foundToken.Name = name;
  1013. // _dbContext.Entry(foundToken).State = EntityState.Modified;
  1014. // _dbContext.SaveChanges();
  1015. // return Json(new { result = new { name = name } });
  1016. //}
  1017. return Json(new { error = "Authentication Token does not exist" });
  1018. }
  1019. return Json(new { error = "User does not exist" });
  1020. }
  1021. catch (Exception ex)
  1022. {
  1023. return Json(new { error = ex.GetFullMessage(true) });
  1024. }
  1025. }
  1026. [HttpPost]
  1027. [ValidateAntiForgeryToken]
  1028. public IActionResult DeleteToken(int tokenId)
  1029. {
  1030. try
  1031. {
  1032. User user = UserHelper.GetUser(_dbContext, User.Identity.Name);
  1033. if (user != null)
  1034. {
  1035. //AuthToken foundToken = _dbContext.AuthTokens.Where(d => d.UserId == user.UserId && d.AuthTokenId == tokenId).FirstOrDefault();
  1036. //if (foundToken != null)
  1037. //{
  1038. // _dbContext.AuthTokens.Remove(foundToken);
  1039. // user.AuthTokens.Remove(foundToken);
  1040. // _dbContext.Entry(user).State = EntityState.Modified;
  1041. // _dbContext.SaveChanges();
  1042. // return Json(new { result = true });
  1043. //}
  1044. return Json(new { error = "Authentication Token does not exist" });
  1045. }
  1046. return Json(new { error = "User does not exist" });
  1047. }
  1048. catch (Exception ex)
  1049. {
  1050. return Json(new { error = ex.GetFullMessage(true) });
  1051. }
  1052. }
  1053. [HttpPost]
  1054. [ValidateAntiForgeryToken]
  1055. public async Task<IActionResult> CreateClient(string name, string homepageUrl, string logoUrl, string callbackUrl, [FromServices] ICompositeViewEngine viewEngine)
  1056. {
  1057. try
  1058. {
  1059. if (string.IsNullOrEmpty(name))
  1060. return Json(new { error = "You must enter a client name" });
  1061. if (string.IsNullOrEmpty(callbackUrl))
  1062. return Json(new { error = "You must enter an authorization callback URL" });
  1063. if (!callbackUrl.IsValidUrl())
  1064. return Json(new { error = "Invalid callback URL" });
  1065. if (!string.IsNullOrEmpty(homepageUrl) && !homepageUrl.IsValidUrl())
  1066. return Json(new { error = "Invalid homepage URL" });
  1067. if (!string.IsNullOrEmpty(logoUrl) && !logoUrl.IsValidUrl())
  1068. return Json(new { error = "Invalid logo URL" });
  1069. // Validate the code with the identity server
  1070. var result = await IdentityHelper.CreateClient(_config, User.Identity.Name, name, homepageUrl, logoUrl, callbackUrl, "openid", "role", "account-info", "security-info", "teknik-api.read", "teknik-api.write");
  1071. if (result.Success)
  1072. {
  1073. var client = (JObject)result.Data;
  1074. ClientViewModel model = new ClientViewModel();
  1075. model.Id = client["id"].ToString();
  1076. model.Name = name;
  1077. model.HomepageUrl = homepageUrl;
  1078. model.LogoUrl = logoUrl;
  1079. model.CallbackUrl = callbackUrl;
  1080. string renderedView = await RenderPartialViewToString(viewEngine, "~/Areas/User/Views/User/Settings/ClientView.cshtml", model);
  1081. return Json(new { result = true, clientId = client["id"], secret = client["secret"], html = renderedView });
  1082. }
  1083. return Json(new { error = result.Message });
  1084. }
  1085. catch (Exception ex)
  1086. {
  1087. return Json(new { error = ex.GetFullMessage(true) });
  1088. }
  1089. }
  1090. [HttpPost]
  1091. [ValidateAntiForgeryToken]
  1092. public async Task<IActionResult> GetClient(string clientId)
  1093. {
  1094. Client foundClient = await IdentityHelper.GetClient(_config, User.Identity.Name, clientId);
  1095. if (foundClient != null)
  1096. {
  1097. ClientViewModel model = new ClientViewModel()
  1098. {
  1099. Id = foundClient.ClientId,
  1100. Name = foundClient.ClientName,
  1101. HomepageUrl = foundClient.ClientUri,
  1102. LogoUrl = foundClient.LogoUri,
  1103. CallbackUrl = string.Join(',', foundClient.RedirectUris),
  1104. AllowedScopes = foundClient.AllowedScopes
  1105. };
  1106. return Json(new { result = true, client = model });
  1107. }
  1108. return new StatusCodeResult(StatusCodes.Status403Forbidden);
  1109. }
  1110. [HttpPost]
  1111. [ValidateAntiForgeryToken]
  1112. public async Task<IActionResult> EditClient(string clientId, string name, string homepageUrl, string logoUrl, string callbackUrl, [FromServices] ICompositeViewEngine viewEngine)
  1113. {
  1114. try
  1115. {
  1116. if (string.IsNullOrEmpty(name))
  1117. return Json(new { error = "You must enter a client name" });
  1118. if (string.IsNullOrEmpty(callbackUrl))
  1119. return Json(new { error = "You must enter an authorization callback URL" });
  1120. if (!callbackUrl.IsValidUrl())
  1121. return Json(new { error = "Invalid callback URL" });
  1122. if (!string.IsNullOrEmpty(homepageUrl) && !homepageUrl.IsValidUrl())
  1123. return Json(new { error = "Invalid homepage URL" });
  1124. if (!string.IsNullOrEmpty(logoUrl) && !logoUrl.IsValidUrl())
  1125. return Json(new { error = "Invalid logo URL" });
  1126. Client foundClient = await IdentityHelper.GetClient(_config, User.Identity.Name, clientId);
  1127. if (foundClient == null)
  1128. return Json(new { error = "Client does not exist" });
  1129. // Validate the code with the identity server
  1130. var result = await IdentityHelper.EditClient(_config, User.Identity.Name, clientId, name, homepageUrl, logoUrl, callbackUrl);
  1131. if (result.Success)
  1132. {
  1133. var client = (JObject)result.Data;
  1134. ClientViewModel model = new ClientViewModel();
  1135. model.Id = clientId;
  1136. model.Name = name;
  1137. model.HomepageUrl = homepageUrl;
  1138. model.LogoUrl = logoUrl;
  1139. model.CallbackUrl = callbackUrl;
  1140. string renderedView = await RenderPartialViewToString(viewEngine, "~/Areas/User/Views/User/Settings/ClientView.cshtml", model);
  1141. return Json(new { result = true, clientId = clientId, html = renderedView });
  1142. }
  1143. return Json(new { error = result.Message });
  1144. }
  1145. catch (Exception ex)
  1146. {
  1147. return Json(new { error = ex.GetFullMessage(true) });
  1148. }
  1149. }
  1150. [HttpPost]
  1151. [ValidateAntiForgeryToken]
  1152. public async Task<IActionResult> DeleteClient(string clientId)
  1153. {
  1154. try
  1155. {
  1156. // Validate the code with the identity server
  1157. var result = await IdentityHelper.DeleteClient(_config, clientId);
  1158. if (result.Success)
  1159. {
  1160. return Json(new { result = true });
  1161. }
  1162. return Json(new { error = result.Message });
  1163. }
  1164. catch (Exception ex)
  1165. {
  1166. return Json(new { error = ex.GetFullMessage(true) });
  1167. }
  1168. }
  1169. [HttpPost]
  1170. [ValidateAntiForgeryToken]
  1171. public IActionResult CreateInviteCodeLink(int inviteCodeId)
  1172. {
  1173. try
  1174. {
  1175. InviteCode code = _dbContext.InviteCodes.Where(c => c.InviteCodeId == inviteCodeId).FirstOrDefault();
  1176. if (code != null)
  1177. {
  1178. if (User.Identity.IsAuthenticated)
  1179. {
  1180. if (code.Owner.Username == User.Identity.Name)
  1181. {
  1182. return Json(new { result = Url.SubRouteUrl("account", "User.Register", new { inviteCode = code.Code }) });
  1183. }
  1184. }
  1185. return Json(new { error = "Invite Code not associated with this user" });
  1186. }
  1187. return Json(new { error = "Invalid Invite Code" });
  1188. }
  1189. catch (Exception ex)
  1190. {
  1191. return Json(new { error = ex.GetFullMessage(true) });
  1192. }
  1193. }
  1194. }
  1195. }