PageRenderTime 653ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/PSAdmin.Web/Controllers/ScriptController.cs

http://psadmin.codeplex.com
C# | 323 lines | 222 code | 67 blank | 34 comment | 39 complexity | a7a7cf3ae116484c966f20abe2234159 MD5 | raw file
  1. //------------------------------------------------------------------------------
  2. // The contents of this file are subject to the Microsoft Public License (Ms-PL)
  3. // You may obtain a copy of the License at http://psadmin.codeplex.com/license.
  4. //
  5. // Software distributed under the License is distributed on an "AS IS" basis,
  6. // WITHOUT WARRANTY OF ANY KIND, either express or implied.
  7. // See the License for the specific language governing rights and limitations
  8. // under the License.
  9. //
  10. // The initial developer is Ben Foster (ben.foster@retroviz.com)
  11. // Copyright (c) Retroviz Limited (http://www.retroviz.com).
  12. // All Rights Reserved.
  13. //------------------------------------------------------------------------------
  14. using System;
  15. using System.Collections.Generic;
  16. using System.Linq;
  17. using System.Web;
  18. using System.Web.Mvc;
  19. using System.Web.Mvc.Ajax;
  20. using PSAdmin.Core;
  21. using PSAdmin.Core.Domain;
  22. using PSAdmin.Core.Interfaces;
  23. using PSAdmin.Core.Utils;
  24. using PSAdmin.Web.Infrastructure;
  25. using PSAdmin.Web.Models;
  26. namespace PSAdmin.Web.Controllers
  27. {
  28. public class ScriptController : SiteController
  29. {
  30. int _pageSize = 6;
  31. IPSScriptRepository _scriptRepository;
  32. IUserRoleRepository _roleRepository;
  33. IUserEventRepository _eventRepository;
  34. IScriptService _scriptService;
  35. public ScriptController(IScriptService scriptService, IPSScriptRepository scriptRepository, IUserRoleRepository roleRepository,
  36. IUserEventRepository eventRepository, ISessionStore sessionStore) : base(sessionStore) {
  37. _scriptService = scriptService;
  38. _scriptRepository = scriptRepository;
  39. _roleRepository = roleRepository;
  40. _eventRepository = eventRepository;
  41. }
  42. //
  43. // GET: /Script/
  44. [HttpGet]
  45. public ActionResult Index() {
  46. ViewData["console"] = this.CurrentConsole;
  47. return View();
  48. }
  49. //
  50. // GET: /Script/List/Page2
  51. [HttpGet]
  52. public ActionResult List(int? page) {
  53. var pageIndex = page ?? 1;
  54. var scripts = (this.IsAdminRequest())
  55. ? _scriptRepository.GetPaged(pageIndex, _pageSize)
  56. :_scriptRepository.GetScriptsForUser(User.Identity.Name, pageIndex, _pageSize);
  57. return View(scripts);
  58. }
  59. //
  60. // GET: /Script/Details/1234
  61. [HttpGet]
  62. public ActionResult Details(int? id) {
  63. if (!id.HasValue) return RedirectToAction("List");
  64. var script = _scriptRepository.GetById(id.Value);
  65. if (script == null) return RedirectToAction("List");
  66. if (!this.CanExecuteScript(script, _roleRepository.GetUserRoles(User.Identity.Name)))
  67. return RedirectToAction("UnAuthorized");
  68. return View(script);
  69. }
  70. //
  71. // POST: /Script/Details/1234?...
  72. [HttpPost]
  73. public ActionResult Details(int id, IDictionary<int, string> variables) {
  74. var script = _scriptRepository.GetById(id);
  75. if (script == null)
  76. return RedirectToAction("Scripts");
  77. var data = new Dictionary<string, object>();
  78. if (script.HasVariables && variables != null) {
  79. foreach (var v in variables) {
  80. var scriptVariable = script.Variables.FirstOrDefault(x => x.Id == v.Key);
  81. if (scriptVariable == null)
  82. throw new InvalidOperationException("Script variable does not exist.");
  83. if (string.IsNullOrEmpty(v.Value)) {
  84. ModelState.AddModelError("", string.Format("A value has not been entered for variable {0}",
  85. scriptVariable.Name));
  86. }
  87. }
  88. if (!ModelState.IsValid)
  89. return View(script);
  90. foreach (var variable in script.Variables) {
  91. if (variables.ContainsKey(variable.Id)) {
  92. data.Add(variable.Token, variables[variable.Id]);
  93. }
  94. }
  95. }
  96. var result = _scriptService.ExecuteScript(script, data);
  97. this.CurrentConsole += result;
  98. // audit
  99. var userEvent = this.CreateEvent(script.Id, UserBehaviour.ExecuteScript, script.Name,
  100. data.ConvertToString(), string.Empty); // TODO need to store output efficiently
  101. _eventRepository.Save(userEvent);
  102. return RedirectToAction("Index");
  103. }
  104. //
  105. // GET: /Script/Create
  106. [HttpGet]
  107. [Authorize(Roles="Administrators")]
  108. public ActionResult Create() {
  109. return View();
  110. }
  111. // POST: /Script/Create
  112. [HttpPost]
  113. [Authorize(Roles = "Administrators")]
  114. public ActionResult Create([Bind(Exclude="Id")]PSScript script) {
  115. if (ModelState.IsValid) {
  116. var result = SaveScript(script);
  117. return RedirectToAction("Edit", new { id = result });
  118. }
  119. return View();
  120. }
  121. //
  122. // GET: /Script/Edit/1234
  123. [HttpGet]
  124. [Authorize(Roles = "Administrators")]
  125. public ActionResult Edit(int? id)
  126. {
  127. if (!id.HasValue) return RedirectToAction("List");
  128. var script = _scriptRepository.GetById(id.Value);
  129. if (script == null) return RedirectToAction("List");
  130. var roles = _roleRepository.GetAll();
  131. var editScript = new PSScriptEditViewModel(script, roles);
  132. return View(editScript);
  133. }
  134. //
  135. // POST: /Script/Edit/
  136. [HttpPost]
  137. [Authorize(Roles = "Administrators")]
  138. public ActionResult Edit([Bind(Exclude = "Roles, Variables")]PSScript script, Guid[] scriptRoles)
  139. {
  140. if (ModelState.IsValid) {
  141. if (scriptRoles != null) {
  142. script.Roles.Clear(); // not the most efficient way, but it works
  143. foreach (var roleId in scriptRoles) {
  144. var role = _roleRepository.GetById(roleId);
  145. script.Roles.Add(role);
  146. }
  147. }
  148. SaveScript(script);
  149. }
  150. return RedirectToAction("Edit", new { id = script.Id});
  151. }
  152. [HttpPost]
  153. [Authorize(Roles = "Administrators")]
  154. public ActionResult Delete(int id) {
  155. var script = _scriptRepository.GetById(id);
  156. if (script != null)
  157. _scriptRepository.Delete(script);
  158. return RedirectToAction("List");
  159. }
  160. //
  161. // POST: /Script/GetVariable/12345?scriptId=12
  162. [HttpPost]
  163. [Authorize(Roles = "Administrators")]
  164. public ActionResult GetVariable(int id, int scriptId) {
  165. var script = _scriptRepository.GetById(scriptId);
  166. var variable = script.Variables.FirstOrDefault(x => x.Id == id);
  167. return PartialView("VariableDetails", variable);
  168. }
  169. //
  170. // POST: /Script/SaveVariable/
  171. [HttpPost]
  172. [Authorize(Roles = "Administrators")]
  173. public ActionResult SaveVariable(PSScriptVariable variable)
  174. {
  175. var script = _scriptRepository.GetById(variable.Script.Id);
  176. var v = script.Variables.FirstOrDefault(x => x.Id == variable.Id);
  177. v.Name = variable.Name;
  178. v.Description = variable.Description;
  179. v.Token = variable.Token;
  180. _scriptRepository.Save(script);
  181. return RedirectToAction("Edit", new { id = variable.Script.Id });
  182. }
  183. [HttpPost]
  184. [Authorize(Roles = "Administrators")]
  185. public ActionResult CreateVariable(int scriptId, FormCollection values)
  186. {
  187. var script = _scriptRepository.GetById(scriptId);
  188. var variable = new PSScriptVariable() {
  189. Name = values.Get("NewVariableName"),
  190. Description = values.Get("NewVariableDescription"),
  191. Token = values.Get("NewVariableToken")
  192. };
  193. script.AddScriptVariable(variable);
  194. _scriptRepository.Save(script);
  195. return RedirectToAction("Edit", new { id = script.Id });
  196. }
  197. [HttpPost]
  198. [Authorize(Roles = "Administrators")]
  199. public JsonResult DeleteVariable(int id, int scriptId)
  200. {
  201. bool result = false;
  202. var script = _scriptRepository.GetById(scriptId);
  203. if (script != null)
  204. {
  205. var variable = script.Variables.FirstOrDefault(x => x.Id == id);
  206. if (variable != null)
  207. {
  208. script.Variables.Remove(variable);
  209. _scriptRepository.Save(script);
  210. result = true;
  211. }
  212. }
  213. return Json(result);
  214. }
  215. [HttpPost]
  216. [Authorize(Roles = "Administrators")]
  217. public ActionResult Execute(string submitButton, string command)
  218. {
  219. if (submitButton == "Clear") {
  220. this.CurrentConsole = string.Empty;
  221. }
  222. // not implemented
  223. if (submitButton == "Execute" && !string.IsNullOrEmpty(command)) {
  224. var script = new PSScript() {
  225. Name = "Ad hoc script",
  226. CommandText = command
  227. };
  228. this.CurrentConsole += _scriptService.ExecuteScript(script, new Dictionary<string, object>());
  229. }
  230. if (Request.IsAjaxRequest())
  231. {
  232. return Content(this.CurrentConsole, "text/plain");
  233. }
  234. return RedirectToAction("Index");
  235. }
  236. [HttpGet]
  237. public ActionResult Download()
  238. {
  239. if (!string.IsNullOrEmpty(this.CurrentConsole)) {
  240. var consoleBytes = System.Text.Encoding.UTF8.GetBytes(this.CurrentConsole);
  241. return File(consoleBytes, "text/plain", "PSAdminSession.txt");
  242. }
  243. return RedirectToAction("Index");
  244. }
  245. [HttpGet]
  246. public ActionResult Unauthorized() {
  247. return View();
  248. }
  249. [NonAction]
  250. private int SaveScript(PSScript script) {
  251. if (!string.IsNullOrEmpty(script.Password))
  252. script.Password = EncryptionHelper.Encrypt(script.Password);
  253. return _scriptRepository.Save(script);
  254. }
  255. }
  256. }