AdminController.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. using Newtonsoft.Json;
  7. using GreenTree.Nachtragsmanagement.Core.Authentication;
  8. using GreenTree.Nachtragsmanagement.Services.User;
  9. using GreenTree.Nachtragsmanagement.Web.Models.Admin.User;
  10. using GreenTree.Nachtragsmanagement.Core.Domain.User;
  11. using GreenTree.Nachtragsmanagement.Core;
  12. using GreenTree.Nachtragsmanagement.Core.Plugins;
  13. using GreenTree.Nachtragsmanagement.Web.Framework.Authorization;
  14. using GreenTree.Nachtragsmanagement.Services.Logging;
  15. using GreenTree.Nachtragsmanagement.Web.Models.Admin.Plugins;
  16. using GreenTree.Nachtragsmanagement.Web.Models.Admin.AppInfo;
  17. using System.Reflection;
  18. using System.Net;
  19. using System.IO;
  20. using GreenTree.Nachtragsmanagement.Services.Configuration;
  21. using GreenTree.Nachtragsmanagement.Web.Extensions;
  22. using System.IO.Compression;
  23. namespace GreenTree.Nachtragsmanagement.Web.Controllers
  24. {
  25. public class AdminController : Controller
  26. {
  27. private readonly IUserService _userService;
  28. private readonly IUserHelper _userHelper;
  29. private readonly IPluginFinder _pluginFinder;
  30. private readonly ILogger _logger;
  31. private readonly IWebHelper _webHelper;
  32. private readonly IConfigurationService _configurationService;
  33. public AdminController(
  34. IUserService userService,
  35. IUserHelper userHelper,
  36. IPluginFinder pluginFinder,
  37. ILogger logger,
  38. IWebHelper webHelper,
  39. IConfigurationService configurationService)
  40. {
  41. _userService = userService;
  42. _userHelper = userHelper;
  43. _pluginFinder = pluginFinder;
  44. _logger = logger;
  45. _webHelper = webHelper;
  46. _configurationService = configurationService;
  47. ViewData["AllRoles"] = _userService.GetAllRoles();
  48. ViewData["AllFunctions"] = _userService.GetAllFunctions();
  49. }
  50. #region Users
  51. /// <summary>
  52. /// Basic user view function
  53. /// </summary>
  54. [FunctionAuthorize(true, "Administration-Users")]
  55. public ActionResult ViewUsers()
  56. {
  57. var users = _userService.GetAllUsers();
  58. var userModels = users
  59. .Select(u => UserDataModel.FromUser(u, false))
  60. .ToList();
  61. return View("~/Views/Admin/Users/View.cshtml", userModels);
  62. }
  63. /// <summary>
  64. /// Get JSON data of specific user
  65. /// </summary>
  66. /// <param name="id">User id.</param>
  67. public ActionResult GetUser(int id = -1)
  68. {
  69. var user = _userService.GetUserById(id);
  70. if (user == null)
  71. return new JsonResult
  72. {
  73. Data = "notFound",
  74. JsonRequestBehavior = JsonRequestBehavior.AllowGet
  75. };
  76. var userModel = UserDataModel.FromUser(user, false);
  77. return new JsonResult
  78. {
  79. Data = JsonConvert.SerializeObject(userModel),
  80. JsonRequestBehavior = JsonRequestBehavior.AllowGet
  81. };
  82. }
  83. /// <summary>
  84. /// Partial edit for searching for users in ActiveDirectory
  85. /// </summary>
  86. /// <param name="searchValue">The text to be searched for.</param>
  87. [HttpPost]
  88. public ActionResult SearchUsers(string searchValue)
  89. {
  90. var users = _userService.SearchUsers(searchValue);
  91. return PartialView("~/Views/Admin/Users/_UserSearchPartial.cshtml", users);
  92. }
  93. /// <summary>
  94. /// Partial edit for selecting a specific user
  95. /// </summary>
  96. /// <param name="accountName">The user accountName.</param>
  97. [HttpPost]
  98. public ActionResult SelectUser(string accountName)
  99. {
  100. var user = _userService.SearchUsers(accountName)
  101. .FirstOrDefault();
  102. if (user == null)
  103. return new EmptyResult();
  104. return new JsonResult
  105. {
  106. Data = user
  107. };
  108. }
  109. /// <summary>
  110. /// Callback result for user grid
  111. /// </summary>
  112. /// <param name="scrollHeight">The height of the grid scrollable component.</param>
  113. public ActionResult PartialUsers(int scrollHeight = -1)
  114. {
  115. var users = _userService.GetAllUsers();
  116. var userModels = users
  117. .Select(u => UserDataModel.FromUser(u, false))
  118. .ToList();
  119. ViewData["ScrollHeight"] = scrollHeight;
  120. return PartialView("~/Views/Admin/Users/_UserGridPartial.cshtml", userModels);
  121. }
  122. /// <summary>
  123. /// Partial edit for editing of existing or for new user
  124. /// </summary>
  125. /// <param name="id">Id for existing user, otherweise -1.</param>
  126. public ActionResult EditUser(int id = -1)
  127. {
  128. var user = _userService.GetUserById(id);
  129. var userModel = UserDataModel.FromUser(user, true);
  130. return PartialView("~/Views/Admin/Users/_UserEditPartial.cshtml", userModel);
  131. }
  132. /// <summary>
  133. /// Partial edit result if ModelState is valid, otherwise simple JSON result for success
  134. /// </summary>
  135. /// <param name="userModel">User model to be saved.</param>
  136. [HttpPost, ValidateInput(false)]
  137. public ActionResult EditUser(UserDataModel userModel)
  138. {
  139. try
  140. {
  141. if (!ModelState.IsValid)
  142. {
  143. foreach (var role in userModel.RoleValues)
  144. userModel.RoleDescriptions.Add(
  145. ((IList<Role>)ViewData["AllRoles"])
  146. .First(r => r.Id == role).Description);
  147. return PartialView("~/Views/Admin/Users/_UserEditPartial.cshtml", userModel);
  148. }
  149. var selectedRoles = _userService.GetRolesByIds(userModel.RoleValues.ToArray());
  150. if (userModel.Id == -1)
  151. {
  152. var user = userModel.ToUser();
  153. user.SetRoles(selectedRoles);
  154. user.Password = StaticHelper.GetMD5Hash(userModel.Password);
  155. _userService.InsertUser(user);
  156. _logger.Entity(user, Core.Domain.Logging.LogEntityActivity.Insert, _userHelper.FromCookiesOrSession());
  157. }
  158. else
  159. {
  160. var user = _userService.GetUserById(userModel.Id);
  161. user.CustomNumber = userModel.CustomNumber;
  162. user.Forename = userModel.Forename;
  163. user.Lastname = userModel.Lastname;
  164. user.MailAddress = userModel.MailAddress;
  165. if (!String.IsNullOrEmpty(userModel.Password))
  166. user.Password = StaticHelper.GetMD5Hash(userModel.Password);
  167. user.SetRoles(selectedRoles);
  168. _userService.UpdateUser(user);
  169. _logger.Entity(user, Core.Domain.Logging.LogEntityActivity.Update, _userHelper.FromCookiesOrSession());
  170. }
  171. return new JsonResult
  172. {
  173. Data = "success"
  174. };
  175. }
  176. catch (Exception ex)
  177. {
  178. _logger.Error("Fehler bei Speicherung eines Benutzers.", ex, _userHelper.FromCookiesOrSession());
  179. return PartialView("~/Views/Shared/_PopupError.cshtml", ex);
  180. }
  181. }
  182. /// <summary>
  183. /// Simple JSON result for deleting a specific user
  184. /// </summary>
  185. /// <param name="id">User id.</param>
  186. [HttpPost]
  187. public ActionResult DeleteUser(int id)
  188. {
  189. try
  190. {
  191. var user = _userService.GetUserById(id);
  192. if (user != null)
  193. _userService.DeleteUser(user);
  194. _logger.Entity(user, Core.Domain.Logging.LogEntityActivity.Delete, _userHelper.FromCookiesOrSession());
  195. return new JsonResult
  196. {
  197. Data = "success"
  198. };
  199. }
  200. catch (Exception ex)
  201. {
  202. _logger.Error("Fehler bei Löschung eines Benutzers.", ex, _userHelper.FromCookiesOrSession());
  203. return PartialView("~/Views/Shared/_PopupError.cshtml", ex);
  204. }
  205. }
  206. #endregion
  207. #region Roles
  208. /// <summary>
  209. /// Basic role view function
  210. /// </summary>
  211. [FunctionAuthorize(true, "Administration-Roles")]
  212. public ActionResult ViewRoles()
  213. {
  214. var roles = _userService.GetAllRoles();
  215. var roleModels = roles
  216. .Select(r => RoleDataModel.FromRole(r, false))
  217. .ToList();
  218. return View("~/Views/Admin/Roles/View.cshtml", roleModels);
  219. }
  220. /// <summary>
  221. /// Get JSON data of specific role
  222. /// </summary>
  223. /// <param name="id">Role id.</param>
  224. public ActionResult GetRole(int id = -1)
  225. {
  226. var role = _userService.GetRoleById(id);
  227. if (role == null)
  228. return new JsonResult
  229. {
  230. Data = "notFound",
  231. JsonRequestBehavior = JsonRequestBehavior.AllowGet
  232. };
  233. var roleModel = RoleDataModel.FromRole(role, false);
  234. return new JsonResult
  235. {
  236. Data = JsonConvert.SerializeObject(roleModel),
  237. JsonRequestBehavior = JsonRequestBehavior.AllowGet
  238. };
  239. }
  240. /// <summary>
  241. /// Callback result for role grid
  242. /// </summary>
  243. /// <param name="scrollHeight">The height of the grid scrollable component.</param>
  244. public ActionResult PartialRoles(int scrollHeight = -1)
  245. {
  246. var roles = _userService.GetAllRoles();
  247. var roleModels = roles
  248. .Select(r => RoleDataModel.FromRole(r, false))
  249. .ToList();
  250. ViewData["ScrollHeight"] = scrollHeight;
  251. return PartialView("~/Views/Admin/Roles/_RoleGridPartial.cshtml", roleModels);
  252. }
  253. /// <summary>
  254. /// Partial edit for editing of existing or for new role
  255. /// </summary>
  256. /// <param name="id">Id for existing role, otherweise -1.</param>
  257. public ActionResult EditRole(int id = -1)
  258. {
  259. var role = _userService.GetRoleById(id);
  260. var roleModel = RoleDataModel.FromRole(role, true);
  261. return PartialView("~/Views/Admin/Roles/_RoleEditPartial.cshtml", roleModel);
  262. }
  263. /// <summary>
  264. /// Partial edit result if ModelState is valid, otherwise simple JSON result for success
  265. /// </summary>
  266. /// <param name="roleModel">Role model to be saved.</param>
  267. [HttpPost, ValidateInput(false)]
  268. public ActionResult EditRole(RoleDataModel roleModel)
  269. {
  270. try
  271. {
  272. if (!ModelState.IsValid)
  273. {
  274. foreach (var role in roleModel.FunctionValues)
  275. roleModel.FunctionDescriptions.Add(
  276. ((IList<Function>)ViewData["AllFunctions"])
  277. .First(r => r.Id == role).Description);
  278. return PartialView("~/Views/Admin/Roles/_RoleEditPartial.cshtml", roleModel);
  279. }
  280. var selectedFunctions = _userService.GetFunctionsByIds(roleModel.FunctionValues.ToArray());
  281. if (roleModel.Id == -1)
  282. {
  283. var role = roleModel.ToRole();
  284. role.SetFunctions(selectedFunctions);
  285. _userService.InsertRole(role);
  286. _logger.Entity(role, Core.Domain.Logging.LogEntityActivity.Insert, _userHelper.FromCookiesOrSession());
  287. }
  288. else
  289. {
  290. var role = _userService.GetRoleById(roleModel.Id);
  291. role.Description = roleModel.Description;
  292. role.Level = roleModel.Level;
  293. role.SetFunctions(selectedFunctions);
  294. _userService.UpdateRole(role);
  295. _logger.Entity(role, Core.Domain.Logging.LogEntityActivity.Update, _userHelper.FromCookiesOrSession());
  296. }
  297. return new JsonResult
  298. {
  299. Data = "success"
  300. };
  301. }
  302. catch (Exception ex)
  303. {
  304. _logger.Error("Fehler bei Speicherung einer Rolle.", ex, _userHelper.FromCookiesOrSession());
  305. return PartialView("~/Views/Shared/_PopupError.cshtml", ex);
  306. }
  307. }
  308. /// <summary>
  309. /// Simple JSON result for deleting a specific role
  310. /// </summary>
  311. /// <param name="id">Role id.</param>
  312. /// <param name="replaceId">Id of role which user get in place of deleting role.</param>
  313. [HttpPost]
  314. public ActionResult DeleteRole(int id, int replaceId)
  315. {
  316. try
  317. {
  318. var role = _userService.GetRoleById(id);
  319. var replaceRole = _userService.GetRoleById(replaceId);
  320. var roleUsers = _userService.GetUsersByRole(id);
  321. foreach (var user in roleUsers)
  322. {
  323. if (replaceId == -1)
  324. user.Roles.Remove(role);
  325. else
  326. user.Roles.Add(replaceRole);
  327. _userService.UpdateUser(user);
  328. }
  329. if (role != null)
  330. _userService.DeleteRole(role);
  331. _logger.Entity(role, Core.Domain.Logging.LogEntityActivity.Delete, _userHelper.FromCookiesOrSession());
  332. return new JsonResult
  333. {
  334. Data = "success"
  335. };
  336. }
  337. catch (Exception ex)
  338. {
  339. _logger.Error("Fehler bei Löschung einer Rolle.", ex, _userHelper.FromCookiesOrSession());
  340. return PartialView("~/Views/Shared/_PopupError.cshtml", ex);
  341. }
  342. }
  343. #endregion
  344. #region Plugins
  345. /// <summary>
  346. /// Basic plugin view function
  347. /// </summary>
  348. [FunctionAuthorize(true, "Administration-Plugins")]
  349. public ActionResult ViewPlugins()
  350. {
  351. var plugins = _pluginFinder.GetPlugins<IPlugin>(LoadPluginsMode.All);
  352. var pluginModels = plugins
  353. .Select(p => PluginDataModel.FromPluginDesciptor(p.PluginDescriptor, _webHelper))
  354. .ToList();
  355. return View("~/Views/Admin/Plugins/View.cshtml", pluginModels);
  356. }
  357. /// <summary>
  358. /// Callback result for plugin grid
  359. /// </summary>
  360. /// <param name="scrollHeight">The height of the grid scrollable component.</param>
  361. public ActionResult PartialPlugins(int scrollHeight = -1)
  362. {
  363. var plugins = _pluginFinder.GetPlugins<IPlugin>(LoadPluginsMode.All);
  364. var pluginModels = plugins
  365. .Select(p => PluginDataModel.FromPluginDesciptor(p.PluginDescriptor, _webHelper))
  366. .ToList();
  367. ViewData["ScrollHeight"] = scrollHeight;
  368. return View("~/Views/Admin/Plugins/_PluginsGridPartial.cshtml", pluginModels);
  369. }
  370. /// <summary>
  371. /// Installs a plugin
  372. /// </summary>
  373. /// <param name="pluginName">SystemName of plugin.</param>
  374. [HttpPost]
  375. public ActionResult InstallPlugin(string pluginName)
  376. {
  377. try
  378. {
  379. var pluginDescriptor = _pluginFinder.GetPluginDescriptorBySystemName(pluginName, LoadPluginsMode.All);
  380. if (pluginDescriptor == null)
  381. return RedirectToAction("Plugins");
  382. if (pluginDescriptor.Installed)
  383. return RedirectToAction("Plugins");
  384. pluginDescriptor.Instance().Install();
  385. _logger.Information(String.Format("Plugin \"{0}\" erfolgreich installiert.", pluginName));
  386. _webHelper.RestartAppDomain();
  387. return new JsonResult
  388. {
  389. Data = "success"
  390. };
  391. }
  392. catch (Exception ex)
  393. {
  394. _logger.Error(
  395. String.Format("Fehler bei der Installation des Plugin \"{0}\".", pluginName), ex);
  396. return PartialView("~/Views/Shared/_PopupError.cshtml", ex);
  397. }
  398. }
  399. /// <summary>
  400. /// Uninstalls a plugin
  401. /// </summary>
  402. /// <param name="pluginName">SystemName of plugin.</param>
  403. [HttpPost]
  404. public ActionResult UninstallPlugin(string pluginName)
  405. {
  406. try
  407. {
  408. var pluginDescriptor = _pluginFinder.GetPluginDescriptorBySystemName(pluginName, LoadPluginsMode.All);
  409. if (pluginDescriptor == null)
  410. return RedirectToAction("Plugins");
  411. if (!pluginDescriptor.Installed)
  412. return RedirectToAction("Plugins");
  413. pluginDescriptor.Instance().Uninstall();
  414. _logger.Information(String.Format("Plugin \"{0}\" erfolgreich deinstalliert.", pluginName));
  415. _webHelper.RestartAppDomain();
  416. return new JsonResult
  417. {
  418. Data = "success"
  419. };
  420. }
  421. catch (Exception ex)
  422. {
  423. _logger.Error(
  424. String.Format("Fehler bei der Installation des Plugin \"{0}\".", pluginName), ex);
  425. return PartialView("~/Views/Shared/_PopupError.cshtml", ex);
  426. }
  427. }
  428. #endregion
  429. #region AppInfo
  430. /// <summary>
  431. /// Basic appInfo view function
  432. /// </summary>
  433. [FunctionAuthorize(true, "Administration-AppInfo")]
  434. public ActionResult ViewAppInfo()
  435. {
  436. var model = new AppInfoDataModel
  437. {
  438. BaseDirectory = AppDomain.CurrentDomain.BaseDirectory,
  439. AspNetVersion = Environment.Version.ToString(),
  440. OperatingSystem = Environment.OSVersion.VersionString,
  441. Is64BitOs = Environment.Is64BitOperatingSystem,
  442. IsUpdate = false
  443. };
  444. model.GetAssemblies();
  445. return View("~/Views/Admin/AppInfo/View.cshtml", model);
  446. }
  447. /// <summary>
  448. /// Basic appInfo view function
  449. /// </summary>
  450. public ActionResult ViewUpdateSuccess()
  451. {
  452. var model = new AppInfoDataModel
  453. {
  454. BaseDirectory = AppDomain.CurrentDomain.BaseDirectory,
  455. IsUpdate = true
  456. };
  457. model.GetAssemblies();
  458. return View("~/Views/Admin/AppInfo/View.cshtml", model);
  459. }
  460. /// <summary>
  461. /// Update check
  462. /// </summary>
  463. public ActionResult PartialCheckUpdate()
  464. {
  465. _logger.Information("Updateüberprüfung gestartet.");
  466. try
  467. {
  468. var model = new AppUpdateDataModel
  469. {
  470. Package = "GreenTree.Nachtragsmanagement",
  471. CurrentVersion = AppendixVersion.CurrentVersion
  472. };
  473. var webResult = String.Empty;
  474. using (var wc = new WebClient())
  475. {
  476. wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
  477. wc.Encoding = System.Text.Encoding.UTF8;
  478. var webData = String.Format("Package={0}&CurrentVersion={1}", model.Package, model.CurrentVersion);
  479. webResult = wc.UploadString(_configurationService.GetCurrentConfiguration().CheckUpdateUrl, webData);
  480. }
  481. var jsonResult = JsonConvert.DeserializeObject<JsonResult>(webResult);
  482. var result = JsonConvert.DeserializeObject<AppUpdateDataModel>(jsonResult.Data.ToString());
  483. if (result.IsUpdateAvailable)
  484. _logger.Information(
  485. String.Format(
  486. "Es ist ein Update verfügbar (Aktuell: {0} - Neu: {1})!", AppendixVersion.CurrentVersion, result.UpdateVersion));
  487. else
  488. _logger.Information("Es kein Update verfügbar!");
  489. if (result.IsUpdateAvailable)
  490. return PartialView("~/Views/Admin/AppInfo/_UpdateNotesPartial.cshtml", result);
  491. else
  492. return PartialView("~/Views/Admin/AppInfo/_UpdateUnnecessaryPartial.cshtml");
  493. }
  494. catch (Exception ex)
  495. {
  496. _logger.Error("Fehler bei der Überprüfung eines Updates", ex);
  497. throw;
  498. }
  499. }
  500. /// <summary>
  501. /// Update check
  502. /// </summary>
  503. [HttpPost]
  504. public ActionResult Update()
  505. {
  506. _logger.Information("Update gestartet.");
  507. try
  508. {
  509. var model = new AppUpdateDataModel
  510. {
  511. Package = "GreenTree.Nachtragsmanagement",
  512. CurrentVersion = AppendixVersion.CurrentVersion
  513. };
  514. var currentConfig = _configurationService.GetCurrentConfiguration();
  515. AppUpdateDataModel result;
  516. string storePath;
  517. using (var wc = new WebClient())
  518. {
  519. wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
  520. var webData = String.Format("Package={0}&CurrentVersion={1}", model.Package, model.CurrentVersion);
  521. var webResult = wc.UploadString(currentConfig.CheckUpdateUrl, webData);
  522. var jsonResult = JsonConvert.DeserializeObject<JsonResult>(webResult);
  523. result = JsonConvert.DeserializeObject<AppUpdateDataModel>(jsonResult.Data.ToString());
  524. storePath = Path.Combine(Server.MapPath(currentConfig.UpdateStorePath), result.PackageFilename);
  525. if (System.IO.File.Exists(storePath))
  526. System.IO.File.Delete(storePath);
  527. wc.DownloadFile(result.PackagePath, storePath);
  528. }
  529. var hash = HashHelper.GetFileMd5(storePath);
  530. if (hash != result.PackageMd5Hash)
  531. return null;
  532. var archive = ZipFile.Open(storePath, ZipArchiveMode.Read);
  533. var applicationPath = Server.MapPath("~/");
  534. archive.ExtractToDirectory(applicationPath, true);
  535. _logger.Information("Update erfolgreich durchgeführt - Anwendung wird neu gestartet!");
  536. _webHelper.RestartAppDomain(true, "~/admin/viewupdatesuccess");
  537. return new JsonResult
  538. {
  539. Data = "success"
  540. };
  541. }
  542. catch (Exception ex)
  543. {
  544. _logger.Error("Fehler bei der Durchführung eines Updates", ex);
  545. throw;
  546. }
  547. }
  548. #endregion
  549. }
  550. }