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.

UserController.cs 57KB

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