AdminController.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  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. public ActionResult ViewPlugins()
  349. {
  350. var plugins = _pluginFinder.GetPlugins<IPlugin>(LoadPluginsMode.All);
  351. var pluginModels = plugins
  352. .Select(p => PluginDataModel.FromPluginDesciptor(p.PluginDescriptor, _webHelper))
  353. .ToList();
  354. return View("~/Views/Admin/Plugins/View.cshtml", pluginModels);
  355. }
  356. /// <summary>
  357. /// Callback result for plugin grid
  358. /// </summary>
  359. /// <param name="scrollHeight">The height of the grid scrollable component.</param>
  360. public ActionResult PartialPlugins(int scrollHeight = -1)
  361. {
  362. var plugins = _pluginFinder.GetPlugins<IPlugin>(LoadPluginsMode.All);
  363. var pluginModels = plugins
  364. .Select(p => PluginDataModel.FromPluginDesciptor(p.PluginDescriptor, _webHelper))
  365. .ToList();
  366. ViewData["ScrollHeight"] = scrollHeight;
  367. return View("~/Views/Admin/Plugins/_PluginsGridPartial.cshtml", pluginModels);
  368. }
  369. /// <summary>
  370. /// Installs a plugin
  371. /// </summary>
  372. /// <param name="pluginName">SystemName of plugin.</param>
  373. [HttpPost]
  374. public ActionResult InstallPlugin(string pluginName)
  375. {
  376. try
  377. {
  378. var pluginDescriptor = _pluginFinder.GetPluginDescriptorBySystemName(pluginName, LoadPluginsMode.All);
  379. if (pluginDescriptor == null)
  380. return RedirectToAction("Plugins");
  381. if (pluginDescriptor.Installed)
  382. return RedirectToAction("Plugins");
  383. pluginDescriptor.Instance().Install();
  384. _logger.Information(String.Format("Plugin \"{0}\" erfolgreich installiert.", pluginName));
  385. _webHelper.RestartAppDomain();
  386. return new JsonResult
  387. {
  388. Data = "success"
  389. };
  390. }
  391. catch (Exception ex)
  392. {
  393. _logger.Error(
  394. String.Format("Fehler bei der Installation des Plugin \"{0}\".", pluginName), ex);
  395. return PartialView("~/Views/Shared/_PopupError.cshtml", ex);
  396. }
  397. }
  398. /// <summary>
  399. /// Uninstalls a plugin
  400. /// </summary>
  401. /// <param name="pluginName">SystemName of plugin.</param>
  402. [HttpPost]
  403. public ActionResult UninstallPlugin(string pluginName)
  404. {
  405. try
  406. {
  407. var pluginDescriptor = _pluginFinder.GetPluginDescriptorBySystemName(pluginName, LoadPluginsMode.All);
  408. if (pluginDescriptor == null)
  409. return RedirectToAction("Plugins");
  410. if (!pluginDescriptor.Installed)
  411. return RedirectToAction("Plugins");
  412. pluginDescriptor.Instance().Uninstall();
  413. _logger.Information(String.Format("Plugin \"{0}\" erfolgreich deinstalliert.", pluginName));
  414. _webHelper.RestartAppDomain();
  415. return new JsonResult
  416. {
  417. Data = "success"
  418. };
  419. }
  420. catch (Exception ex)
  421. {
  422. _logger.Error(
  423. String.Format("Fehler bei der Installation des Plugin \"{0}\".", pluginName), ex);
  424. return PartialView("~/Views/Shared/_PopupError.cshtml", ex);
  425. }
  426. }
  427. #endregion
  428. #region AppInfo
  429. /// <summary>
  430. /// Basic appInfo view function
  431. /// </summary>
  432. public ActionResult ViewAppInfo()
  433. {
  434. var model = new AppInfoDataModel
  435. {
  436. BaseDirectory = AppDomain.CurrentDomain.BaseDirectory,
  437. IsUpdate = false
  438. };
  439. model.GetAssemblies();
  440. return View("~/Views/Admin/AppInfo/View.cshtml", model);
  441. }
  442. /// <summary>
  443. /// Basic appInfo view function
  444. /// </summary>
  445. public ActionResult ViewUpdateSuccess()
  446. {
  447. var model = new AppInfoDataModel
  448. {
  449. BaseDirectory = AppDomain.CurrentDomain.BaseDirectory,
  450. IsUpdate = true
  451. };
  452. model.GetAssemblies();
  453. return View("~/Views/Admin/AppInfo/View.cshtml", model);
  454. }
  455. /// <summary>
  456. /// Update check
  457. /// </summary>
  458. public ActionResult PartialCheckUpdate()
  459. {
  460. _logger.Information("Updateüberprüfung gestartet.");
  461. try
  462. {
  463. var model = new AppUpdateDataModel
  464. {
  465. Package = "GreenTree.Nachtragsmanagement",
  466. CurrentVersion = AppendixVersion.CurrentVersion
  467. };
  468. var webResult = String.Empty;
  469. using (var wc = new WebClient())
  470. {
  471. wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
  472. wc.Encoding = System.Text.Encoding.UTF8;
  473. var webData = String.Format("Package={0}&CurrentVersion={1}", model.Package, model.CurrentVersion);
  474. webResult = wc.UploadString(_configurationService.GetCurrentConfiguration().CheckUpdateUrl, webData);
  475. }
  476. var jsonResult = JsonConvert.DeserializeObject<JsonResult>(webResult);
  477. var result = JsonConvert.DeserializeObject<AppUpdateDataModel>(jsonResult.Data.ToString());
  478. if (result.IsUpdateAvailable)
  479. _logger.Information(
  480. String.Format(
  481. "Es ist ein Update verfügbar (Aktuell: {0} - Neu: {1})!", AppendixVersion.CurrentVersion, result.UpdateVersion));
  482. else
  483. _logger.Information("Es kein Update verfügbar!");
  484. if (result.IsUpdateAvailable)
  485. return PartialView("~/Views/Admin/AppInfo/_UpdateNotesPartial.cshtml", result);
  486. else
  487. return PartialView("~/Views/Admin/AppInfo/_UpdateUnnecessaryPartial.cshtml");
  488. }
  489. catch (Exception ex)
  490. {
  491. _logger.Error("Fehler bei der Überprüfung eines Updates", ex);
  492. throw;
  493. }
  494. }
  495. /// <summary>
  496. /// Update check
  497. /// </summary>
  498. [HttpPost]
  499. public ActionResult Update()
  500. {
  501. _logger.Information("Update gestartet.");
  502. try
  503. {
  504. var model = new AppUpdateDataModel
  505. {
  506. Package = "GreenTree.Nachtragsmanagement",
  507. CurrentVersion = AppendixVersion.CurrentVersion
  508. };
  509. var currentConfig = _configurationService.GetCurrentConfiguration();
  510. AppUpdateDataModel result;
  511. string storePath;
  512. using (var wc = new WebClient())
  513. {
  514. wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
  515. var webData = String.Format("Package={0}&CurrentVersion={1}", model.Package, model.CurrentVersion);
  516. var webResult = wc.UploadString(currentConfig.CheckUpdateUrl, webData);
  517. var jsonResult = JsonConvert.DeserializeObject<JsonResult>(webResult);
  518. result = JsonConvert.DeserializeObject<AppUpdateDataModel>(jsonResult.Data.ToString());
  519. storePath = Path.Combine(Server.MapPath(currentConfig.UpdateStorePath), result.PackageFilename);
  520. if (System.IO.File.Exists(storePath))
  521. System.IO.File.Delete(storePath);
  522. wc.DownloadFile(result.PackagePath, storePath);
  523. }
  524. var hash = HashHelper.GetFileMd5(storePath);
  525. if (hash != result.PackageMd5Hash)
  526. return null;
  527. var archive = ZipFile.Open(storePath, ZipArchiveMode.Read);
  528. var applicationPath = Server.MapPath("~/");
  529. archive.ExtractToDirectory(applicationPath, true);
  530. _logger.Information("Update erfolgreich durchgeführt - Anwendung wird neu gestartet!");
  531. _webHelper.RestartAppDomain(true, "~/admin/viewupdatesuccess");
  532. return new JsonResult
  533. {
  534. Data = "success"
  535. };
  536. }
  537. catch (Exception ex)
  538. {
  539. _logger.Error("Fehler bei der Durchführung eines Updates", ex);
  540. throw;
  541. }
  542. }
  543. #endregion
  544. }
  545. }