AdminController.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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. namespace GreenTree.Nachtragsmanagement.Web.Controllers
  22. {
  23. public class AdminController : Controller
  24. {
  25. private readonly IUserService _userService;
  26. private readonly IUserHelper _userHelper;
  27. private readonly IPluginFinder _pluginFinder;
  28. private readonly ILogger _logger;
  29. private readonly IWebHelper _webHelper;
  30. private readonly IConfigurationService _configurationService;
  31. public AdminController(
  32. IUserService userService,
  33. IUserHelper userHelper,
  34. IPluginFinder pluginFinder,
  35. ILogger logger,
  36. IWebHelper webHelper,
  37. IConfigurationService configurationService)
  38. {
  39. _userService = userService;
  40. _userHelper = userHelper;
  41. _pluginFinder = pluginFinder;
  42. _logger = logger;
  43. _webHelper = webHelper;
  44. _configurationService = configurationService;
  45. ViewData["AllRoles"] = _userService.GetAllRoles();
  46. ViewData["AllFunctions"] = _userService.GetAllFunctions();
  47. }
  48. #region Users
  49. /// <summary>
  50. /// Basic user view function
  51. /// </summary>
  52. [FunctionAuthorize(true, "Administration-Users")]
  53. public ActionResult ViewUsers()
  54. {
  55. var users = _userService.GetAllUsers();
  56. var userModels = users
  57. .Select(u => UserDataModel.FromUser(u, false))
  58. .ToList();
  59. return View("~/Views/Admin/Users/View.cshtml", userModels);
  60. }
  61. /// <summary>
  62. /// Get JSON data of specific user
  63. /// </summary>
  64. /// <param name="id">User id.</param>
  65. public ActionResult GetUser(int id = -1)
  66. {
  67. var user = _userService.GetUserById(id);
  68. if (user == null)
  69. return new JsonResult
  70. {
  71. Data = "notFound",
  72. JsonRequestBehavior = JsonRequestBehavior.AllowGet
  73. };
  74. var userModel = UserDataModel.FromUser(user, false);
  75. return new JsonResult
  76. {
  77. Data = JsonConvert.SerializeObject(userModel),
  78. JsonRequestBehavior = JsonRequestBehavior.AllowGet
  79. };
  80. }
  81. /// <summary>
  82. /// Callback result for user grid
  83. /// </summary>
  84. /// <param name="scrollHeight">The height of the grid scrollable component.</param>
  85. public ActionResult PartialUsers(int scrollHeight = -1)
  86. {
  87. var users = _userService.GetAllUsers();
  88. var userModels = users
  89. .Select(u => UserDataModel.FromUser(u, false))
  90. .ToList();
  91. ViewData["ScrollHeight"] = scrollHeight;
  92. return PartialView("~/Views/Admin/Users/_UserGridPartial.cshtml", userModels);
  93. }
  94. /// <summary>
  95. /// Partial edit for editing of existing or for new user
  96. /// </summary>
  97. /// <param name="id">Id for existing user, otherweise -1.</param>
  98. public ActionResult EditUser(int id = -1)
  99. {
  100. var user = _userService.GetUserById(id);
  101. var userModel = UserDataModel.FromUser(user, true);
  102. return PartialView("~/Views/Admin/Users/_UserEditPartial.cshtml", userModel);
  103. }
  104. /// <summary>
  105. /// Partial edit result if ModelState is valid, otherwise simple JSON result for success
  106. /// </summary>
  107. /// <param name="userModel">User model to be saved.</param>
  108. [HttpPost, ValidateInput(false)]
  109. public ActionResult EditUser(UserDataModel userModel)
  110. {
  111. try
  112. {
  113. if (!ModelState.IsValid)
  114. {
  115. foreach (var role in userModel.RoleValues)
  116. userModel.RoleDescriptions.Add(
  117. ((IList<Role>)ViewData["AllRoles"])
  118. .First(r => r.Id == role).Description);
  119. return PartialView("~/Views/Admin/Users/_UserEditPartial.cshtml", userModel);
  120. }
  121. var selectedRoles = _userService.GetRolesByIds(userModel.RoleValues.ToArray());
  122. if (userModel.Id == -1)
  123. {
  124. var user = userModel.ToUser();
  125. user.SetRoles(selectedRoles);
  126. user.Password = StaticHelper.GetMD5Hash(userModel.Password);
  127. _userService.InsertUser(user);
  128. _logger.Entity(user, Core.Domain.Logging.LogEntityActivity.Insert, _userHelper.FromCookiesOrSession());
  129. }
  130. else
  131. {
  132. var user = _userService.GetUserById(userModel.Id);
  133. user.CustomNumber = userModel.CustomNumber;
  134. user.Forename = userModel.Forename;
  135. user.Lastname = userModel.Lastname;
  136. user.MailAddress = userModel.MailAddress;
  137. if (!String.IsNullOrEmpty(userModel.Password))
  138. user.Password = StaticHelper.GetMD5Hash(userModel.Password);
  139. user.SetRoles(selectedRoles);
  140. _userService.UpdateUser(user);
  141. _logger.Entity(user, Core.Domain.Logging.LogEntityActivity.Update, _userHelper.FromCookiesOrSession());
  142. }
  143. return new JsonResult
  144. {
  145. Data = "success"
  146. };
  147. }
  148. catch (Exception ex)
  149. {
  150. _logger.Error("Fehler bei Speicherung eines Benutzers.", ex, _userHelper.FromCookiesOrSession());
  151. return PartialView("~/Views/Shared/_PopupError.cshtml", ex);
  152. }
  153. }
  154. /// <summary>
  155. /// Simple JSON result for deleting a specific user
  156. /// </summary>
  157. /// <param name="id">User id.</param>
  158. [HttpPost]
  159. public ActionResult DeleteUser(int id)
  160. {
  161. try
  162. {
  163. var user = _userService.GetUserById(id);
  164. if (user != null)
  165. _userService.DeleteUser(user);
  166. _logger.Entity(user, Core.Domain.Logging.LogEntityActivity.Delete, _userHelper.FromCookiesOrSession());
  167. return new JsonResult
  168. {
  169. Data = "success"
  170. };
  171. }
  172. catch (Exception ex)
  173. {
  174. _logger.Error("Fehler bei Löschung eines Benutzers.", ex, _userHelper.FromCookiesOrSession());
  175. return PartialView("~/Views/Shared/_PopupError.cshtml", ex);
  176. }
  177. }
  178. #endregion
  179. #region Roles
  180. /// <summary>
  181. /// Basic role view function
  182. /// </summary>
  183. [FunctionAuthorize(true, "Administration-Roles")]
  184. public ActionResult ViewRoles()
  185. {
  186. var roles = _userService.GetAllRoles();
  187. var roleModels = roles
  188. .Select(r => RoleDataModel.FromRole(r, false))
  189. .ToList();
  190. return View("~/Views/Admin/Roles/View.cshtml", roleModels);
  191. }
  192. /// <summary>
  193. /// Get JSON data of specific role
  194. /// </summary>
  195. /// <param name="id">Role id.</param>
  196. public ActionResult GetRole(int id = -1)
  197. {
  198. var role = _userService.GetRoleById(id);
  199. if (role == null)
  200. return new JsonResult
  201. {
  202. Data = "notFound",
  203. JsonRequestBehavior = JsonRequestBehavior.AllowGet
  204. };
  205. var roleModel = RoleDataModel.FromRole(role, false);
  206. return new JsonResult
  207. {
  208. Data = JsonConvert.SerializeObject(roleModel),
  209. JsonRequestBehavior = JsonRequestBehavior.AllowGet
  210. };
  211. }
  212. /// <summary>
  213. /// Callback result for role grid
  214. /// </summary>
  215. /// <param name="scrollHeight">The height of the grid scrollable component.</param>
  216. public ActionResult PartialRoles(int scrollHeight = -1)
  217. {
  218. var roles = _userService.GetAllRoles();
  219. var roleModels = roles
  220. .Select(r => RoleDataModel.FromRole(r, false))
  221. .ToList();
  222. ViewData["ScrollHeight"] = scrollHeight;
  223. return PartialView("~/Views/Admin/Roles/_RoleGridPartial.cshtml", roleModels);
  224. }
  225. /// <summary>
  226. /// Partial edit for editing of existing or for new role
  227. /// </summary>
  228. /// <param name="id">Id for existing role, otherweise -1.</param>
  229. public ActionResult EditRole(int id = -1)
  230. {
  231. var role = _userService.GetRoleById(id);
  232. var roleModel = RoleDataModel.FromRole(role, true);
  233. return PartialView("~/Views/Admin/Roles/_RoleEditPartial.cshtml", roleModel);
  234. }
  235. /// <summary>
  236. /// Partial edit result if ModelState is valid, otherwise simple JSON result for success
  237. /// </summary>
  238. /// <param name="roleModel">Role model to be saved.</param>
  239. [HttpPost, ValidateInput(false)]
  240. public ActionResult EditRole(RoleDataModel roleModel)
  241. {
  242. try
  243. {
  244. if (!ModelState.IsValid)
  245. {
  246. foreach (var role in roleModel.FunctionValues)
  247. roleModel.FunctionDescriptions.Add(
  248. ((IList<Function>)ViewData["AllFunctions"])
  249. .First(r => r.Id == role).Description);
  250. return PartialView("~/Views/Admin/Roles/_RoleEditPartial.cshtml", roleModel);
  251. }
  252. var selectedFunctions = _userService.GetFunctionsByIds(roleModel.FunctionValues.ToArray());
  253. if (roleModel.Id == -1)
  254. {
  255. var role = roleModel.ToRole();
  256. role.SetFunctions(selectedFunctions);
  257. _userService.InsertRole(role);
  258. _logger.Entity(role, Core.Domain.Logging.LogEntityActivity.Insert, _userHelper.FromCookiesOrSession());
  259. }
  260. else
  261. {
  262. var role = _userService.GetRoleById(roleModel.Id);
  263. role.Description = roleModel.Description;
  264. role.Level = roleModel.Level;
  265. role.SetFunctions(selectedFunctions);
  266. _userService.UpdateRole(role);
  267. _logger.Entity(role, Core.Domain.Logging.LogEntityActivity.Update, _userHelper.FromCookiesOrSession());
  268. }
  269. return new JsonResult
  270. {
  271. Data = "success"
  272. };
  273. }
  274. catch (Exception ex)
  275. {
  276. _logger.Error("Fehler bei Speicherung einer Rolle.", ex, _userHelper.FromCookiesOrSession());
  277. return PartialView("~/Views/Shared/_PopupError.cshtml", ex);
  278. }
  279. }
  280. /// <summary>
  281. /// Simple JSON result for deleting a specific role
  282. /// </summary>
  283. /// <param name="id">Role id.</param>
  284. /// <param name="replaceId">Id of role which user get in place of deleting role.</param>
  285. [HttpPost]
  286. public ActionResult DeleteRole(int id, int replaceId)
  287. {
  288. try
  289. {
  290. var role = _userService.GetRoleById(id);
  291. var replaceRole = _userService.GetRoleById(replaceId);
  292. var roleUsers = _userService.GetUsersByRole(id);
  293. foreach (var user in roleUsers)
  294. {
  295. if (replaceId == -1)
  296. user.Roles.Remove(role);
  297. else
  298. user.Roles.Add(replaceRole);
  299. _userService.UpdateUser(user);
  300. }
  301. if (role != null)
  302. _userService.DeleteRole(role);
  303. _logger.Entity(role, Core.Domain.Logging.LogEntityActivity.Delete, _userHelper.FromCookiesOrSession());
  304. return new JsonResult
  305. {
  306. Data = "success"
  307. };
  308. }
  309. catch (Exception ex)
  310. {
  311. _logger.Error("Fehler bei Löschung einer Rolle.", ex, _userHelper.FromCookiesOrSession());
  312. return PartialView("~/Views/Shared/_PopupError.cshtml", ex);
  313. }
  314. }
  315. #endregion
  316. #region Plugins
  317. /// <summary>
  318. /// Basic plugin view function
  319. /// </summary>
  320. public ActionResult ViewPlugins()
  321. {
  322. var plugins = _pluginFinder.GetPlugins<IPlugin>(LoadPluginsMode.All);
  323. var pluginModels = plugins
  324. .Select(p => PluginDataModel.FromPluginDesciptor(p.PluginDescriptor, _webHelper))
  325. .ToList();
  326. return View("~/Views/Admin/Plugins/View.cshtml", pluginModels);
  327. }
  328. /// <summary>
  329. /// Callback result for plugin grid
  330. /// </summary>
  331. /// <param name="scrollHeight">The height of the grid scrollable component.</param>
  332. public ActionResult PartialPlugins(int scrollHeight = -1)
  333. {
  334. var plugins = _pluginFinder.GetPlugins<IPlugin>(LoadPluginsMode.All);
  335. var pluginModels = plugins
  336. .Select(p => PluginDataModel.FromPluginDesciptor(p.PluginDescriptor, _webHelper))
  337. .ToList();
  338. ViewData["ScrollHeight"] = scrollHeight;
  339. return View("~/Views/Admin/Plugins/_PluginsGridPartial.cshtml", pluginModels);
  340. }
  341. /// <summary>
  342. /// Installs a plugin
  343. /// </summary>
  344. /// <param name="pluginName">SystemName of plugin.</param>
  345. [HttpPost]
  346. public ActionResult InstallPlugin(string pluginName)
  347. {
  348. try
  349. {
  350. var pluginDescriptor = _pluginFinder.GetPluginDescriptorBySystemName(pluginName, LoadPluginsMode.All);
  351. if (pluginDescriptor == null)
  352. return RedirectToAction("Plugins");
  353. if (pluginDescriptor.Installed)
  354. return RedirectToAction("Plugins");
  355. pluginDescriptor.Instance().Install();
  356. _logger.Information(String.Format("Plugin \"{0}\" erfolgreich installiert.", pluginName));
  357. _webHelper.RestartAppDomain();
  358. return new JsonResult
  359. {
  360. Data = "success"
  361. };
  362. }
  363. catch (Exception ex)
  364. {
  365. _logger.Error(
  366. String.Format("Fehler bei der Installation des Plugin \"{0}\".", pluginName), ex);
  367. return PartialView("~/Views/Shared/_PopupError.cshtml", ex);
  368. }
  369. }
  370. /// <summary>
  371. /// Uninstalls a plugin
  372. /// </summary>
  373. /// <param name="pluginName">SystemName of plugin.</param>
  374. [HttpPost]
  375. public ActionResult UninstallPlugin(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().Uninstall();
  385. _logger.Information(String.Format("Plugin \"{0}\" erfolgreich deinstalliert.", 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. #endregion
  400. #region AppInfo
  401. /// <summary>
  402. /// Basic appInfo view function
  403. /// </summary>
  404. public ActionResult ViewAppInfo()
  405. {
  406. var assemblies = AppDomain.CurrentDomain.GetAssemblies()
  407. .Select(a => new AssemblyDataModel
  408. {
  409. Name = a.GetName().Name,
  410. Version = a.GetName().Version.ToString(),
  411. Manufacturer =
  412. a.GetCustomAttributes<AssemblyCompanyAttribute>().Any()
  413. ? a.GetCustomAttributes<AssemblyCompanyAttribute>()
  414. .FirstOrDefault().Company
  415. : "Unbekannt"
  416. })
  417. .OrderBy(a => a.Manufacturer)
  418. .ThenBy(a => a.Name)
  419. .ToArray();
  420. var model = new AppInfoDataModel
  421. {
  422. Assemblies = assemblies,
  423. BaseDirectory = AppDomain.CurrentDomain.BaseDirectory
  424. };
  425. return View("~/Views/Admin/AppInfo/View.cshtml", model);
  426. }
  427. /// <summary>
  428. /// Update check
  429. /// </summary>
  430. [HttpPost]
  431. public ActionResult CheckUpdate()
  432. {
  433. var model = new AppUpdateDataModel
  434. {
  435. Package = "GreenTree.Nachtragsmanagement",
  436. CurrentVersion = AppendixVersion.CurrentVersion
  437. };
  438. var wc = new WebClient();
  439. wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
  440. var webData = String.Format("Package={0}&CurrentVersion={1}", model.Package, model.CurrentVersion);
  441. var webResult = wc.UploadString(_configurationService.GetCurrentConfiguration().CheckUpdateUrl, webData);
  442. var jsonResult = JsonConvert.DeserializeObject<JsonResult>(webResult);
  443. var result = JsonConvert.DeserializeObject<AppUpdateDataModel>(jsonResult.Data.ToString());
  444. return new JsonResult
  445. {
  446. Data = result
  447. };
  448. }
  449. #endregion
  450. }
  451. }