public void TestRetrieveUserSettingsDefaultValues() { using (MySqlDataManipulator manipulator = new MySqlDataManipulator()) { manipulator.Connect(TestingConstants.ConnectionString); Assert.IsTrue(NetTestingUserUtils.LogInTestingUser(TestingUserStorage.ValidUser1)); var user = manipulator.GetUsersWhere(string.Format("Email=\"{0}\"", TestingUserStorage.ValidUser1.Email))[0]; var currentSettings = user.Settings; object[] contextAndRequest = ServerTestingMessageSwitchback.SwitchbackMessage( TestingUserStorage.ValidUser1.ConstructRetrieveSettingsRequest( user.UserId, UserVerificationUtil.ExtractLoginTokens(user).LoginToken), "PUT"); var ctx = contextAndRequest[0] as HttpListenerContext; var req = contextAndRequest[1] as HttpWebRequest; TestApi.PUT(ctx); HttpWebResponse resp = null; try { resp = req.EndGetResponse(contextAndRequest[2] as IAsyncResult) as HttpWebResponse; } catch (Exception e) { Assert.Fail(e.Message); } using (resp) { Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode); byte[] data = new byte[resp.ContentLength]; resp.GetResponseStream().Read(data, 0, data.Length); string received = Encoding.UTF8.GetString(data); Assert.AreEqual(currentSettings, received); } } }
public void TestUnauthorizedOnNonLoggedInUser() { MySqlDataManipulator manipulator = new MySqlDataManipulator(); Assert.IsTrue(manipulator.Connect(TestingConstants.ConnectionString)); using (manipulator) { PartCatalogueEntry entry = manipulator.GetPartCatalogueEntriesWhere(1, string.Format("PartId=\"{0}\"", TestingPartEntry.ValidPartEntry1.PartId) )[0]; Assert.IsTrue(NetTestingUserUtils.AuthenticateTestingUser(TestingUserStorage.ValidUser3, manipulator)); OverallUser validUser1 = manipulator.GetUsersWhere( string.Format("Email=\"{0}\"", TestingUserStorage.ValidUser3.Email) )[0]; var loginTokens = UserVerificationUtil.ExtractLoginTokens(validUser1); var message = TestingPartEntry.ValidPartEntry1.ConstructDeletionRequest( validUser1.UserId, loginTokens.LoginToken, loginTokens.AuthToken, entry.Id ); message["LoginToken"] = "x'abacbadabac'"; object[] contextAndRequest = ServerTestingMessageSwitchback.SwitchbackMessage( message, "PATCH" ); var context = contextAndRequest[0] as HttpListenerContext; var req = contextAndRequest[1] as HttpWebRequest; TestApi.PATCH(context); HttpWebResponse response; try { response = req.EndGetResponse(contextAndRequest[2] as IAsyncResult) as HttpWebResponse; Assert.Fail("Expected and error response, but did not receive one"); } catch (WebException e) { response = e.Response as HttpWebResponse; } Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode); } }
public static bool AuthenticateTestingUser(TestingUserStorage.TestingUser userIn, MySqlDataManipulator manipulatorIn) { UserAuthApi api = new UserAuthApi(10000); if (!LogInTestingUser(userIn)) { return(false); } var databaseUser = manipulatorIn.GetUsersWhere(string.Format("Email=\"{0}\"", userIn.Email))[0]; var loginTokens = UserVerificationUtil.ExtractLoginTokens(databaseUser); object[] contextAndRequest = ServerTestingMessageSwitchback.SwitchbackMessage( userIn.ConstructAuthenticationRequest(loginTokens.LoginToken, databaseUser.UserId), "PUT"); var ctx = contextAndRequest[0] as HttpListenerContext; var req = contextAndRequest[1] as HttpWebRequest; api.PUT(ctx); HttpWebResponse resp; try { resp = req.EndGetResponse(contextAndRequest[2] as IAsyncResult) as HttpWebResponse; return(true); } catch { return(false); } }
public void TestNotFoundOnNonExistentUser() { using (MySqlDataManipulator manipulator = new MySqlDataManipulator()) { manipulator.Connect(TestingConstants.ConnectionString); NetTestingUserUtils.AuthenticateTestingUser(TestingUserStorage.ValidUser1, manipulator); var reportingUser = manipulator.GetUsersWhere( string.Format("Email=\"{0}\"", TestingUserStorage.ValidUser1.Email) )[0]; var loginTokens = UserVerificationUtil.ExtractLoginTokens(reportingUser); object[] contextAndRequest = ServerTestingMessageSwitchback.SwitchbackMessage( TestingUserStorage.ValidUser1.ConstructReportMessage( 10000000, loginTokens.LoginToken, loginTokens.AuthToken, "TerribleName" ), "POST" ); var ctx = contextAndRequest[0] as HttpListenerContext; var req = contextAndRequest[1] as HttpWebRequest; HttpWebResponse resp = null; TestApi.POST(ctx); try { resp = req.EndGetResponse(contextAndRequest[2] as IAsyncResult) as HttpWebResponse; Assert.Fail("Expected an error message but never received one"); } catch (WebException e) { resp = e.Response as HttpWebResponse; } Assert.AreEqual(HttpStatusCode.NotFound, resp.StatusCode); } }
public void TestValidRequest() { using (MySqlDataManipulator manipulator = new MySqlDataManipulator()) { manipulator.Connect(TestingConstants.ConnectionString); Assert.IsTrue(NetTestingUserUtils.LogInTestingUser(TestingUserStorage.ValidUser1)); var user = manipulator.GetUsersWhere(string.Format("Email=\"{0}\"", TestingUserStorage.ValidUser1.Email))[0]; var loginTokens = UserVerificationUtil.ExtractLoginTokens(user); object[] contextAndRequest = ServerTestingMessageSwitchback.SwitchbackMessage( TestingUserStorage.ValidUser1.ConstructSecurityQuestionRequest(loginTokens.LoginToken, user.UserId), "POST"); var ctx = contextAndRequest[0] as HttpListenerContext; var req = contextAndRequest[1] as HttpWebRequest; HttpWebResponse resp; TestApi.POST(ctx); try { resp = req.EndGetResponse(contextAndRequest[2] as IAsyncResult) as HttpWebResponse; } catch (WebException e) { resp = e.Response as HttpWebResponse; byte[] respData = new byte[resp.ContentLength]; resp.GetResponseStream().Read(respData, 0, respData.Length); Console.WriteLine(Encoding.UTF8.GetString(respData)); throw e; } byte[] data = new byte[resp.ContentLength]; resp.GetResponseStream().Read(data, 0, data.Length); string receivedData = Encoding.UTF8.GetString(data); Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode); Assert.AreEqual(TestingUserStorage.ValidUser1.SecurityQuestion, receivedData); } }
public void BadRequestOnInvalidUserId() { MySqlDataManipulator manipulator = new MySqlDataManipulator(); using (manipulator) { manipulator.Connect(TestingConstants.ConnectionString); Assert.IsTrue(NetTestingUserUtils.AuthenticateTestingUser(TestingUserStorage.ValidUser2, manipulator)); OverallUser user = manipulator.GetUsersWhere(string.Format("Email=\"{0}\"", TestingUserStorage.ValidUser2.Email))[0]; var loginTokens = UserVerificationUtil.ExtractLoginTokens(user); var authReq = TestingUserStorage.ValidUser2.ConstructCheckAuthenticationStatusRequest(loginTokens.LoginToken, loginTokens.AuthToken, user.UserId); authReq.SetMapping("UserId", 0); object[] contextAndRequest = ServerTestingMessageSwitchback.SwitchbackMessage(authReq, "PUT"); var ctx = contextAndRequest[0] as HttpListenerContext; var req = contextAndRequest[1] as HttpWebRequest; TestApi.PUT(ctx); HttpWebResponse resp; try { resp = req.EndGetResponse(contextAndRequest[2] as IAsyncResult) as HttpWebResponse; Assert.Fail(); } catch (WebException e) { resp = e.Response as HttpWebResponse; } Assert.AreEqual(HttpStatusCode.BadRequest, resp.StatusCode); } }
public void TestUploadRepairJobSimilarJobsForced() { using (MySqlDataManipulator manipulator = new MySqlDataManipulator()) { manipulator.Connect(TestingConstants.ConnectionString); NetTestingUserUtils.AuthenticateTestingUser(TestingUserStorage.ValidUser1, manipulator); var uploadingUser = manipulator.GetUsersWhere( string.Format("Email=\"{0}\"", TestingUserStorage.ValidUser1.Email) )[0]; var loginTokens = UserVerificationUtil.ExtractLoginTokens(uploadingUser); object[] contextAndRequest = ServerTestingMessageSwitchback.SwitchbackMessage( TestingRepairJobStorage.RepairJob1.ConstructCreationMessage( uploadingUser.UserId, loginTokens.LoginToken, loginTokens.AuthToken, 1 ), "POST" ); var ctx = contextAndRequest[0] as HttpListenerContext; var req = contextAndRequest[1] as HttpWebRequest; HttpWebResponse resp = null; TestApi.POST(ctx); try { resp = req.EndGetResponse(contextAndRequest[2] as IAsyncResult) as HttpWebResponse; } catch (WebException) { Assert.Fail("Received an error message when one was not expected"); } Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode); } }
public void TestUnauthorizedOnNotLoggedInUser() { using (MySqlDataManipulator manipulator = new MySqlDataManipulator()) { manipulator.Connect(TestingConstants.ConnectionString); NetTestingUserUtils.AuthenticateTestingUser(TestingUserStorage.ValidUser1, manipulator); var uploadingUser = manipulator.GetUsersWhere( string.Format("Email=\"{0}\"", TestingUserStorage.ValidUser1.Email) )[0]; var loginTokens = UserVerificationUtil.ExtractLoginTokens(uploadingUser); object[] contextAndRequest = ServerTestingMessageSwitchback.SwitchbackMessage( TestingRepairJobStorage.RepairJob1.ConstructCreationMessage( uploadingUser.UserId, "I'm Logged-In I Swear!", loginTokens.AuthToken, 0 ), "POST" ); var ctx = contextAndRequest[0] as HttpListenerContext; var req = contextAndRequest[1] as HttpWebRequest; HttpWebResponse resp = null; TestApi.POST(ctx); try { resp = req.EndGetResponse(contextAndRequest[2] as IAsyncResult) as HttpWebResponse; } catch (WebException e) { resp = e.Response as HttpWebResponse; string message = e.Message; } Assert.AreEqual(HttpStatusCode.Unauthorized, resp.StatusCode); } }
public void TestBadRequestOnInvalidUserId() { MySqlDataManipulator manipulator = new MySqlDataManipulator(); Assert.IsTrue(manipulator.Connect(TestingConstants.ConnectionString)); using (manipulator) { Assert.IsTrue(NetTestingUserUtils.AuthenticateTestingUser(TestingUserStorage.ValidUser3, manipulator)); OverallUser validUser1 = manipulator.GetUsersWhere( string.Format("Email=\"{0}\"", TestingUserStorage.ValidUser3.Email) )[0]; var loginTokens = UserVerificationUtil.ExtractLoginTokens(validUser1); var message = TestingPartEntry.ValidPartEntry1.ConstructAdditionRequest( validUser1.UserId, loginTokens.LoginToken, loginTokens.AuthToken ); message["UserId"] = 0; object[] contextAndRequest = ServerTestingMessageSwitchback.SwitchbackMessage( message, "POST" ); var context = contextAndRequest[0] as HttpListenerContext; var req = contextAndRequest[1] as HttpWebRequest; TestApi.POST(context); HttpWebResponse response; try { response = req.EndGetResponse(contextAndRequest[2] as IAsyncResult) as HttpWebResponse; Assert.Fail("Expected an error response, but did not receive one"); } catch (WebException e) { response = e.Response as HttpWebResponse; } Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode); } }
public void TestNotFoundOnNonExistentUser() { using (MySqlDataManipulator manipulator = new MySqlDataManipulator()) { manipulator.Connect(TestingConstants.ConnectionString); Assert.IsTrue(NetTestingUserUtils.LogInTestingUser(TestingUserStorage.ValidUser1)); var user = manipulator.GetUsersWhere(string.Format("Email=\"{0}\"", TestingUserStorage.ValidUser1.Email))[0]; var currentSettings = user.Settings; object[] contextAndRequest = ServerTestingMessageSwitchback.SwitchbackMessage( TestingUserStorage.ValidUser1.ConstructRetrieveSettingsRequest( 100000, UserVerificationUtil.ExtractLoginTokens(user).LoginToken), "PUT"); var ctx = contextAndRequest[0] as HttpListenerContext; var req = contextAndRequest[1] as HttpWebRequest; TestApi.PUT(ctx); HttpWebResponse resp = null; try { resp = req.EndGetResponse(contextAndRequest[2] as IAsyncResult) as HttpWebResponse; Assert.Fail("Expected error response, but did not receive one"); } catch (WebException e) { resp = e.Response as HttpWebResponse; } Assert.AreEqual(HttpStatusCode.NotFound, resp.StatusCode); } }
public void TestValidAuthenticationRequest() { MySqlDataManipulator manipulator = new MySqlDataManipulator(); using (manipulator) { manipulator.Connect(TestingConstants.ConnectionString); Assert.IsTrue(NetTestingUserUtils.AuthenticateTestingUser(TestingUserStorage.ValidUser2, manipulator)); OverallUser user = manipulator.GetUsersWhere(string.Format("Email=\"{0}\"", TestingUserStorage.ValidUser2.Email))[0]; var loginTokens = UserVerificationUtil.ExtractLoginTokens(user); var authReq = TestingUserStorage.ValidUser2.ConstructCheckAuthenticationStatusRequest(loginTokens.LoginToken, loginTokens.AuthToken, user.UserId); object[] contextAndRequest = ServerTestingMessageSwitchback.SwitchbackMessage(authReq, "PUT"); var ctx = contextAndRequest[0] as HttpListenerContext; var req = contextAndRequest[1] as HttpWebRequest; TestApi.PUT(ctx); HttpWebResponse resp; try { resp = req.EndGetResponse(contextAndRequest[2] as IAsyncResult) as HttpWebResponse; } catch (WebException e) { resp = e.Response as HttpWebResponse; byte[] respData = new byte[resp.ContentLength]; resp.GetResponseStream().Read(respData, 0, respData.Length); Console.WriteLine(Encoding.UTF8.GetString(respData)); throw e; } Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode); } }
public void TestValidRequest() { MySqlDataManipulator manipulator = new MySqlDataManipulator(); Assert.IsTrue(manipulator.Connect(TestingConstants.ConnectionString)); using (manipulator) { PartCatalogueEntry entry = manipulator.GetPartCatalogueEntriesWhere(1, string.Format("PartId=\"{0}\"", TestingPartEntry.ValidPartEntry1.PartId) )[0]; Assert.IsTrue(manipulator.RemovePartCatalogueEntry( 1, entry.Id )); var entryList = manipulator.GetPartCatalogueEntriesWhere( 1, string.Format("PartId=\"{0}\"", TestingPartEntry.ValidPartEntry1.PartId) ); Assert.AreEqual(0, entryList.Count); try { Assert.IsTrue(NetTestingUserUtils.AuthenticateTestingUser(TestingUserStorage.ValidUser3, manipulator)); OverallUser validUser1 = manipulator.GetUsersWhere( string.Format("Email=\"{0}\"", TestingUserStorage.ValidUser3.Email) )[0]; var loginTokens = UserVerificationUtil.ExtractLoginTokens(validUser1); var message = TestingPartEntry.ValidPartEntry1.ConstructAdditionRequest( validUser1.UserId, loginTokens.LoginToken, loginTokens.AuthToken ); object[] contextAndRequest = ServerTestingMessageSwitchback.SwitchbackMessage( message, "POST" ); var context = contextAndRequest[0] as HttpListenerContext; var req = contextAndRequest[1] as HttpWebRequest; TestApi.POST(context); HttpWebResponse response; try { response = req.EndGetResponse(contextAndRequest[2] as IAsyncResult) as HttpWebResponse; } catch (WebException e) { response = e.Response as HttpWebResponse; Assert.Fail("Server sent back an error response: {0}", response.StatusCode); } Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); var addedEntryList = manipulator.GetPartCatalogueEntriesWhere( 1, string.Format("PartId=\"{0}\"", TestingPartEntry.ValidPartEntry1.PartId) ); Assert.AreEqual(1, addedEntryList.Count); } finally { if ( manipulator.GetPartCatalogueEntriesWhere(1, string.Format("PartId=\"{0}\"", TestingPartEntry.ValidPartEntry1.PartId) ).Count == 0 ) { Assert.IsTrue(TestingDatabaseCreationUtils.InitializePartCatelogueEntries()); } } } }
/// <summary> /// Request for retrieving a user's security question. Documention is found in the Web API Enumeration file /// in the /User/Auth tab, starting at row 1 /// </summary> /// <param name="ctx">The HttpListenerContext to respond to</param> private void HandlePostRequest(HttpListenerContext ctx) { try { #region Input Validation if (!ctx.Request.HasEntityBody) { WriteBodyResponse(ctx, 400, "No Body", "Request lacked a body"); return; } SecurityQuestionRequest req = JsonDataObjectUtil <SecurityQuestionRequest> .ParseObject(ctx); if (req == null) { WriteBodyResponse(ctx, 400, "Incorrect Format", "Request was in the wrong format"); return; } if (!ValidateSecurityQuestionRequest(req)) { WriteBodyResponse(ctx, 400, "Incorrect Format", "Not all fields of the request were filled"); return; } #endregion MySqlDataManipulator connection = new MySqlDataManipulator(); using (connection) { bool res = connection.Connect(MySqlDataManipulator.GlobalConfiguration.GetConnectionString()); if (!res) { WriteBodyResponse(ctx, 500, "Unexpected ServerError", "Connection to database failed"); return; } #region Action Handling var user = connection.GetUserById(req.UserId); if (user == null) { WriteBodyResponse(ctx, 404, "Not Found", "User was not found on the server"); return; } if (!UserVerificationUtil.LoginTokenValid(user, req.LoginToken)) { WriteBodyResponse(ctx, 401, "Unauthorized", "Login Token was incorrect or expired"); return; } WriteBodyResponse(ctx, 200, "OK", user.SecurityQuestion); #endregion } } catch (HttpListenerException) { //HttpListeners dispose themselves when an exception occurs, so we can do no more. } catch (Exception) { WriteBodylessResponse(ctx, 500, "Internal Server Error"); } }
public void TestValidReport() { using (MySqlDataManipulator manipulator = new MySqlDataManipulator()) { manipulator.Connect(TestingConstants.ConnectionString); var reportedUser = manipulator.GetUsersWhere(string.Format("Email=\"{0}\"", TestingUserStorage.ValidUser2.Email))[0]; try { reportedUser.UpdateSettings(UserSettingsEntryKeys.DisplayName, "TerribleName"); Assert.IsTrue(manipulator.UpdateUsersSettings(reportedUser)); NetTestingUserUtils.AuthenticateTestingUser(TestingUserStorage.ValidUser1, manipulator); var reportingUser = manipulator.GetUsersWhere( string.Format("Email=\"{0}\"", TestingUserStorage.ValidUser1.Email) )[0]; var loginTokens = UserVerificationUtil.ExtractLoginTokens(reportingUser); object[] contextAndRequest = ServerTestingMessageSwitchback.SwitchbackMessage( TestingUserStorage.ValidUser1.ConstructReportMessage( reportingUser.UserId, loginTokens.LoginToken, loginTokens.AuthToken, "TerribleName" ), "POST" ); var ctx = contextAndRequest[0] as HttpListenerContext; var req = contextAndRequest[1] as HttpWebRequest; HttpWebResponse resp = null; TestApi.POST(ctx); try { resp = req.EndGetResponse(contextAndRequest[2] as IAsyncResult) as HttpWebResponse; } catch (WebException) { Assert.Fail("Received an error message when one was not expected"); } Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode); reportedUser = manipulator.GetUsersWhere(string.Format("Email=\"{0}\"", TestingUserStorage.ValidUser2.Email))[0]; var reportedUserSettings = JsonDataObjectUtil <List <UserSettingsEntry> > .ParseObject(reportedUser.Settings); bool foundDisplayName = false; foreach (UserSettingsEntry entry in reportedUserSettings) { if (entry.Key == UserSettingsEntryKeys.DisplayName) { foundDisplayName = true; Assert.AreEqual("Default User " + reportedUser.UserId, entry.Value); break; } } Assert.IsTrue(foundDisplayName); } finally { reportedUser.Settings = OverallUser.GenerateDefaultSettings(); Assert.IsTrue(manipulator.UpdateUsersSettings(reportedUser)); } } }
/// <summary> /// GET request format located in the Web Api Enumeration v2 /// under the tab Company/Parts/Request, starting row 23 /// </summary> /// <param name="ctx">HttpListenerContext to respond to</param> private void HandleGetRequest(HttpListenerContext ctx, CompanyPartsRequestGetRequest entry) { try { MySqlDataManipulator connection = new MySqlDataManipulator(); using (connection) { bool res = connection.Connect(MySqlDataManipulator.GlobalConfiguration.GetConnectionString()); if (!res) { WriteBodyResponse(ctx, 500, "Unexpected Server Error", "Connection to database failed"); return; } #region User Validation OverallUser mappedUser = connection.GetUserById(entry.UserId); if (mappedUser == null) { WriteBodyResponse(ctx, 404, "Not Found", "User was not found on on the server"); return; } if (!UserVerificationUtil.LoginTokenValid(mappedUser, entry.LoginToken)) { WriteBodyResponse(ctx, 401, "Not Authorized", "Login token was incorrect."); return; } if (!UserVerificationUtil.AuthTokenValid(mappedUser, entry.AuthToken)) { WriteBodyResponse(ctx, 401, "Not Authorized", "Auth token was ezpired or incorrect"); return; } if ((mappedUser.AccessLevel & AccessLevelMasks.PartMask) == 0) { WriteBodyResponse(ctx, 401, "Not Authorized", "User was not a parts level user"); return; } #endregion #region Action Handling JsonListStringConstructor retConstructor = new JsonListStringConstructor(); List <PartsRequest> requests = connection.GetPartsRequests(mappedUser.Company); requests.ForEach(req => retConstructor.AddElement(WritePartsRequestToOutput(req, connection, mappedUser.Company))); WriteBodyResponse(ctx, 200, "OK", retConstructor.ToString()); #endregion } } catch (HttpListenerException) { //HttpListeners dispose themselves when an exception occurs, so we can do no more. } catch (Exception e) { WriteBodyResponse(ctx, 500, "Internal Server Error", e.Message); } }
public void TestRetrievePastRequests() { using (MySqlDataManipulator manipulator = new MySqlDataManipulator()) { manipulator.Connect(TestingConstants.ConnectionString); Assert.IsTrue(NetTestingUserUtils.LogInTestingUser(TestingUserStorage.ValidUser1)); var user = manipulator.GetUsersWhere(string.Format("Email=\"{0}\"", TestingUserStorage.ValidUser1.Email))[0]; List <PreviousUserRequest> currentRequests = user.DecodeRequests(); currentRequests.Add(new PreviousUserRequest() { Request = new RequestString() { Company = 1, Type = "TestingRequest" }, RequestStatus = "Completed" }); user.EncodeRequests(currentRequests); Assert.IsTrue(manipulator.UpdateUserPreviousRequests(user)); object[] contextAndRequest = ServerTestingMessageSwitchback.SwitchbackMessage( TestingUserStorage.ValidUser1.ConstructRetrievePreviousRequestsRequest( user.UserId, UserVerificationUtil.ExtractLoginTokens(user).LoginToken), "PUT"); var ctx = contextAndRequest[0] as HttpListenerContext; var req = contextAndRequest[1] as HttpWebRequest; TestApi.PUT(ctx); HttpWebResponse resp = null; try { resp = req.EndGetResponse(contextAndRequest[2] as IAsyncResult) as HttpWebResponse; } catch (Exception e) { Assert.Fail(e.Message); } using (resp) { Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode); byte[] data = new byte[resp.ContentLength]; resp.GetResponseStream().Read(data, 0, data.Length); string received = Encoding.UTF8.GetString(data); var receivedRequests = JsonDataObjectUtil <List <PreviousUserRequest> > .ParseObject(received); Assert.AreEqual(currentRequests.Count, receivedRequests.Count); for (int i = 0; i < currentRequests.Count; i++) { Assert.AreEqual(currentRequests[i], receivedRequests[i]); } } } }
public void TestUpdateUserSetting() { using (MySqlDataManipulator manipulator = new MySqlDataManipulator()) { manipulator.Connect(TestingConstants.ConnectionString); Assert.IsTrue(NetTestingUserUtils.AuthenticateTestingUser(TestingUserStorage.ValidUser1, manipulator)); var user = manipulator.GetUsersWhere(string.Format("Email=\"{0}\"", TestingUserStorage.ValidUser1.Email))[0]; user.Settings = OverallUser.GenerateDefaultSettings(); Assert.IsTrue(manipulator.UpdateUsersSettings(user)); var currentSettings = user.Settings; var loginTokens = UserVerificationUtil.ExtractLoginTokens(user); object[] contextAndRequest = ServerTestingMessageSwitchback.SwitchbackMessage( TestingUserStorage.ValidUser1.ConstructChangeSettingRequest( user.UserId, loginTokens.LoginToken, loginTokens.AuthToken, UserSettingsEntryKeys.DisplayName, "New Name #2!"), "PATCH"); var ctx = contextAndRequest[0] as HttpListenerContext; var req = contextAndRequest[1] as HttpWebRequest; TestApi.PATCH(ctx); HttpWebResponse resp = null; try { resp = req.EndGetResponse(contextAndRequest[2] as IAsyncResult) as HttpWebResponse; } catch (Exception e) { Assert.Fail(e.Message); } using (resp) Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode); user = manipulator.GetUsersWhere(string.Format("Email=\"{0}\"", TestingUserStorage.ValidUser1.Email))[0]; var newSettings = JsonDataObjectUtil <List <UserSettingsEntry> > .ParseObject(user.Settings); foreach (UserSettingsEntry entry in newSettings) { if (entry.Key == UserSettingsEntryKeys.DisplayName) { Assert.AreEqual("New Name #2!", entry.Value); break; } } } }
private void HandleAuthCheckRequest(HttpListenerContext ctx, AuthenticationCheckRequest req) { try { MySqlDataManipulator connection = new MySqlDataManipulator(); using (connection) { bool res = connection.Connect(MySqlDataManipulator.GlobalConfiguration.GetConnectionString()); if (!res) { WriteBodyResponse(ctx, 500, "Unexpected ServerError", "Connection to database failed"); return; } var user = connection.GetUserById(req.UserId); if (user == null) { WriteBodyResponse(ctx, 404, "Not Found", "User was not found on the server"); return; } if (!UserVerificationUtil.LoginTokenValid(user, req.LoginToken)) { WriteBodyResponse(ctx, 401, "Unauthorized", "Login Token is incorrect or expired"); return; } if (!UserVerificationUtil.AuthTokenValid(user, req.AuthToken)) { WriteBodylessResponse(ctx, 401, "Unauthorized"); return; } WriteBodylessResponse(ctx, 200, "OK"); } } catch (HttpListenerException) { //HttpListeners dispose themselves when an exception occurs, so we can do no more. } catch (Exception e) { WriteBodyResponse(ctx, 500, "Internal Server Error", e.Message); } }
public void TestBadRequestOnInvalidUserId() { using (MySqlDataManipulator manipulator = new MySqlDataManipulator()) { manipulator.Connect(TestingConstants.ConnectionString); Assert.IsTrue(NetTestingUserUtils.AuthenticateTestingUser(TestingUserStorage.ValidUser1, manipulator)); var user = manipulator.GetUsersWhere(string.Format("Email=\"{0}\"", TestingUserStorage.ValidUser1.Email))[0]; user.Settings = OverallUser.GenerateDefaultSettings(); Assert.IsTrue(manipulator.UpdateUsersSettings(user)); var currentSettings = user.Settings; var loginTokens = UserVerificationUtil.ExtractLoginTokens(user); object[] contextAndRequest = ServerTestingMessageSwitchback.SwitchbackMessage( TestingUserStorage.ValidUser1.ConstructChangeSettingRequest( 0, loginTokens.LoginToken, loginTokens.AuthToken, UserSettingsEntryKeys.DisplayName, "New Name #2!"), "PATCH"); var ctx = contextAndRequest[0] as HttpListenerContext; var req = contextAndRequest[1] as HttpWebRequest; TestApi.PATCH(ctx); HttpWebResponse resp = null; try { resp = req.EndGetResponse(contextAndRequest[2] as IAsyncResult) as HttpWebResponse; Assert.Fail("Expected an error response, but did not receive one"); } catch (WebException e) { resp = e.Response as HttpWebResponse; } using (resp) Assert.AreEqual(HttpStatusCode.BadRequest, resp.StatusCode); } }
/// <summary> /// PATCH request format located in the Web Api Enumeration v2 /// under the tab Company/Parts, starting row 28 /// </summary> /// <param name="ctx">HttpListenerContext to respond to</param> private void HandlePatchRequest(HttpListenerContext ctx) { try { #region Inpute Validation if (!ctx.Request.HasEntityBody) { WriteBodyResponse(ctx, 400, "Bad Request", "No Body"); return; } string reqStr; using (var reader = new StreamReader(ctx.Request.InputStream)) { reqStr = reader.ReadToEnd(); } CompanyPartsApiPatchRequest entry = JsonDataObjectUtil <CompanyPartsApiPatchRequest> .ParseObject(reqStr); if (!ValidatePatchRequest(entry)) { CompanyPartsApiDeleteRequest entry2 = JsonDataObjectUtil <CompanyPartsApiDeleteRequest> .ParseObject(reqStr); if (entry2 != null) { HandleDeleteRequest(ctx, entry2); return; } WriteBodyResponse(ctx, 400, "Bad Request", "Incorrect Format"); return; } #endregion MySqlDataManipulator connection = new MySqlDataManipulator(); using (connection) { bool res = connection.Connect(MySqlDataManipulator.GlobalConfiguration.GetConnectionString()); if (!res) { WriteBodyResponse(ctx, 500, "Unexpected Server Error", "Connection to database failed"); return; } #region User Validation OverallUser mappedUser = connection.GetUserById(entry.UserId); if (mappedUser == null) { WriteBodyResponse(ctx, 404, "Not Found", "User was not found on on the server"); return; } if (!UserVerificationUtil.LoginTokenValid(mappedUser, entry.LoginToken)) { WriteBodyResponse(ctx, 401, "Not Authorized", "Login token was incorrect."); return; } if (!UserVerificationUtil.AuthTokenValid(mappedUser, entry.AuthToken)) { WriteBodyResponse(ctx, 401, "Not Authorized", "Auth token was ezpired or incorrect"); return; } if ((mappedUser.AccessLevel & AccessLevelMasks.PartMask) == 0) { WriteBodyResponse(ctx, 401, "Not Autherized", "Not marked as a Parts User"); return; } #endregion #region Edit Parts Entry var partEntry = connection.GetPartCatalogueEntryById(mappedUser.Company, entry.PartEntryId); if (partEntry == null) { WriteBodyResponse(ctx, 404, "Not Found", "Part entry with the given id was not found"); return; } switch (entry.FieldName) { case "Make": partEntry.Make = entry.FieldValue; break; case "Model": partEntry.Model = entry.FieldValue; break; case "Year": partEntry.Year = int.Parse(entry.FieldValue); break; case "PartId": partEntry.PartId = entry.FieldValue; break; case "PartName": partEntry.PartName = entry.FieldValue; break; default: WriteBodyResponse(ctx, 404, "Not Found", "The field specified was not found"); return; } if (!connection.UpdatePartEntry(mappedUser.Company, partEntry)) { WriteBodyResponse(ctx, 500, "Internal Server Error", "Error occured while removing part entry: " + connection.LastException.Message); return; } WriteBodylessResponse(ctx, 200, "OK"); #endregion } } catch (HttpListenerException) { //HttpListeners dispose themselves when an exception occurs, so we can do no more. } catch (Exception e) { WriteBodyResponse(ctx, 500, "Internal Server Error", e.Message); } }
/// <summary> /// DELETE request format located in the Web Api Enumeration v2 /// under the tab Company/Parts, starting row 51 /// </summary> /// <param name="ctx">HttpListenerContext to respond to</param> private void HandleDeleteRequest(HttpListenerContext ctx, CompanyPartsApiDeleteRequest req) { try { #region Input Validation if (!ValidateDeleteRequest(req)) { WriteBodyResponse(ctx, 400, "Bad Request", "Incorrect Format"); return; } #endregion MySqlDataManipulator connection = new MySqlDataManipulator(); using (connection) { bool res = connection.Connect(MySqlDataManipulator.GlobalConfiguration.GetConnectionString()); if (!res) { WriteBodyResponse(ctx, 500, "Unexpected Server Error", "Connection to database failed"); return; } #region User Validation OverallUser mappedUser = connection.GetUserById(req.UserId); if (mappedUser == null) { WriteBodyResponse(ctx, 404, "Not Found", "User was not found on on the server"); return; } if (!UserVerificationUtil.LoginTokenValid(mappedUser, req.LoginToken)) { WriteBodyResponse(ctx, 401, "Not Authorized", "Login token was incorrect."); return; } if (!UserVerificationUtil.AuthTokenValid(mappedUser, req.AuthToken)) { WriteBodyResponse(ctx, 401, "Not Authorized", "Auth token was ezpired or incorrect"); return; } if ((mappedUser.AccessLevel & AccessLevelMasks.PartMask) == 0) { WriteBodyResponse(ctx, 401, "Not Autherized", "Not marked as a Parts User"); return; } #endregion #region Delete Parts Request if (connection.GetPartCatalogueEntryById(mappedUser.Company, req.PartEntryId) == null) { WriteBodyResponse(ctx, 404, "Not Found", "Part entry with the given id was not found"); return; } if (!connection.RemovePartCatalogueEntry(mappedUser.Company, req.PartEntryId)) { WriteBodyResponse(ctx, 500, "Internal Server Error", "Error occured while removing part entry: " + connection.LastException.Message); return; } WriteBodylessResponse(ctx, 200, "OK"); #endregion } } catch (HttpListenerException) { //HttpListeners dispose themselves when an exception occurs, so we can do no more. } catch (Exception e) { WriteBodyResponse(ctx, 500, "Internal Server Error", e.Message); } }
/// <summary> /// GET request format located in the Web Api Enumeration v2 /// under the tab Company/Parts, starting row 72 /// </summary> /// <param name="ctx">HttpListenerContext to respond to</param> private void HandleGetRequest(HttpListenerContext ctx) { try { #region Input Validation if (!ctx.Request.HasEntityBody) { WriteBodyResponse(ctx, 400, "Bad Request", "No Body"); return; } CompanyPartsApiGetRequest entry = JsonDataObjectUtil <CompanyPartsApiGetRequest> .ParseObject(ctx); if (!ValidateGetRequest(entry)) { WriteBodyResponse(ctx, 400, "Bad Request", "Incorrect Format"); return; } #endregion MySqlDataManipulator connection = new MySqlDataManipulator(); using (connection) { bool res = connection.Connect(MySqlDataManipulator.GlobalConfiguration.GetConnectionString()); if (!res) { WriteBodyResponse(ctx, 500, "Unexpected Server Error", "Connection to database failed"); return; } #region User Validation OverallUser mappedUser = connection.GetUserById(entry.UserId); if (mappedUser == null) { WriteBodyResponse(ctx, 404, "Not Found", "User was not found on on the server"); return; } if (!UserVerificationUtil.LoginTokenValid(mappedUser, entry.LoginToken)) { WriteBodyResponse(ctx, 401, "Not Authorized", "Login token was incorrect."); return; } if (!UserVerificationUtil.AuthTokenValid(mappedUser, entry.AuthToken)) { WriteBodyResponse(ctx, 401, "Not Authorized", "Auth token was ezpired or incorrect"); return; } if ((mappedUser.AccessLevel & AccessLevelMasks.PartMask) == 0) { WriteBodyResponse(ctx, 401, "Not Autherized", "Not marked as a Parts User"); return; } #endregion #region Get Parts List List <PartCatalogueEntry> catelogue = connection.GetPartCatalogueEntries(mappedUser.Company); JsonListStringConstructor retConstructor = new JsonListStringConstructor(); catelogue.ForEach(part => retConstructor.AddElement(WritePartCatelogueEntryToOutput(part))); WriteBodyResponse(ctx, 200, "OK", retConstructor.ToString()); #endregion } } catch (HttpListenerException) { //HttpListeners dispose themselves when an exception occurs, so we can do no more. } catch (Exception e) { WriteBodyResponse(ctx, 500, "Internal Server Error", e.Message); } }
/// <summary> /// POST request format located in the Web Api Enumeration v2 /// under the tab Company/Parts, starting row 1 /// </summary> /// <param name="ctx">HttpListenerContext to respond to</param> private void HandlePostRequest(HttpListenerContext ctx) { try { #region Input Validation if (!ctx.Request.HasEntityBody) { WriteBodyResponse(ctx, 400, "Bad Request", "No Body"); return; } CompanyPartsApiFullPostRequest entry = JsonDataObjectUtil <CompanyPartsApiFullPostRequest> .ParseObject(ctx); if (!ValidateFullPostRequest(entry)) { WriteBodyResponse(ctx, 400, "Bad Request", "Incorrect Format"); return; } #endregion MySqlDataManipulator connection = new MySqlDataManipulator(); using (connection) { bool res = connection.Connect(MySqlDataManipulator.GlobalConfiguration.GetConnectionString()); if (!res) { WriteBodyResponse(ctx, 500, "Unexpected Server Error", "Connection to database failed"); return; } #region User Validation OverallUser mappedUser = connection.GetUserById(entry.UserId); if (mappedUser == null) { WriteBodyResponse(ctx, 404, "Not Found", "User was not found on on the server"); return; } if (!UserVerificationUtil.LoginTokenValid(mappedUser, entry.LoginToken)) { WriteBodyResponse(ctx, 401, "Not Authorized", "Login token was incorrect."); return; } if (!UserVerificationUtil.AuthTokenValid(mappedUser, entry.AuthToken)) { WriteBodyResponse(ctx, 401, "Not Authorized", "Auth token was expired or incorrect"); return; } if ((mappedUser.AccessLevel & AccessLevelMasks.PartMask) == 0) { WriteBodyResponse(ctx, 401, "Not Authorized", "Not marked as a Parts User"); return; } #endregion #region Post Part PartCatalogueEntry ent = new PartCatalogueEntry(entry.Make, entry.Model, entry.Year, entry.PartId, entry.PartName); res = connection.AddPartEntry(mappedUser.Company, ent); if (!res) { WriteBodyResponse(ctx, 500, "Unexpected Server Error", connection.LastException.Message); return; } WriteBodylessResponse(ctx, 200, "OK"); #endregion } } catch (HttpListenerException) { //HttpListeners dispose themselves when an exception occurs, so we can do no more. } catch (Exception e) { WriteBodyResponse(ctx, 500, "Internal Server Error", e.Message); } }
/// <summary> /// POST request format located in the Web Api Enumeration v2 /// under the tab Company/Forum, starting row 1 /// </summary> /// <param name="ctx">HttpListenerContext to respond to</param> private void HandlePostRequest(HttpListenerContext ctx) { try { #region Input Validation if (!ctx.Request.HasEntityBody) { WriteBodyResponse(ctx, 400, "Bad Request", "No Body"); return; } CompanyForumApiFullPostRequest entry = ParseForumEntry(ctx); if (!ValidateFullPostRequest(entry)) { WriteBodyResponse(ctx, 400, "Bad Request", "Incorrect Format"); return; } #endregion //Otherwise we have a valid entry, validate user MySqlDataManipulator connection = new MySqlDataManipulator(); using (connection) { bool res = connection.Connect(MySqlDataManipulator.GlobalConfiguration.GetConnectionString()); if (!res) { WriteBodyResponse(ctx, 500, "Unexpected ServerError", "Connection to database failed"); return; } #region User Validation OverallUser mappedUser = connection.GetUserById(entry.UserId); if (!UserVerificationUtil.LoginTokenValid(mappedUser, entry.LoginToken)) { WriteBodyResponse(ctx, 401, "Not Authorized", "Login token was incorrect."); return; } if (entry.PostText.Contains('<')) { WriteBodyResponse(ctx, 400, "Bad Request", "Request contained the < character, which is disallowed due to cross site scripting attacks"); return; } CompanySettingsEntry isPublicSetting = connection.GetCompanySettingsWhere(entry.CompanyId, "SettingKey=\"" + CompanySettingsKey.Public + "\"")[0]; bool isPublic = bool.Parse(isPublicSetting.SettingValue); if (!isPublic && mappedUser.Company != entry.CompanyId) { WriteBodyResponse(ctx, 401, "Not Authorized", "Cannot access other company's private data"); return; } #endregion //user is good, add post text res = connection.AddForumPost(entry.CompanyId, entry.JobEntryId, new UserToTextEntry() { Text = entry.PostText, UserId = entry.UserId }); if (!res) { WriteBodyResponse(ctx, 500, "Unexpected Server Error", connection.LastException.Message); return; } WriteBodylessResponse(ctx, 200, "OK"); } } catch (HttpListenerException) { //HttpListeners dispose themselves when an exception occurs, so we can do no more. } catch (Exception e) { WriteBodyResponse(ctx, 500, "Internal Server Error", e.Message); } }
/// <summary> /// DELETE request format located in the Web Api Enumeration v2 /// under the tab Company/Forum, starting row 26 /// </summary> /// <param name="ctx">HttpListenerContext to respond to</param> private void HandleDeleteRequest(HttpListenerContext ctx) { try { #region Input Validation if (!ctx.Request.HasEntityBody) { WriteBodyResponse(ctx, 400, "Bad Request", "No Body"); return; } CompanyForumApiDeleteRequest entry = JsonDataObjectUtil <CompanyForumApiDeleteRequest> .ParseObject(ctx); if (!ValidateDeleteRequest(entry)) { WriteBodyResponse(ctx, 400, "Bad Request", "Incorrect Format"); return; } #endregion //Otherwise we have a valid entry, validate user MySqlDataManipulator connection = new MySqlDataManipulator(); using (connection) { bool res = connection.Connect(MySqlDataManipulator.GlobalConfiguration.GetConnectionString()); if (!res) { WriteBodyResponse(ctx, 500, "Unexpected ServerError", "Connection to database failed"); return; } #region User Validation OverallUser mappedUser = connection.GetUserById(entry.UserId); if (mappedUser == null) { WriteBodyResponse(ctx, 404, "Not Found", "User was not found on the server"); return; } if (!UserVerificationUtil.LoginTokenValid(mappedUser, entry.LoginToken)) { WriteBodyResponse(ctx, 401, "Not Authorized", "Login token was incorrect."); return; } if (!UserVerificationUtil.AuthTokenValid(mappedUser, entry.AuthToken)) { WriteBodyResponse(ctx, 401, "Not Authorized", "Auth token was expired or incorrect"); return; } #endregion #region Delete Forum UserToTextEntry forumPost = connection.GetForumPostById(mappedUser.Company, entry.JobEntryId, entry.ForumPostId); if (forumPost == null) { WriteBodylessResponse(ctx, 404, "Not Found"); return; } if (forumPost.UserId != entry.UserId) { WriteBodyResponse(ctx, 401, "Unauthorized", "Cannot delete the post of a different user"); return; } if (!connection.RemoveForumPost(mappedUser.Company, entry.JobEntryId, forumPost)) { WriteBodyResponse(ctx, 500, "Internal Server Error", "Error occured while removing forum post: " + connection.LastException.Message); return; } WriteBodylessResponse(ctx, 200, "OK"); #endregion } } catch (HttpListenerException) { //HttpListeners dispose themselves when an exception occurs, so we can do no more. } catch (Exception e) { WriteBodyResponse(ctx, 500, "Internal Server Error", e.Message); } }
/// <summary> /// GET request format located in the Web Api Enumeration v2 /// under the tab Company/Forum, starting row 49 /// </summary> /// <param name="ctx">HttpListenerContext to respond to</param> private void HandleGetRequest(HttpListenerContext ctx) { try { #region Input Validation if (!ctx.Request.HasEntityBody) { WriteBodyResponse(ctx, 400, "Bad Request", "No Body"); return; } CompanyForumApiGetRequest entry = JsonDataObjectUtil <CompanyForumApiGetRequest> .ParseObject(ctx); if (!ValidateGetRequest(entry)) { WriteBodyResponse(ctx, 400, "Bad Request", "Incorrect Format"); return; } #endregion //Otherwise we have a valid entry, validate user MySqlDataManipulator connection = new MySqlDataManipulator(); using (connection) { bool res = connection.Connect(MySqlDataManipulator.GlobalConfiguration.GetConnectionString()); if (!res) { WriteBodyResponse(ctx, 500, "Unexpected ServerError", "Connection to database failed"); return; } #region User Validation OverallUser mappedUser = connection.GetUserById(entry.UserId); if (mappedUser == null) { WriteBodyResponse(ctx, 404, "Not Found", "User was not found on the server"); return; } if (!UserVerificationUtil.LoginTokenValid(mappedUser, entry.LoginToken)) { WriteBodyResponse(ctx, 401, "Not Authorized", "Login token was incorrect."); return; } CompanySettingsEntry isPublicSetting = connection.GetCompanySettingsWhere(entry.CompanyId, "SettingKey=\"" + CompanySettingsKey.Public + "\"")[0]; bool isPublic = bool.Parse(isPublicSetting.SettingValue); if (!isPublic && mappedUser.Company != entry.CompanyId) { WriteBodyResponse(ctx, 401, "Not Authorized", "Cannot access other company's private data"); return; } #endregion #region Get Forum RepairJobEntry forumEntry = connection.GetDataEntryById(entry.CompanyId, entry.JobEntryId); if (forumEntry == null) { WriteBodyResponse(ctx, 404, "Not Found", "Job Data Entry was not found on the server"); return; } JsonListStringConstructor returnListConstructor = new JsonListStringConstructor(); JsonDictionaryStringConstructor repairJobConstructor = new JsonDictionaryStringConstructor(); repairJobConstructor.SetMapping("Make", forumEntry.Make); repairJobConstructor.SetMapping("Model", forumEntry.Model); if (forumEntry.Year == -1) { repairJobConstructor.SetMapping("Year", "Unknown"); } else { repairJobConstructor.SetMapping("Year", forumEntry.Year); } repairJobConstructor.SetMapping("Complaint", forumEntry.Complaint); repairJobConstructor.SetMapping("Problem", forumEntry.Problem); RequirementsEntry repairJobRequirements = RequirementsEntry.ParseJsonString(forumEntry.Requirements); List <string> auxillaryRequirements = new List <string>(repairJobRequirements.Auxillary.Select(req => req.Requirement)); repairJobConstructor.SetMapping("AuxillaryRequirements", auxillaryRequirements); repairJobConstructor.SetMapping("PartRequirements", repairJobRequirements.Parts); repairJobConstructor.SetMapping("SafetyRequirements", repairJobRequirements.Safety); returnListConstructor.AddElement(repairJobConstructor); List <UserToTextEntry> forumPosts = connection.GetForumPosts(mappedUser.Company, entry.JobEntryId); if (forumPosts == null) { WriteBodylessResponse(ctx, 404, "Not Found"); return; } forumPosts.ForEach(post => returnListConstructor.AddElement(ConvertForumPostToJson(post, connection))); WriteBodyResponse(ctx, 200, "OK", returnListConstructor.ToString(), "application/json"); #endregion } } catch (HttpListenerException) { //HttpListeners dispose themselves when an exception occurs, so we can do no more. } catch (Exception e) { WriteBodyResponse(ctx, 500, "Internal Server Error", e.Message); } }
/// <summary> /// Request for either negatively or positively reporting a repair job entry. Documention is found in the Web API Enumeration file /// in the /RepairJob/Report tab, starting at row 1 /// </summary> /// <param name="ctx">The HttpListenerContext to respond to</param> private void HandlePutRequest(HttpListenerContext ctx) { try { #region Input Validation if (!ctx.Request.HasEntityBody) { WriteBodyResponse(ctx, 400, "Bad Request", "No Body"); return; } RepairJobVoteRequest entry = JsonDataObjectUtil <RepairJobVoteRequest> .ParseObject(ctx); if (entry == null) { WriteBodyResponse(ctx, 400, "Bad Request", "Incorrect Format"); return; } #endregion //Otherwise we have a valid entry, validate user MySqlDataManipulator connection = new MySqlDataManipulator(); using (connection) { bool res = connection.Connect(MySqlDataManipulator.GlobalConfiguration.GetConnectionString()); if (!res) { WriteBodyResponse(ctx, 500, "Unexpected ServerError", "Connection to database failed"); return; } #region User Validation OverallUser mappedUser = connection.GetUserById(entry.UserId); if (mappedUser == null) { WriteBodyResponse(ctx, 404, "Not Found", "User Not Found"); return; } if (!ValidateVoteRequest(entry)) { WriteBodyResponse(ctx, 400, "Invalid Format", "Request was in incorrect format"); return; } if (!UserVerificationUtil.LoginTokenValid(mappedUser, entry.LoginToken)) { WriteBodyResponse(ctx, 401, "Not Authorized", "Login token was incorrect."); return; } if (!UserVerificationUtil.AuthTokenValid(mappedUser, entry.AuthToken)) { WriteBodyResponse(ctx, 401, "Not Authorized", "Auth token was expired or incorrect"); return; } #endregion #region Action Handling RepairJobEntry repairEntry = connection.GetDataEntryById(mappedUser.Company, entry.RepairJobId, true); if (repairEntry == null && connection.LastException == null) { WriteBodyResponse(ctx, 404, "Not Found", "Referenced Repair Job Was Not Found"); return; } else if (repairEntry == null) { WriteBodyResponse(ctx, 500, "Unexpected Server Error", connection.LastException.Message); return; } if (entry.Upvote == 0) { if (!connection.UpdateValidationStatus(mappedUser.Company, repairEntry, true)) { WriteBodyResponse(ctx, 500, "Unexpected Server Error", connection.LastException.Message); return; } } else { NotSupported(ctx); return; } WriteBodylessResponse(ctx, 200, "OK"); #endregion } } catch (HttpListenerException) { //HttpListeners dispose themselves when an exception occurs, so we can do no more. } catch (Exception e) { WriteBodyResponse(ctx, 500, "Internal Server Error", e.Message); } }
private void HandlePostRequest(HttpListenerContext ctx) { try { #region Input Validation if (!ctx.Request.HasEntityBody) { WriteBodyResponse(ctx, 400, "Invalid Format", "Request did not contain a body"); return; } UsableCompanyListRetrieveRequest entry = JsonDataObjectUtil <UsableCompanyListRetrieveRequest> .ParseObject(ctx); if (entry == null) { WriteBodylessResponse(ctx, 400, "Invalid Format"); return; } if (!ValidateUsableRetrieveRequest(entry)) { WriteBodyResponse(ctx, 400, "Invalid Format", "One or more fields contained an invalid value or were missing"); return; } #endregion MySqlDataManipulator connection = new MySqlDataManipulator(); using (connection) { bool res = connection.Connect(MySqlDataManipulator.GlobalConfiguration.GetConnectionString()); if (!res) { WriteBodyResponse(ctx, 500, "Unexpected Server Error", "Connection to database failed"); return; } #region User Validation OverallUser mappedUser = connection.GetUserById(entry.UserId); if (mappedUser == null) { WriteBodyResponse(ctx, 404, "Not Found", "User was not found on on the server"); return; } if (!UserVerificationUtil.LoginTokenValid(mappedUser, entry.LoginToken)) { WriteBodyResponse(ctx, 401, "Not Authorized", "Login token was incorrect."); return; } #endregion #region Post CompanyList List <CompanyId> companies = connection.GetPublicCompanies(); CompanyId userCompany = connection.GetCompanyById(mappedUser.Company); if (companies == null) { WriteBodyResponse(ctx, 500, "Internal Server Error", "Error occured while retrieving companies: " + connection.LastException.Message); return; } if (!companies.Contains(userCompany)) { companies.Add(userCompany); } JsonListStringConstructor retConstructor = new JsonListStringConstructor(); companies.ForEach(req => retConstructor.AddElement(WriteCompanyIdToOutput(req))); WriteBodyResponse(ctx, 200, "OK", retConstructor.ToString()); #endregion } } catch (HttpListenerException) { //HttpListeners dispose themselves when an exception occurs, so we can do no more. } catch (Exception e) { WriteBodyResponse(ctx, 500, "Internal Server Error", e.Message); } }
/// <summary> /// GET request format located in the Web Api Enumeration v2 google sheets document in the shared drive, /// under the tab Company/Accuracy, starting at row 1 /// </summary> /// <param name="ctx">HttpListenerContext to respond to</param> private void HandlePutRequest(HttpListenerContext ctx) { try { #region Input Validation if (!ctx.Request.HasEntityBody) { WriteBodyResponse(ctx, 400, "Bad Request", "No Body"); return; } CompanyAccuracyApiPutRequest entry = JsonDataObjectUtil <CompanyAccuracyApiPutRequest> .ParseObject(ctx); if (!ValidatePutRequest(entry)) { WriteBodyResponse(ctx, 400, "Bad Request", "Incorrect Format"); return; } #endregion MySqlDataManipulator connection = new MySqlDataManipulator(); using (connection) { bool res = connection.Connect(MySqlDataManipulator.GlobalConfiguration.GetConnectionString()); if (!res) { WriteBodyResponse(ctx, 500, "Unexpected Server Error", "Connection to database failed"); return; } #region User Validation OverallUser mappedUser = connection.GetUserById(entry.UserId); if (mappedUser == null) { WriteBodyResponse(ctx, 404, "Not Found", "User was not found on on the server"); return; } if (!UserVerificationUtil.LoginTokenValid(mappedUser, entry.LoginToken)) { WriteBodyResponse(ctx, 401, "Not Authorized", "Login token was incorrect."); return; } if ((mappedUser.AccessLevel & AccessLevelMasks.AdminMask) == 0) { WriteBodyResponse(ctx, 401, "Not Authorized", "User was not an admin"); return; } #endregion double companyAccuracy = connection.GetCompanyAccuracy(mappedUser.Company); WriteBodyResponse(ctx, 200, "OK", companyAccuracy.ToString()); } } catch (HttpListenerException) { //HttpListeners dispose themselves when an exception occurs, so we can do no more. } catch (Exception e) { WriteBodyResponse(ctx, 500, "Internal Server Error", e.Message); } }
/// <summary> /// PATCH request format located in the Web Api Enumeration v2 /// under the tab Company/Partslists/Request, starting row 95 /// </summary> /// <param name="ctx">HttpListenerContext to respond to</param> private void HandlePatchRequest(HttpListenerContext ctx) { try { #region Input Validation if (!ctx.Request.HasEntityBody) { WriteBodyResponse(ctx, 400, "Bad Request", "No Body"); return; } string reqStr; using (var reader = new StreamReader(ctx.Request.InputStream)) { reqStr = reader.ReadToEnd(); } CompanyPartsListsRequestApiPatchRequest entry = JsonDataObjectUtil <CompanyPartsListsRequestApiPatchRequest> .ParseObject(reqStr); if (!ValidatePatchRequest(entry)) { CompanyPartsListsRequestApiDeleteRequest entry2 = JsonDataObjectUtil <CompanyPartsListsRequestApiDeleteRequest> .ParseObject(reqStr); if (entry2 != null && ValidateDeleteRequest(entry2)) { HandleDeleteRequest(ctx, entry2); return; } WriteBodyResponse(ctx, 400, "Bad Request", "Incorrect Format"); return; } #endregion MySqlDataManipulator connection = new MySqlDataManipulator(); using (connection) { bool res = connection.Connect(MySqlDataManipulator.GlobalConfiguration.GetConnectionString()); if (!res) { WriteBodyResponse(ctx, 500, "Unexpected Server Error", "Connection to database failed"); return; } #region User Validation OverallUser mappedUser = connection.GetUserById(entry.UserId); if (mappedUser == null) { WriteBodyResponse(ctx, 404, "Not Found", "User was not found on on the server"); return; } if (!UserVerificationUtil.LoginTokenValid(mappedUser, entry.LoginToken)) { WriteBodyResponse(ctx, 401, "Not Authorized", "Login token was incorrect."); return; } if (!UserVerificationUtil.AuthTokenValid(mappedUser, entry.AuthToken)) { WriteBodyResponse(ctx, 401, "Not Authorized", "Auth token was ezpired or incorrect"); return; } if ((mappedUser.AccessLevel & AccessLevelMasks.PartMask) == 0) { WriteBodyResponse(ctx, 401, "Not Authorized", "User was not a parts level user"); return; } #endregion #region Action Handling var request = connection.GetPartsListAdditionRequestById(mappedUser.Company, entry.RequestId); if (request == null) { WriteBodyResponse(ctx, 404, "Not Found", "The requested request was not found"); return; } List <int> requestedParts = JsonDataObjectUtil <List <int> > .ParseObject(request.RequestedAdditions); if (entry.RequirementId >= requestedParts.Count) { WriteBodyResponse(ctx, 404, "Not Found", "The requested part to change was not found"); return; } requestedParts[entry.RequirementId] = entry.PartsRequirement; JsonListStringConstructor editConstructor = new JsonListStringConstructor(); foreach (int i in requestedParts) { editConstructor.AddElement(i); } request.RequestedAdditions = editConstructor.ToString(); if (!connection.UpdatePartsListAdditionRequest(mappedUser.Company, request)) { WriteBodyResponse(ctx, 500, "Internal Server Error", "Error occurred while attempting to update request: " + connection.LastException.Message); return; } WriteBodylessResponse(ctx, 200, "OK"); #endregion } } catch (HttpListenerException) { //HttpListeners dispose themselves when an exception occurs, so we can do no more. } catch (Exception e) { WriteBodyResponse(ctx, 500, "Internal Server Error", e.Message); } }