AdminController.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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. namespace GreenTree.Nachtragsmanagement.Web.Controllers
  16. {
  17. public class AdminController : Controller
  18. {
  19. private readonly IUserService _userService;
  20. private readonly IUserHelper _userHelper;
  21. private readonly IPluginFinder _pluginFinder;
  22. private readonly ILogger _logger;
  23. public AdminController(
  24. IUserService userService,
  25. IUserHelper userHelper,
  26. IPluginFinder pluginFinder,
  27. ILogger logger)
  28. {
  29. _userService = userService;
  30. _userHelper = userHelper;
  31. _pluginFinder = pluginFinder;
  32. _logger = logger;
  33. ViewData["AllRoles"] = _userService.GetAllRoles();
  34. ViewData["AllFunctions"] = _userService.GetAllFunctions();
  35. }
  36. #region Users
  37. /// <summary>
  38. /// Basic user view function
  39. /// </summary>
  40. [FunctionAuthorize(true, "Administration-Users")]
  41. public ActionResult ViewUsers()
  42. {
  43. var users = _userService.GetAllUsers();
  44. var userModels = users
  45. .Select(u => UserDataModel.FromUser(u, false))
  46. .ToList();
  47. return View("~/Views/Admin/Users/View.cshtml", userModels);
  48. }
  49. /// <summary>
  50. /// Get JSON data of specific user
  51. /// </summary>
  52. /// <param name="id">User id.</param>
  53. public ActionResult GetUser(int id = -1)
  54. {
  55. var user = _userService.GetUserById(id);
  56. if (user == null)
  57. return new JsonResult
  58. {
  59. Data = "notFound",
  60. JsonRequestBehavior = JsonRequestBehavior.AllowGet
  61. };
  62. var userModel = UserDataModel.FromUser(user, false);
  63. return new JsonResult
  64. {
  65. Data = JsonConvert.SerializeObject(userModel),
  66. JsonRequestBehavior = JsonRequestBehavior.AllowGet
  67. };
  68. }
  69. /// <summary>
  70. /// Callback result for user grid
  71. /// </summary>
  72. /// <param name="scrollHeight">The height of the grid scrollable component.</param>
  73. public ActionResult PartialUsers(int scrollHeight = -1)
  74. {
  75. var users = _userService.GetAllUsers();
  76. var userModels = users
  77. .Select(u => UserDataModel.FromUser(u, false))
  78. .ToList();
  79. ViewData["ScrollHeight"] = scrollHeight;
  80. return PartialView("~/Views/Admin/Users/_UserGridPartial.cshtml", userModels);
  81. }
  82. /// <summary>
  83. /// Partial edit for editing of existing or for new user
  84. /// </summary>
  85. /// <param name="id">Id for existing user, otherweise -1.</param>
  86. public ActionResult EditUser(int id = -1)
  87. {
  88. var user = _userService.GetUserById(id);
  89. var userModel = UserDataModel.FromUser(user, true);
  90. return PartialView("~/Views/Admin/Users/_UserEditPartial.cshtml", userModel);
  91. }
  92. /// <summary>
  93. /// Partial edit result if ModelState is valid, otherwise simple JSON result for success
  94. /// </summary>
  95. /// <param name="userModel">User model to be saved.</param>
  96. [HttpPost, ValidateInput(false)]
  97. public ActionResult EditUser(UserDataModel userModel)
  98. {
  99. try
  100. {
  101. if (!ModelState.IsValid)
  102. {
  103. foreach (var role in userModel.RoleValues)
  104. userModel.RoleDescriptions.Add(
  105. ((IList<Role>)ViewData["AllRoles"])
  106. .First(r => r.Id == role).Description);
  107. return PartialView("~/Views/Admin/Users/_UserEditPartial.cshtml", userModel);
  108. }
  109. var selectedRoles = _userService.GetRolesByIds(userModel.RoleValues.ToArray());
  110. if (userModel.Id == -1)
  111. {
  112. var user = userModel.ToUser();
  113. user.SetRoles(selectedRoles);
  114. user.Password = StaticHelper.GetMD5Hash(userModel.Password);
  115. _userService.InsertUser(user);
  116. _logger.Entity(user, Core.Domain.Logging.LogEntityActivity.Insert, _userHelper.FromCookies());
  117. }
  118. else
  119. {
  120. var user = _userService.GetUserById(userModel.Id);
  121. user.CustomNumber = userModel.CustomNumber;
  122. user.Forename = userModel.Forename;
  123. user.Lastname = userModel.Lastname;
  124. user.MailAddress = userModel.MailAddress;
  125. if (!String.IsNullOrEmpty(userModel.Password))
  126. user.Password = StaticHelper.GetMD5Hash(userModel.Password);
  127. user.SetRoles(selectedRoles);
  128. _userService.UpdateUser(user);
  129. _logger.Entity(user, Core.Domain.Logging.LogEntityActivity.Update, _userHelper.FromCookies());
  130. }
  131. return new JsonResult
  132. {
  133. Data = "success"
  134. };
  135. }
  136. catch (Exception ex)
  137. {
  138. _logger.Error("Fehler bei Speicherung eines Benutzers.", ex, _userHelper.FromCookies());
  139. return PartialView("~/Views/Shared/_PopupError.cshtml", ex);
  140. }
  141. }
  142. /// <summary>
  143. /// Simple JSON result for deleting a specific user
  144. /// </summary>
  145. /// <param name="id">User id.</param>
  146. [HttpPost]
  147. public ActionResult DeleteUser(int id)
  148. {
  149. try
  150. {
  151. var user = _userService.GetUserById(id);
  152. if (user != null)
  153. _userService.DeleteUser(user);
  154. _logger.Entity(user, Core.Domain.Logging.LogEntityActivity.Delete, _userHelper.FromCookies());
  155. return new JsonResult
  156. {
  157. Data = "success"
  158. };
  159. }
  160. catch (Exception ex)
  161. {
  162. _logger.Error("Fehler bei Löschung eines Benutzers.", ex, _userHelper.FromCookies());
  163. return PartialView("~/Views/Shared/_PopupError.cshtml", ex);
  164. }
  165. }
  166. #endregion
  167. #region Roles
  168. /// <summary>
  169. /// Basic role view function
  170. /// </summary>
  171. [FunctionAuthorize(true, "Administration-Roles")]
  172. public ActionResult ViewRoles()
  173. {
  174. var roles = _userService.GetAllRoles();
  175. var roleModels = roles
  176. .Select(r => RoleDataModel.FromRole(r, false))
  177. .ToList();
  178. return View("~/Views/Admin/Roles/View.cshtml", roleModels);
  179. }
  180. /// <summary>
  181. /// Get JSON data of specific role
  182. /// </summary>
  183. /// <param name="id">Role id.</param>
  184. public ActionResult GetRole(int id = -1)
  185. {
  186. var role = _userService.GetRoleById(id);
  187. if (role == null)
  188. return new JsonResult
  189. {
  190. Data = "notFound",
  191. JsonRequestBehavior = JsonRequestBehavior.AllowGet
  192. };
  193. var roleModel = RoleDataModel.FromRole(role, false);
  194. return new JsonResult
  195. {
  196. Data = JsonConvert.SerializeObject(roleModel),
  197. JsonRequestBehavior = JsonRequestBehavior.AllowGet
  198. };
  199. }
  200. /// <summary>
  201. /// Callback result for role grid
  202. /// </summary>
  203. /// <param name="scrollHeight">The height of the grid scrollable component.</param>
  204. public ActionResult PartialRoles(int scrollHeight = -1)
  205. {
  206. var roles = _userService.GetAllRoles();
  207. var roleModels = roles
  208. .Select(r => RoleDataModel.FromRole(r, false))
  209. .ToList();
  210. ViewData["ScrollHeight"] = scrollHeight;
  211. return PartialView("~/Views/Admin/Roles/_RoleGridPartial.cshtml", roleModels);
  212. }
  213. /// <summary>
  214. /// Partial edit for editing of existing or for new role
  215. /// </summary>
  216. /// <param name="id">Id for existing role, otherweise -1.</param>
  217. public ActionResult EditRole(int id = -1)
  218. {
  219. var role = _userService.GetRoleById(id);
  220. var roleModel = RoleDataModel.FromRole(role, true);
  221. return PartialView("~/Views/Admin/Roles/_RoleEditPartial.cshtml", roleModel);
  222. }
  223. /// <summary>
  224. /// Partial edit result if ModelState is valid, otherwise simple JSON result for success
  225. /// </summary>
  226. /// <param name="roleModel">Role model to be saved.</param>
  227. [HttpPost, ValidateInput(false)]
  228. public ActionResult EditRole(RoleDataModel roleModel)
  229. {
  230. try
  231. {
  232. if (!ModelState.IsValid)
  233. {
  234. foreach (var role in roleModel.FunctionValues)
  235. roleModel.FunctionDescriptions.Add(
  236. ((IList<Function>)ViewData["AllFunctions"])
  237. .First(r => r.Id == role).Description);
  238. return PartialView("~/Views/Admin/Roles/_RoleEditPartial.cshtml", roleModel);
  239. }
  240. var selectedFunctions = _userService.GetFunctionsByIds(roleModel.FunctionValues.ToArray());
  241. if (roleModel.Id == -1)
  242. {
  243. var role = roleModel.ToRole();
  244. role.SetFunctions(selectedFunctions);
  245. _userService.InsertRole(role);
  246. _logger.Entity(role, Core.Domain.Logging.LogEntityActivity.Insert, _userHelper.FromCookies());
  247. }
  248. else
  249. {
  250. var role = _userService.GetRoleById(roleModel.Id);
  251. role.Description = roleModel.Description;
  252. role.Level = roleModel.Level;
  253. role.SetFunctions(selectedFunctions);
  254. _userService.UpdateRole(role);
  255. _logger.Entity(role, Core.Domain.Logging.LogEntityActivity.Update, _userHelper.FromCookies());
  256. }
  257. return new JsonResult
  258. {
  259. Data = "success"
  260. };
  261. }
  262. catch (Exception ex)
  263. {
  264. _logger.Error("Fehler bei Speicherung einer Rolle.", ex, _userHelper.FromCookies());
  265. return PartialView("~/Views/Shared/_PopupError.cshtml", ex);
  266. }
  267. }
  268. /// <summary>
  269. /// Simple JSON result for deleting a specific role
  270. /// </summary>
  271. /// <param name="id">Role id.</param>
  272. /// <param name="replaceId">Id of role which user get in place of deleting role.</param>
  273. [HttpPost]
  274. public ActionResult DeleteRole(int id, int replaceId)
  275. {
  276. try
  277. {
  278. var role = _userService.GetRoleById(id);
  279. var replaceRole = _userService.GetRoleById(replaceId);
  280. var roleUsers = _userService.GetUsersByRole(id);
  281. foreach (var user in roleUsers)
  282. {
  283. if (replaceId == -1)
  284. user.Roles.Remove(role);
  285. else
  286. user.Roles.Add(replaceRole);
  287. _userService.UpdateUser(user);
  288. }
  289. if (role != null)
  290. _userService.DeleteRole(role);
  291. _logger.Entity(role, Core.Domain.Logging.LogEntityActivity.Delete, _userHelper.FromCookies());
  292. return new JsonResult
  293. {
  294. Data = "success"
  295. };
  296. }
  297. catch (Exception ex)
  298. {
  299. _logger.Error("Fehler bei Löschung einer Rolle.", ex, _userHelper.FromCookies());
  300. return PartialView("~/Views/Shared/_PopupError.cshtml", ex);
  301. }
  302. }
  303. #endregion
  304. #region Plugins
  305. ///// <summary>
  306. ///// Basic plugin view function
  307. ///// </summary>
  308. //public ActionResult ViewPlugins()
  309. //{
  310. // var model = new PluginModel
  311. // {
  312. // PluginNames = new List<string[]>()
  313. // };
  314. // var uninstalledPlugins = _pluginFinder.GetPlugins<IPlugin>(LoadPluginsMode.NotInstalledOnly);
  315. // var installedPlugins = _pluginFinder.GetPlugins<IPlugin>(LoadPluginsMode.InstalledOnly);
  316. // if (installedPlugins.Any())
  317. // model.PluginNames.AddRange(new List<string[]>()
  318. // {
  319. // new [] { installedPlugins.First().PluginDescriptor.SystemName, "installed" }
  320. // });
  321. // if (uninstalledPlugins.Any())
  322. // model.PluginNames.AddRange(new List<string[]>()
  323. // {
  324. // new [] { uninstalledPlugins.First().PluginDescriptor.SystemName, "uninstalled" }
  325. // });
  326. // return View("~/Views/Admin/Plugins/View.cshtml");
  327. //}
  328. //[HttpPost]
  329. //public ActionResult InstallPlugin(string pluginName)
  330. //{
  331. // var pluginDescriptor = _pluginFinder.GetPluginDescriptorBySystemName(pluginName, LoadPluginsMode.All);
  332. // if (pluginDescriptor == null)
  333. // return RedirectToAction("Plugins");
  334. // if (pluginDescriptor.Installed)
  335. // return RedirectToAction("Plugins");
  336. // var routes = System.Web.Routing.RouteTable.Routes;
  337. // pluginDescriptor.Instance().Install();
  338. // _webHelper.RestartAppDomain();
  339. // return RedirectToAction("Plugins");
  340. //}
  341. //[HttpPost]
  342. //public ActionResult UninstallPlugin(string pluginName)
  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().Uninstall();
  350. // _webHelper.RestartAppDomain();
  351. // return RedirectToAction("Plugins");
  352. //}
  353. #endregion
  354. }
  355. }