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 55KB

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