AdminController.cs 18 KB

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