public async Task <IActionResult> Edit(Guid id, [Bind("Nickname", "Hostname")] CabinetController cabinetController) { string userId = _userManager.GetUserId(HttpContext.User); if (ModelState.IsValid) { try { cabinetController.Id = id; cabinetController.UserId = userId; _context.Update(cabinetController); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CabinetControllerExists(cabinetController.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(cabinetController)); }
// GET: CabinetControllers/Details/5 public async Task <IActionResult> Details(Guid?id) { string userId = _userManager.GetUserId(HttpContext.User); if (id == null) { return(NotFound()); } CabinetController cabinetController = await _context.Controllers.Where(o => o.UserId == userId) .SingleOrDefaultAsync(m => m.Id == id); if (cabinetController == null) { return(NotFound()); } Cabinet cabinet = await _context.Cabinets.Where(o => o.UserId == userId).SingleOrDefaultAsync(m => m.ControllerId == cabinetController.Id); if (cabinet == null) { return(NotFound()); } return(View(new Tuple <CabinetController, Cabinet>(cabinetController, cabinet))); }
public static void ClassInit(TestContext context) { cabinetsData = mockCabinets(3); mockDatabase = new Mock <IZippyDatabase>(MockBehavior.Strict); mockDatabase.SetupGet(x => x.Users) .Returns(new List <User>() { new User() { Id = 0 } }.AsQueryable()); mockDatabase.SetupGet(x => x.Cabinets) .Returns(() => cabinetsData.AsQueryable()); mockDatabase.Setup(x => x.Add(It.IsAny <Cabinet>())) .Callback <Cabinet>(x => { x.Id = new Random().Next(5, int.MaxValue); cabinetsData.Add(x); }) .Returns((Cabinet x) => x); mockDatabase.Setup(x => x.Remove(It.IsAny <Cabinet>())) .Callback <Cabinet>(x => cabinetsData.Remove(x)) .Returns((Cabinet x) => x); mockDatabase.Setup(x => x.Remove(It.IsAny <Medication>())) .Returns((Medication x) => x); mockDatabase.Setup(x => x.Commit()) .Returns(0); controller = new CabinetController(mockDatabase.Object); }
public async Task <IActionResult> Create([Bind("Nickname", "Hostname")] CabinetController cabinetController) { string userId = _userManager.GetUserId(HttpContext.User); if (ModelState.IsValid) { cabinetController.Id = Guid.NewGuid(); cabinetController.UserId = userId; Cabinet cabinet = new Cabinet() { Id = Guid.NewGuid(), ControllerId = cabinetController.Id, UserId = userId, }; _context.Add(cabinetController); _context.Add(cabinet); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(cabinetController)); }
public CabinetViewer() { InitializeComponent(); MyController = new CabinetController(this); Controller = MyController; CleanEmptyReportButtons(); }
public async Task <IActionResult> DeleteConfirmed(Guid id) { CabinetController cabinetController = await GetController(id); Cabinet cabinet = await GetCabinet(cabinetController); if (cabinet != null) { _context.Cabinets.Remove(cabinet); } ControllerProxy proxy = GetControllerProxy(cabinetController); // If the controller isn't connected, force un-enroll it if (proxy.ValidateController(cabinetController)) { // Notify the controller that it should delete its JWT token and reset await proxy.SendCommandToController("clientDelete"); } // Wait a second or two for completion await Task.Delay(TimeSpan.FromSeconds(2)); _context.Controllers.Remove(cabinetController); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); }
/// <summary> /// Gets a controller proxy for the specified controller. /// </summary> protected ControllerProxy GetControllerProxy(CabinetController controller) { return(new ControllerProxy(controller, HttpContext.RequestServices) { CurrentUserId = _userManager.GetUserId(HttpContext.User), }); }
/// <summary> /// Validates the controller. /// </summary> public bool ValidateController(CabinetController controller) { // Ensure we have a valid Controller if (controller == null || String.IsNullOrEmpty(controller.HubConnectionId) || _hub.Clients == null || _hub.Clients.Client(controller.HubConnectionId) == null) { return(false); } return(true); }
public IActionResult Get(Guid?id) { CabinetController controller = DbContext.Controllers.SingleOrDefault(c => c.Id == id); if (controller == null) { return(new NotFoundResult()); } return(new OkObjectResult(controller.StripUselessInfo())); }
public ControllerProxy(CabinetController controller, IServiceProvider provider) { this.controller = controller; _provider = provider; _context = (ApplicationDbContext)provider.GetService(typeof(ApplicationDbContext)); _hub = (CommandHub)provider.GetService(typeof(CommandHub)); cabinet = _context.Cabinets.Select(s => s).SingleOrDefault(p => (p.ControllerId == controller.Id)); _hub.CommandStatusUpdated += Hub_CommandStatusUpdated; }
public override Task OnDisconnectedAsync(Exception exception) { using (IServiceScope scope = _serviceProvider.CreateScope()) { ApplicationDbContext _context = scope.ServiceProvider.GetRequiredService <ApplicationDbContext>(); // Unset the Connection ID of the controller in the database. CabinetController controller = GetSessionController(_context); controller.HubConnectionId = null; _context.Update(controller); _context.SaveChanges(); } return(base.OnDisconnectedAsync(exception)); }
/// <summary> /// Pushes a single command to the controller from the server side. /// Always called when a command is being executed on a live connection. /// </summary> private async Task PushCommandToController(CabinetController controller, ScheduledCommand command) { // Don't send if the controller is offline! if (!ValidateController(controller)) { throw new Exception("The controller is not connected to the hub!"); } if (command.State != CommandState.Scheduled) { throw new Exception("Command is in an incorrect state. It may be invalid or have completed already."); } await _hub.Clients.Client(controller.HubConnectionId)?.SendCoreAsync("RecieveCommand", new[] { command }); }
public Task UpdateCabinetStatus(Cabinet newCabinet) { using (IServiceScope scope = _serviceProvider.CreateScope()) { ApplicationDbContext _context = scope.ServiceProvider.GetRequiredService <ApplicationDbContext>(); CabinetController controller = GetSessionController(_context); Cabinet cabinet = _context.Cabinets.SingleOrDefault(c => c.ControllerId == controller.Id); cabinet.SecurityArmed = newCabinet.SecurityArmed; cabinet.SecurityAlerted = newCabinet.SecurityAlerted; cabinet.FireAlerted = newCabinet.FireAlerted; cabinet.Override = newCabinet.Override; _context.Update(cabinet); _context.SaveChanges(); return(Task.CompletedTask); } }
public async Task <IActionResult> Post(Guid id, [FromBody] ScheduledCommand _scheduledCommand) { CabinetController cabinetController = await GetController(id); if (cabinetController == null) { return(GetCommandError(_scheduledCommand, ErrorStrings.ControllerNotFound)); } // Make sure the controller is online ControllerProxy proxy = GetControllerProxy(cabinetController); if (!proxy.ValidateController(cabinetController)) { return(GetCommandError(_scheduledCommand, ErrorStrings.ControllerOffline)); } // Send the command to the proxy ScheduledCommand command = await proxy.SendCommandToController(_scheduledCommand.Name, _scheduledCommand.Payload); return(new JsonResult(command)); }
public IActionResult Enroll() { string hostname = Dns.GetHostEntry(HttpContext.Connection.RemoteIpAddress.ToString()).HostName; // Get the controller from the database. CabinetController controller = DbContext.Controllers.SingleOrDefault(c => c.Hostname.ToLower() == hostname.ToLower()); if (controller == null || controller.Authorized == true) { return(new UnauthorizedResult()); } Guid revocationGuid = Guid.NewGuid(); // Give the client a JWT security token Claim[] claims = new Claim[] { new Claim("RevocationGuid", revocationGuid.ToString()), new Claim("ControllerGuid", controller.Id.ToString()), new Claim("AuthorizationType", "ControllerAuthOnly"), new Claim(ClaimTypes.Dns, hostname), }; SigningCredentials credentials = new SigningCredentials(new X509SecurityKey(Startup.GetMachineCertificate()), SecurityAlgorithms.RsaSha256); JwtSecurityToken token = new JwtSecurityToken( issuer: "tower.local", audience: "tower.local", claims: claims, expires: DateTime.Now.AddMonths(2), signingCredentials: credentials); // Controller is enrolled! controller.Authorized = true; controller.RevocationGuid = revocationGuid; DbContext.Controllers.Update(controller); DbContext.SaveChanges(); return(new OkObjectResult(new { token = new JwtSecurityTokenHandler().WriteToken(token), guid = controller.Id.ToString() })); }
/// <summary> /// Attempts to connect to the hub. /// </summary> public async Task Connect() { _logger.LogInformation("Attempting to connect to the message bus."); if (String.IsNullOrEmpty(controllerSettings.JwtToken)) { _logger.LogInformation("JWT token is missing or not found. Cannot connect."); return; } try { // First check our controller's state via the API endpoint. _logger.LogInformation("Checking client enrollment state via CCS API."); HttpResponseMessage message = await client.SendAsync(new HttpRequestMessage(HttpMethod.Get, serverUrl + "/api/Enrollment/Get/" + controllerSettings.Guid.ToString())); // If the controller object isn't found, the controller has been unenrolled // without being notified. Controller should force disconnect itself. if (message.StatusCode == HttpStatusCode.NotFound) { _logger.LogInformation("Controller does not exist on server side. Unenrolling client."); await Unenroll(); return; } message.EnsureSuccessStatusCode(); CabinetController controller = JsonConvert.DeserializeObject <CabinetController>(await message.Content.ReadAsStringAsync()); _logger.LogInformation("Client enrollment state is valid."); } catch (Exception e) { _logger.LogError("Unable to verify the controller enrollment status. The connection will be retried.", e); autoReconnectTimer.Start(); } // Connect via SignalR. try { _logger.LogInformation("Connecting to SignalR."); hubConnection = hubConnectionBuilder.Build(); await hubConnection.StartAsync(); autoReconnectTimer.Stop(); hubConnection.On <ScheduledCommand>("RecieveCommand", command => { Task.Run(() => HandleCommand(command)); }); hubConnection.Closed += HubConnection_Closed; Connected = true; _logger.LogInformation("Connected to SignalR successfully."); } catch (Exception e) { _logger.LogError("Error connecting to SignalR. The connection will be retried.", e); autoReconnectTimer.Start(); } }
// Update is called once per frame void Update() { RaycastHit hitInfo = new RaycastHit(); bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo); if (hit) { text.text = ""; GameObject tempObject = hitInfo.transform.gameObject; //cabinet opening and closing CabinetController tempCabinet = tempObject.GetComponent <CabinetController> (); if (tempCabinet != null) { text.text = "Open\n" + tempObject.name; if (Input.GetMouseButtonDown(0)) { tempCabinet.toggleDoors(); } } //else { //picking up items // PickUp tempPick = tempObject.GetComponent<PickUp> (); // if (tempPick != null) { // this.pickUpItem (tempPick); // } else { //examining objects Description tempDesc = tempObject.GetComponent <Description> (); //objects that have descriptions if (tempDesc != null) { //special folder exception if (tempObject.tag == "Folder") { text.text = "Go to simulation"; if (Input.GetMouseButtonDown(0)) { print("Folder Clicked!"); this.load(); } } //general items with descriptions else { text.text = "Examine\n" + tempObject.name; if (Input.GetMouseButtonDown(0)) { descText.text = tempDesc.getDescription(); this.dTimer.startTimer(); } } } else if (tempObject.tag == "Door") { text.text = "Go to Professor's office"; if (Input.GetMouseButtonDown(0)) { print("Door Clicked!"); this.loadOffice(); } } else if (tempObject.tag == "OfficeDoor") { text.text = "Go to Apartment"; if (Input.GetMouseButtonDown(0)) { print("Door Clicked!"); this.loadRoom(); } } else if (tempObject.tag == "Professor") { text.text = "Talk to Professor"; if (Input.GetMouseButtonDown(0)) { Cursor.visible = true; Cursor.lockState = CursorLockMode.None; ProfQuestions.SetActive(true); } } else if (tempObject.tag == "Stethoscope") { text.text = "Take Stethoscope"; if (Input.GetMouseButtonDown(0)) { PickUp tempPick = tempObject.GetComponent <PickUp> (); if (tempPick != null) { this.pickUpItem(tempPick); tempObject.SetActive(false); objectiveText.text = "Proceed to simulation"; } } /* * else { * text.text = ""; * } */ } } } if (Input.GetMouseButtonDown(1)) { var ball = GameObject.Instantiate(sphere, this.transform.position, Quaternion.identity) as GameObject; Vector3 value = new Vector3(0, 1, 0); ball.transform.position = transform.position + value; ball.GetComponent <Rigidbody> ().velocity = transform.forward * 3; ball.GetComponent <Rigidbody> ().velocity += Vector3.up * 1; } }
protected async Task <Cabinet> GetCabinet(CabinetController controller) { return(await _context.Cabinets.Where(o => o.UserId == _userManager.GetUserId(HttpContext.User)).SingleOrDefaultAsync(m => m.ControllerId == controller.Id)); }