private JsonDictionaryStringConstructor WritePartsRequestToOutput(PartsRequest request, MySqlDataManipulator manipulator, int companyId) { JsonDictionaryStringConstructor ret = new JsonDictionaryStringConstructor(); var user = manipulator.GetUserById(request.UserId); if (user == null) { ret.SetMapping("DisplayName", "defaultUser"); } else { List <UserSettingsEntry> entries = JsonDataObjectUtil <List <UserSettingsEntry> > .ParseObject(user.Settings); ret.SetMapping("DisplayName", entries.Where(entry => entry.Key.Equals(UserSettingsEntryKeys.DisplayName)).First().Value); } List <int> referencedParts = JsonDataObjectUtil <List <int> > .ParseObject(request.ReferencedParts); JsonListStringConstructor partsConstructor = new JsonListStringConstructor(); foreach (int i in referencedParts) { var part = manipulator.GetPartCatalogueEntryById(companyId, i); if (part == null) { continue; } partsConstructor.AddElement(part.PartId); } ret.SetMapping("ReferencedParts", partsConstructor); ret.SetMapping("JobId", request.JobId); ret.SetMapping("Id", request.Id); return(ret); }
/// <summary> /// <para>Uses the supplied <see cref="MySqlDataManipulator"/> to add the setting to all of the specified targets</para> /// </summary> /// <param name="manipulator"></param> public override void PerformFunction(MySqlDataManipulator manipulator) { if (Target.Equals("user")) { var users = manipulator.GetUsersWhere("id > 0"); foreach (OverallUser user in users) { //Add the setting to the user if they do not already have a setting with the same key List <UserSettingsEntry> settings = JsonDataObjectUtil <List <UserSettingsEntry> > .ParseObject(user.Settings); bool found = false; foreach (UserSettingsEntry entry in settings) { if (entry.Key.Equals(Key)) { found = true; break; } } if (!found) { settings.Add(new UserSettingsEntry() { Key = Key, Value = Value }); user.Settings = JsonDataObjectUtil <List <UserSettingsEntry> > .ConvertObject(settings); if (!manipulator.UpdateUsersSettings(user)) { Console.WriteLine("Failed to update settings for user " + user.UserId); continue; } Console.WriteLine("Updated settings for user " + user.UserId); continue; } Console.WriteLine("User " + user.UserId + " already had a setting with key " + Key); } } else if (Target.Equals("company")) { var companies = manipulator.GetCompaniesWithNamePortion(""); foreach (CompanyId company in companies) { //Add the setting to the company if it does not already have one with the same key int companyId = company.Id; bool found = manipulator.GetCompanySettingsWhere(companyId, "SettingKey = \"" + Key + "\"").Count == 1; if (!found) { if (!manipulator.AddCompanySetting(companyId, new CompanySettingsEntry(Key, Value))) { Console.WriteLine("Company " + company.LegalName + " failed to have the setting added"); continue; } Console.WriteLine("Successfully added setting for company " + company.LegalName); continue; } Console.WriteLine("Company " + company.LegalName + " already had a setting with key " + Key); } } }
public override void PerformFunction(MySqlDataManipulator manipulator) { //Ensure that all KeywordPredictor models are loaded //If one is not, then a company requesting that model through its settings will cause an error if (!GlobalModelHelper.LoadOrTrainGlobalModels(ReflectionHelper.GetAllKeywordPredictors())) { throw new NullReferenceException("One or more global models failed to load. Server cannot start."); } DatabaseQueryProcessor processor = new DatabaseQueryProcessor(DatabaseQueryProcessorSettings.RetrieveCompanySettings(manipulator, CompanyId)); List <RepairJobEntry> validatedData = manipulator.GetDataEntriesWhere(CompanyId, "id > 0", validated: true); List <string> sentences; if (Flag.ToLower().Equals("complaint")) { //train model sentences = validatedData.Select(entry => entry.Complaint).ToList(); if (!processor.TrainClusteringModels(manipulator, CompanyId, sentences, false)) { Console.WriteLine("Failed to train problem prediction models for company " + CompanyId); return; } //register the complaint groups that the clusterer predicts with the repair job entry in the database foreach (RepairJobEntry entry in validatedData) { string groups = JsonDataObjectUtil <List <int> > .ConvertObject(processor.PredictGroupsInJobData(entry, CompanyId, manipulator)); entry.ComplaintGroups = groups; manipulator.UpdateDataEntryGroups(CompanyId, entry, complaint: true); } } Console.WriteLine("Trained clustering models for company " + CompanyId); }
private JsonDictionaryStringConstructor WriteSafetyRequestToOutput(RequirementAdditionRequest request, MySqlDataManipulator connection, int companyId) { JsonDictionaryStringConstructor ret = new JsonDictionaryStringConstructor(); var user = connection.GetUserById(request.UserId); if (user == null) { ret.SetMapping("DisplayName", "Unknown User"); } else { List <UserSettingsEntry> userSettings = JsonDataObjectUtil <List <UserSettingsEntry> > .ParseObject(user.Settings); ret.SetMapping("DisplayName", userSettings.Where(entry => entry.Key.Equals(UserSettingsEntryKeys.DisplayName)).First().Value); } ret.SetMapping("RequestedAdditions", request.RequestedAdditions); var job = connection.GetDataEntryById(companyId, request.ValidatedDataId); if (job == null) { ret.SetMapping("JobId", "Unknown"); } else { ret.SetMapping("JobId", job.JobId); } ret.SetMapping("Id", request.Id); return(ret); }
/// <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)); } } }
private JsonDictionaryStringConstructor ConvertUserToOutput(OverallUser toConvert) { JsonDictionaryStringConstructor ret = new JsonDictionaryStringConstructor(); ret.SetMapping("Access Level", toConvert.AccessLevel); ret.SetMapping("Email", toConvert.Email); ret.SetMapping("DatabaseId", toConvert.UserId); List <UserSettingsEntry> entries = JsonDataObjectUtil <List <UserSettingsEntry> > .ParseObject(toConvert.Settings); ret.SetMapping("Display Name", entries.Where(obj => obj.Key.Equals(UserSettingsEntryKeys.DisplayName)).First().Value); return(ret); }
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 JsonDictionaryStringConstructor ConvertForumPostToJson(UserToTextEntry forumPost, MySqlDataManipulator connection) { JsonDictionaryStringConstructor retConstructor = new JsonDictionaryStringConstructor(); var user = connection.GetUserById(forumPost.UserId); if (user == null) { retConstructor.SetMapping("DisplayName", "Unknown User"); } else { List <UserSettingsEntry> userSettings = JsonDataObjectUtil <List <UserSettingsEntry> > .ParseObject(user.Settings); retConstructor.SetMapping("DisplayName", userSettings.Where(entry => entry.Key.Equals(UserSettingsEntryKeys.DisplayName)).First().Value); } retConstructor.SetMapping("PostText", forumPost.Text); retConstructor.SetMapping("ForumPostId", forumPost.Id); return(retConstructor); }
public override void PerformFunction(MySqlDataManipulator manipulator) { StreamReader fileReader = new StreamReader(FilePath); string jsonString = fileReader.ReadToEnd(); fileReader.Close(); List <RepairJobEntry> loadedData = JsonDataObjectUtil <List <RepairJobEntry> > .ParseObject(jsonString); foreach (RepairJobEntry entry in loadedData) { entry.Make = entry.Make.ToLower(); entry.Model = entry.Model.ToLower(); entry.Complaint = entry.Complaint.ToLower(); entry.Problem = entry.Problem.ToLower(); if (!manipulator.AddDataEntry(CompanyId, entry, validated: true)) { Console.WriteLine(JsonDataObjectUtil <RepairJobEntry> .ConvertObject(entry) + " was not added to the database"); } } }
private JsonDictionaryStringConstructor WriteJoinRequestToOutput(JoinRequest requestIn, MySqlDataManipulator connection) { JsonDictionaryStringConstructor ret = new JsonDictionaryStringConstructor(); ret.SetMapping("Id", requestIn.Id); var user = connection.GetUserById(requestIn.UserId); if (user == null) { ret.SetMapping("DisplayName", "Unknown"); ret.SetMapping("Email", "Unknown"); } else { var userSettings = JsonDataObjectUtil <List <UserSettingsEntry> > .ParseObject(user.Settings); ret.SetMapping("DisplayName", userSettings.Where(entry => entry.Key.Equals(UserSettingsEntryKeys.DisplayName)).First().Value); ret.SetMapping("Email", user.Email); } return(ret); }
public override void PerformFunction(MySqlDataManipulator manipulator) { //Convert all MechanicQueries to RepairJobEntries FileSystemDataSource dataSource = new FileSystemDataSource(); List <MechanicQuery> queries = dataSource.LoadMechanicQueries(); List <RepairJobEntry> toWrite = new List <RepairJobEntry>(); foreach (MechanicQuery query in queries) { RepairJobEntry toAdd = new RepairJobEntry() { Make = query.Make, Model = query.Model, Complaint = query.Complaint, Problem = query.Problem, JobId = "Unknown", Year = -1 }; toWrite.Add(toAdd); } //Write all RepairJobEntries to the specified file StreamWriter fileWriter = new StreamWriter(FilePath); //This is a CLI for devs, so no worries if this goes wonky fileWriter.WriteLine('['); foreach (RepairJobEntry entry in toWrite) { string entryJson = JsonDataObjectUtil <RepairJobEntry> .ConvertObject(entry); fileWriter.WriteLine(entryJson); } fileWriter.WriteLine(']'); fileWriter.Close(); }
/// <summary> /// PATCH request format located in the Web Api Enumeration v2 /// under the tab Company/Settings, starting row 27 /// </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, "No Body", "Request lacked a body"); return; } CompanySettingsApiPatchRequest entry = JsonDataObjectUtil <CompanySettingsApiPatchRequest> .ParseObject(ctx); if (entry == null) { WriteBodyResponse(ctx, 400, "Incorrect Format", "Request was in the wrong format"); return; } if (!ValidatePatchRequest(entry)) { WriteBodyResponse(ctx, 400, "Incorrect Format", "Not all fields in 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 User Validation var user = connection.GetUserById(entry.UserId); if (user == null) { WriteBodyResponse(ctx, 404, "Not Found", "User was not found on the server"); return; } List <CompanySettingsEntry> entries = connection.GetCompanySettings(user.Company); if (entries == null) { WriteBodyResponse(ctx, 500, "Internal Server Error", "Error occured while retrieving settings: " + connection.LastException.Message); return; } #endregion #region Action Handling var toModify = entries.Where(obj => obj.SettingKey.Equals(entry.SettingsKey)).FirstOrDefault(); if (toModify == null) { WriteBodyResponse(ctx, 404, "Not Found", "Setting with the specified key was not found on the server"); return; } toModify.SettingValue = entry.SettingsValue; if (!connection.UpdateCompanySettings(user.Company, toModify)) { WriteBodyResponse(ctx, 500, "Internal Server Error", "Error occurred while updating company's settings: " + 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", "Error occurred while processing request: " + 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 HandlePutRequest(HttpListenerContext ctx) { try { #region Input Validation if (!ctx.Request.HasEntityBody) { WriteBodyResponse(ctx, 400, "Bad Request", "No Body"); return; } ArchiveApiPutRequest req = JsonDataObjectUtil <ArchiveApiPutRequest> .ParseObject(ctx); if (!ValidatePutRequest(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 Validate User 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; } CompanySettingsEntry isPublicSetting = connection.GetCompanySettingsWhere(req.CompanyId, "SettingKey=\"" + CompanySettingsKey.Public + "\"")[0]; bool isPublic = bool.Parse(isPublicSetting.SettingValue); if (!isPublic && mappedUser.Company != req.CompanyId) { WriteBodyResponse(ctx, 401, "Not Authorized", "Cannot access other company's private data"); return; } #endregion UserSettingsEntry numPredictionsRequested = JsonDataObjectUtil <List <UserSettingsEntry> > .ParseObject(mappedUser.Settings).FirstOrDefault(entry => entry.Key.Equals(UserSettingsEntryKeys.ArchiveQueryResults)); if (numPredictionsRequested == null) { WriteBodyResponse(ctx, 500, "Internal Server Error", "User did not contain a setting with a key " + UserSettingsEntryKeys.ArchiveQueryResults); return; } int numRequested = int.Parse(numPredictionsRequested.Value); #region Input sanitation string whereString = ""; bool addedWhere = false; if (req.Entry.Complaint != null) { if (!PerformSanitization(req.Entry.Complaint)) { return; } whereString += " Complaint like \"%" + req.Entry.Complaint + "%\""; addedWhere = true; } if (req.Entry.Problem != null) { if (!PerformSanitization(req.Entry.Problem)) { return; } if (addedWhere) { whereString += " and"; } whereString += " Problem like \"%" + req.Entry.Problem + "%\""; addedWhere = true; } if (req.Entry.Make != null) { if (!PerformSanitization(req.Entry.Make)) { return; } if (addedWhere) { whereString += " and"; } whereString += " Make like \"%" + req.Entry.Make + "%\""; addedWhere = true; } if (req.Entry.Model != null) { if (!PerformSanitization(req.Entry.Model)) { return; } if (addedWhere) { whereString += " and"; } whereString += " Model like \"%" + req.Entry.Model + "%\""; addedWhere = true; } if (req.Entry.Year != 0) { if (addedWhere) { whereString += " and"; } whereString += " Year =" + req.Entry.Year; addedWhere = true; } #endregion if (!addedWhere) { WriteBodyResponse(ctx, 400, "Bad Request", "No fields in the request's entry were filled"); return; } List <RepairJobEntry> entries = connection.GetDataEntriesWhere(req.CompanyId, whereString, true); JsonListStringConstructor retConstructor = new JsonListStringConstructor(); try { entries.ForEach(entry => retConstructor.AddElement(ConvertEntry(entry))); } catch (NullReferenceException) { WriteBodyResponse(ctx, 200, "OK", "[]", "application/json"); return; } WriteBodyResponse(ctx, 200, "OK", retConstructor.ToString(), "application/json"); bool PerformSanitization(string queryIn) { if (queryIn.Contains('`')) { WriteBodyResponse(ctx, 400, "Bad Request", "Request contained the single quote character, which is disallowed due to MySQL injection attacks"); return(false); } return(true); } } } catch (HttpListenerException) { //HttpListeners dispose themselves when an exception occurs, so we can do no more. } catch (Exception e) { WriteBodyResponse(ctx, 500, "Internal Server Error", "Error occurred during processing of request: " + 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); } }
/// <summary> /// GET request format located in the Web Api Enumeration v2 /// under the tab Company/Settings, starting 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, "No Body", "Request lacked a body"); return; } CompanySettingsApiPutRequest entry = JsonDataObjectUtil <CompanySettingsApiPutRequest> .ParseObject(ctx); if (entry == null) { WriteBodyResponse(ctx, 400, "Incorrect Format", "Request was in the wrong format"); return; } if (!ValidatePutRequest(entry)) { WriteBodyResponse(ctx, 400, "Incorrect Format", "Not all fields in 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 User Validation var user = connection.GetUserById(entry.UserId); if (user == null) { WriteBodyResponse(ctx, 404, "Not Found", "User was not found on the server"); return; } #endregion #region Action Handling List <CompanySettingsEntry> entries = connection.GetCompanySettings(user.Company); if (entries == null) { WriteBodyResponse(ctx, 500, "Internal Server Error", "Error occured while retrieving settings: " + connection.LastException.Message); return; } JsonListStringConstructor retConstructor = new JsonListStringConstructor(); entries.ForEach(obj => retConstructor.AddElement(WriteSettingToOutput(obj))); 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", "Error occurred while processing request: " + e.Message); } }
/// <summary> /// Request for creating a base mechanic user account. Documention is found in the Web API Enumeration file /// in the /RepairJob/Requirements tab, starting at row 1 /// </summary> /// <param name="ctx">The HttpListenerContext to respond to</param> public void HandlePostRequest(HttpListenerContext ctx) { try { #region Input Validation if (!ctx.Request.HasEntityBody) { WriteBodyResponse(ctx, 400, "No Body", "Request lacked a body"); return; } UserCreationRequest req = JsonDataObjectUtil <UserCreationRequest> .ParseObject(ctx); if (req == null) { WriteBodyResponse(ctx, 400, "Incorrect Format", "Request was in the wrong format"); return; } if (!ValidateCreationResponse(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 users = connection.GetUsersWhere(" Email = \"" + req.Email + "\""); if (users == null) { WriteBodyResponse(ctx, 500, "Unexpected Server Error", connection.LastException.Message); return; } if (users.Count > 0) { WriteBodyResponse(ctx, 409, "User Conflict", "User with email already exists"); return; } res = connection.AddUser(req.Email, req.Password, req.SecurityQuestion, req.SecurityAnswer); if (!res) { WriteBodyResponse(ctx, 500, "Unexpected ServerError", 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> /// 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> /// Request for adding an auxillary requirement to a repair job entry. Documention is found in the Web API Enumeration file /// in the /RepairJob/Requirements 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, "Bad Request", "No Body"); return; } RequirementsPostRequest entry = JsonDataObjectUtil <RequirementsPostRequest> .ParseObject(ctx); if (!ValidatePostRequest(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 (!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, false); 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; } //User is authenticated, and the job entry exists.... time to edit the requirements RequirementsEntry requirementsEntry = RequirementsEntry.ParseJsonString(repairEntry.Requirements); if (requirementsEntry == null) { WriteBodylessResponse(ctx, 500, "Unexpected Server Error"); return; } requirementsEntry.Auxillary.Add(new AuxillaryRequirement() { Downvotes = 0, Requirement = entry.RequirementString, UserId = entry.UserId }); repairEntry.Requirements = requirementsEntry.GenerateJsonString(); if (!connection.UpdateDataEntryRequirements(mappedUser.Company, repairEntry, false)) { 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> /// Request for down voting an auxillary requirement in a repair job entry. Documention is found in the Web API Enumeration file /// in the /RepairJob/Requirements tab, starting at row 21 /// </summary> /// <param name="ctx">The 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; } RequirementsDownvoteRequest entry = JsonDataObjectUtil <RequirementsDownvoteRequest> .ParseObject(ctx); if (!ValidateDownvoteRequest(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 (!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, false); 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; } //User is authenticated, and the job entry exists.... time to edit the requirements RequirementsEntry requirementsEntry = RequirementsEntry.ParseJsonString(repairEntry.Requirements); if (requirementsEntry == null) { WriteBodylessResponse(ctx, 500, "Unexpected Server Error"); return; } if (entry.RequirementId >= requirementsEntry.Auxillary.Count) { WriteBodylessResponse(ctx, 404, "Could not find a requirement with id " + entry.RequirementId); } if (requirementsEntry.Auxillary[entry.RequirementId].UserId == mappedUser.UserId || (mappedUser.AccessLevel & AccessLevelMasks.AdminMask) != 0) { requirementsEntry.Auxillary.RemoveAt(entry.RequirementId); } else { requirementsEntry.Auxillary[entry.RequirementId].Downvotes++; //TODO: Once company settings are completed, search in the company's settings to see if the //downvotes are high enough to warrent removal } repairEntry.Requirements = requirementsEntry.GenerateJsonString(); if (!connection.UpdateDataEntryRequirements(mappedUser.Company, repairEntry, false)) { 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/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> /// PUT request format located in the Web Api Enumeration v2 /// under the tab Company/Safety/Request, starting row 49 /// </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; } string reqStr = new StreamReader(ctx.Request.InputStream).ReadToEnd(); CompanySafetyRequestApiPutRequest entry = JsonDataObjectUtil <CompanySafetyRequestApiPutRequest> .ParseObject(reqStr); if (!ValidatePutRequest(entry)) { CompanySafetyRequestApiGetRequest entry2 = JsonDataObjectUtil <CompanySafetyRequestApiGetRequest> .ParseObject(reqStr); if (entry2 != null && ValidateGetRequest(entry2)) { HandleGetRequest(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.SafetyMask) == 0) { WriteBodyResponse(ctx, 401, "Not Authorized", "User was not a safety level user"); return; } #endregion #region Action Handling var request = connection.GetSafetyAdditionRequestById(mappedUser.Company, entry.RequestId); if (request == null) { WriteBodyResponse(ctx, 404, "Not Found", "The requested request was not found"); return; } if (!connection.RemoveSafetyAdditionRequest(mappedUser.Company, entry.RequestId, accept: true)) { WriteBodyResponse(ctx, 500, "Internal Server Error", "Error ocurred while removing 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); } }
/// <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> /// POST request format located in the Web Api Enumeration v2 /// under the tab Company/Partslists/Request, 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; } CompanyPartslistsRequestApiFullPostRequest entry = JsonDataObjectUtil <CompanyPartslistsRequestApiFullPostRequest> .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 ezpired or incorrect"); return; } #endregion #region Add Part Requirement List <int> requiredPartsList = JsonDataObjectUtil <List <int> > .ParseObject(entry.RequiredPartsList); foreach (int i in requiredPartsList) { RequirementAdditionRequest request = new RequirementAdditionRequest(entry.UserId, entry.RepairJobId, i.ToString()); res = connection.AddPartsListAdditionRequest(entry.CompanyId, request); if (!res) { WriteBodyResponse(ctx, 500, "Unexpected Server Error", connection.LastException.Message); return; } } WriteBodylessResponse(ctx, 200, "OK"); #endregion } } catch (Exception e) { WriteBodyResponse(ctx, 500, "Internal Server Error", e.Message); } }