示例#1
0
        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);
        }
        public void TestBadRequestOnAllEmptyFields()
        {
            try
            {
                MySqlDataManipulator manipulator = new MySqlDataManipulator();
                using (manipulator)
                {
                    manipulator.Connect(TestingConstants.ConnectionString);
                    Assert.IsTrue(manipulator.RemoveUserByEmail(TestingUserStorage.ValidUser1.Email));
                    var      creationMessage   = new JsonDictionaryStringConstructor();
                    object[] contextAndRequest = ServerTestingMessageSwitchback.SwitchbackMessage(
                        creationMessage,
                        "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;
                    }
                    Assert.AreEqual(HttpStatusCode.BadRequest, resp.StatusCode);
                }
            }
            finally
            {
                TestingDatabaseCreationUtils.InitializeUsers();
            }
        }
        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);
        }
示例#4
0
        /// <summary>
        /// Converts the input <see cref="CompanyId"></see> to JSON stored in a <see cref="JsonDictionaryStringConstructor"/>
        /// </summary>
        /// <remarks>
        /// JSON format is as follows:
        /// <code>
        /// {
        ///     Id : int
        ///     LegalName : string
        /// }
        /// </code>
        /// </remarks>
        /// <param name="idIn"></param>
        /// <returns></returns>
        private JsonDictionaryStringConstructor WriteCompanyIdToOutput(CompanyId idIn)
        {
            JsonDictionaryStringConstructor ret = new JsonDictionaryStringConstructor();

            ret.SetMapping("Id", idIn.Id);
            ret.SetMapping("LegalName", idIn.LegalName);
            return(ret);
        }
示例#5
0
            public JsonDictionaryStringConstructor ConstructSecurityQuestionRequest(string loginToken, int userId)
            {
                JsonDictionaryStringConstructor ret = new JsonDictionaryStringConstructor();

                ret.SetMapping("LoginToken", loginToken);
                ret.SetMapping("UserId", userId);
                return(ret);
            }
示例#6
0
            public JsonDictionaryStringConstructor ConstructCheckLoginStatusRequest(int userId, string loginToken)
            {
                JsonDictionaryStringConstructor ret = new JsonDictionaryStringConstructor();

                ret.SetMapping("UserId", userId);
                ret.SetMapping("LoginToken", loginToken);
                return(ret);
            }
示例#7
0
            public JsonDictionaryStringConstructor ConstructLoginRequest()
            {
                JsonDictionaryStringConstructor ret = new JsonDictionaryStringConstructor();

                ret.SetMapping("Email", Email);
                ret.SetMapping("Password", Password);
                return(ret);
            }
示例#8
0
            public JsonDictionaryStringConstructor ConstructCheckAuthenticationStatusRequest(string loginToken, string authToken, int userId)
            {
                JsonDictionaryStringConstructor ret = new JsonDictionaryStringConstructor();

                ret.SetMapping("LoginToken", loginToken);
                ret.SetMapping("AuthToken", authToken);
                ret.SetMapping("UserId", userId);
                return(ret);
            }
        /// <summary>
        /// Generates a JSON string that matches the format of a RequirementsEntry object containing no requirements
        /// </summary>
        /// <returns>A JSON string that matches the format of a RequirementsEntry object containing no requirements</returns>
        public static string GenerateEmptyJson()
        {
            JsonDictionaryStringConstructor constructor = new JsonDictionaryStringConstructor();

            constructor.SetMapping("Safety", new List <object>());
            constructor.SetMapping("Parts", new List <object>());
            constructor.SetMapping("Auxillary", new List <object>());
            return(constructor.ToString());
        }
示例#10
0
            public JsonDictionaryStringConstructor ConstructReportMessage(int userId, string loginToken, string authToken, string reportedName)
            {
                JsonDictionaryStringConstructor ret = new JsonDictionaryStringConstructor();

                ret.SetMapping("UserId", userId);
                ret.SetMapping("LoginToken", loginToken);
                ret.SetMapping("AuthToken", authToken);
                ret.SetMapping("DisplayName", reportedName);
                return(ret);
            }
        public JsonDictionaryStringConstructor ConstructDeletionRequest(int userId, string loginToken, string authToken, int entryId)
        {
            JsonDictionaryStringConstructor ret = new JsonDictionaryStringConstructor();

            ret["UserId"]      = userId;
            ret["LoginToken"]  = loginToken;
            ret["AuthToken"]   = authToken;
            ret["PartEntryId"] = entryId;
            return(ret);
        }
示例#12
0
        private JsonDictionaryStringConstructor WriteSettingToOutput(CompanySettingsEntry entry)
        {
            JsonDictionaryStringConstructor ret = new JsonDictionaryStringConstructor();

            ret.SetMapping("SettingValue", entry.SettingValue);
            ret.SetMapping("SettingKey", entry.SettingKey);
            ret.SetMapping("Id", entry.Id);
            ret.SetMapping("Options", GetOptionsForKey(entry.SettingKey));
            return(ret);
        }
示例#13
0
            public JsonDictionaryStringConstructor ConstructCreationMessage()
            {
                JsonDictionaryStringConstructor ret = new JsonDictionaryStringConstructor();

                ret.SetMapping("Email", Email);
                ret.SetMapping("SecurityQuestion", SecurityQuestion);
                ret.SetMapping("SecurityAnswer", SecurityAnswer);
                ret.SetMapping("Password", Password);
                return(ret);
            }
示例#14
0
            public JsonDictionaryStringConstructor ConstructChangeSettingRequest(int userId, string loginToken, string authToken, string key, string newValue)
            {
                JsonDictionaryStringConstructor ret = new JsonDictionaryStringConstructor();

                ret.SetMapping("UserId", userId);
                ret.SetMapping("LoginToken", loginToken);
                ret.SetMapping("AuthToken", authToken);
                ret.SetMapping("Key", key);
                ret.SetMapping("Value", newValue);
                return(ret);
            }
        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);
        }
示例#16
0
        /// <summary>
        /// Attempts to return a list of the top 3 most similar complaint groups from the database
        /// </summary>
        /// <param name="entryIn">The query to predict the most similar complaint groups of</param>
        /// <param name="manipulator">The object to use to access the database</param>
        /// <param name="companyId">The id of the company the request is being made for. Determines which tables to use in the database</param>
        /// <returns>Json formatted string that contains the top 3 complaint groups that are most similar to the query made, and their database ids</returns>
        public string ProcessQueryForComplaintGroups(RepairJobEntry entryIn, MySqlDataManipulator manipulator, int companyId, int numGroupsRequested = 3)
        {
            List <string>         tokens       = SentenceTokenizer.TokenizeSentence(entryIn.Complaint);
            List <List <string> > taggedTokens = KeywordTagger.Tag(tokens);
            List <string>         keywords     = KeywordPredictor.PredictKeywords(taggedTokens);
            KeywordExample        example      = new KeywordExample();

            foreach (string keyword in keywords)
            {
                example.AddKeyword(keyword);
            }
            KeywordClusterer.Load(manipulator, companyId);
            List <int> groups = KeywordClusterer.PredictTopNSimilarGroups(example, numGroupsRequested);
            List <KeywordGroupEntry> companyComplaintGroups = manipulator.GetCompanyComplaintGroups(companyId);

            if (companyComplaintGroups == null)
            {
                throw new NullReferenceException("Company " + companyId + " complaint groups were not available in database");
            }
            List <KeywordGroupEntry> ret = new List <KeywordGroupEntry>();
            bool uncategorizedAdded      = false;

            foreach (int i in groups)
            {
                if (i == 0 && !uncategorizedAdded)
                {
                    ret.Add(new KeywordGroupEntry("Uncategorized")
                    {
                        Id = 0
                    });
                    uncategorizedAdded = true;
                }
                else if (i != 0)
                {
                    companyComplaintGroups[i - 1].Id = i;
                    ret.Add(companyComplaintGroups[i - 1]);
                }
            }
            JsonListStringConstructor constructor = new JsonListStringConstructor();

            ret.ForEach(obj => constructor.AddElement(ConvertKeywordGroupEntry(obj)));
            return(constructor.ToString());

            JsonDictionaryStringConstructor ConvertKeywordGroupEntry(KeywordGroupEntry e)
            {
                JsonDictionaryStringConstructor r = new JsonDictionaryStringConstructor();

                r.SetMapping("GroupDefinition", e.GroupDefinition);
                r.SetMapping("Id", e.Id);
                return(r);
            }
        }
        public JsonDictionaryStringConstructor ConstructAdditionRequest(int userId, string loginToken, string authToken)
        {
            JsonDictionaryStringConstructor ret = new JsonDictionaryStringConstructor();

            ret["UserId"]     = userId;
            ret["LoginToken"] = loginToken;
            ret["AuthToken"]  = authToken;
            ret["Make"]       = Make;
            ret["Model"]      = Model;
            ret["Year"]       = Year;
            ret["PartId"]     = PartId;
            ret["PartName"]   = PartName;
            return(ret);
        }
示例#18
0
            public JsonDictionaryStringConstructor ConstructCreationMessage(int Userid, String LoginToken, String AuthToken, int dup)
            {
                JsonDictionaryStringConstructor ret   = new JsonDictionaryStringConstructor();
                JsonDictionaryStringConstructor entry = new JsonDictionaryStringConstructor();

                entry.SetMapping("JobId", JobId);
                entry.SetMapping("Make", Make);
                entry.SetMapping("Model", Model);
                entry.SetMapping("Complaint", Complaint);
                entry.SetMapping("Problem", Problem);
                ret.SetMapping("ContainedEntry", entry);
                ret.SetMapping("UserId", Userid);
                ret.SetMapping("LoginToken", LoginToken);
                ret.SetMapping("AuthToken", AuthToken);
                ret.SetMapping("Duplicate", dup);
                return(ret);
            }
示例#19
0
        public static object[] SwitchbackMessage(JsonDictionaryStringConstructor messageContentsIn, string httpRequestMethod)
        {
            var            switchback    = GetSwitchback();
            var            switchbackUri = SwitchbackUri.Replace("+", "localhost");
            HttpWebRequest req           = (HttpWebRequest)WebRequest.Create(switchbackUri);

            req.Method = httpRequestMethod;
            if (!req.Method.Equals("GET"))
            {
                Stream messageStream = req.GetRequestStream();
                byte[] messageBytes  = Encoding.UTF8.GetBytes(messageContentsIn.ToString());
                req.ContentLength = messageBytes.Length;
                messageStream.Write(messageBytes, 0, messageBytes.Length);
            }
            var asyncState = req.BeginGetResponse(GetResponseCallback, null);

            return(new object[] { switchback.GetContext(), req, asyncState });
        }
示例#20
0
        private JsonDictionaryStringConstructor WritePartCatelogueEntryToOutput(PartCatalogueEntry entryOut)
        {
            JsonDictionaryStringConstructor ret = new JsonDictionaryStringConstructor();

            ret.SetMapping("Make", entryOut.Make);
            ret.SetMapping("Model", entryOut.Model);
            if (entryOut.Year == -1)
            {
                ret.SetMapping("Year", "Unknown");
            }
            else
            {
                ret.SetMapping("Year", entryOut.Year);
            }
            ret.SetMapping("PartId", entryOut.PartId);
            ret.SetMapping("PartName", entryOut.PartName);
            return(ret);
        }
示例#21
0
        public string ProcessQueryForSimilarQueriesArchive(RepairJobEntry entryIn, MySqlDataManipulator manipulator, int companyId, int problemGroupId, int numRequested, int offset = 0)
        {
            List <string>         tokens       = SentenceTokenizer.TokenizeSentence(entryIn.Problem);
            List <List <string> > taggedTokens = KeywordTagger.Tag(tokens);
            List <string>         keywords     = KeywordPredictor.PredictKeywords(taggedTokens);
            KeywordExample        example      = new KeywordExample();

            foreach (string keyword in keywords)
            {
                example.AddKeyword(keyword);
            }
            KeywordClusterer.Load(manipulator, companyId);
            List <int> groups = KeywordClusterer.PredictTopNSimilarGroups(example, 3);

            entryIn.ComplaintGroups = "[" + string.Join(',', groups) + "]";
            List <RepairJobEntry>     potentials     = manipulator.GetDataEntriesByProblemGroup(companyId, problemGroupId);
            List <EntrySimilarity>    ret            = ProblemPredictor.GetQueryResults(entryIn, potentials, numRequested, offset);
            JsonListStringConstructor retConstructor = new JsonListStringConstructor();

            ret.ForEach(obj => retConstructor.AddElement(ConvertEntrySimilarity(obj)));
            return(retConstructor.ToString());


            JsonDictionaryStringConstructor ConvertEntrySimilarity(EntrySimilarity e)
            {
                JsonDictionaryStringConstructor r = new JsonDictionaryStringConstructor();

                r.SetMapping("Make", e.Entry.Make);
                r.SetMapping("Model", e.Entry.Model);
                r.SetMapping("Complaint", e.Entry.Complaint);
                r.SetMapping("Problem", e.Entry.Problem);
                if (e.Entry.Year == -1)
                {
                    r.SetMapping("Year", "Unknown");
                }
                else
                {
                    r.SetMapping("Year", e.Entry.Year);
                }
                r.SetMapping("Id", e.Entry.Id);
                r.SetMapping("Difference", e.Difference);
                return(r);
            }
        }
示例#22
0
        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);
        }
        /// <summary>
        /// Converts the current RepairJobEntry into a JSON formatted representation of the object
        /// </summary>
        /// <remarks>
        /// <para>Format:</para>
        /// <code>
        /// {
        ///     Make : string,
        ///     Model : string,
        ///     Complaint : string,
        ///     Problem : string,
        ///     Year : string,
        ///     Id : int
        /// }
        /// </code>
        /// </remarks>
        /// <param name="e"></param>
        /// <returns><see cref="JsonDictionaryStringConstructor"/> storing the JSON data in the format displayed in the <c>remarks</c> section</returns>
        private JsonDictionaryStringConstructor ConvertEntry(RepairJobEntry e)
        {
            JsonDictionaryStringConstructor r = new JsonDictionaryStringConstructor();

            r.SetMapping("Make", e.Make);
            r.SetMapping("Model", e.Model);
            r.SetMapping("Complaint", e.Complaint);
            r.SetMapping("Problem", e.Problem);
            if (e.Year == -1)
            {
                r.SetMapping("Year", "Unknown");
            }
            else
            {
                r.SetMapping("Year", e.Year);
            }
            r.SetMapping("Id", e.Id);
            return(r);
        }
        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);
        }
示例#25
0
        /// <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);
            }
        }
示例#26
0
        /// <summary>
        /// Request for a user to receive authentication to make edits to content they have access to. 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 HandlePutRequest(HttpListenerContext ctx)
        {
            try
            {
                #region Input Validation
                if (!ctx.Request.HasEntityBody)
                {
                    WriteBodyResponse(ctx, 400, "No Body", "Request lacked a body");
                    return;
                }
                string reqString          = new StreamReader(ctx.Request.InputStream).ReadToEnd();
                AuthenticationRequest req = JsonDataObjectUtil <AuthenticationRequest> .ParseObject(reqString);

                if (req == null)
                {
                    WriteBodyResponse(ctx, 400, "Incorrect Format", "Request was in the wrong format");
                    return;
                }
                if (!ValidateAuthenticationRequest(req))
                {
                    AuthenticationCheckRequest req2 = JsonDataObjectUtil <AuthenticationCheckRequest> .ParseObject(reqString);

                    if (req2 != null && ValidateAuthCheckRequest(req2))
                    {
                        HandleAuthCheckRequest(ctx, req2);
                        return;
                    }
                    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 User Validation
                    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.VerifyAuthentication(user, req.SecurityQuestion, req.SecurityAnswer))
                    {
                        WriteBodyResponse(ctx, 401, "Unauthorized", "Security Answer was incorrect");
                        return;
                    }
                    #endregion

                    #region Action Handling
                    LoginStatusTokens tokens = UserVerificationUtil.ExtractLoginTokens(user);
                    UserVerificationUtil.GenerateNewAuthToken(tokens);
                    if (!connection.UpdateUsersLoginToken(user, tokens))
                    {
                        WriteBodyResponse(ctx, 500, "Unexpected Server Error", "Failed to write login token to database");
                        return;
                    }
                    JsonDictionaryStringConstructor retConstructor = new JsonDictionaryStringConstructor();
                    retConstructor.SetMapping("token", tokens.AuthToken);
                    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);
            }
        }
示例#27
0
        /// <summary>
        /// Request for a user to log in using their email and password. 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>
        public void HandlePutRequest(HttpListenerContext ctx)
        {
            try
            {
                #region Input Validation
                if (!ctx.Request.HasEntityBody)
                {
                    WriteBodyResponse(ctx, 400, "No Body", "Request lacked a body");
                    return;
                }
                string           reqString = new StreamReader(ctx.Request.InputStream).ReadToEnd();
                UserLoginRequest req       = JsonDataObjectUtil <UserLoginRequest> .ParseObject(reqString);

                if (req == null)
                {
                    WriteBodyResponse(ctx, 400, "Incorrect Format", "Request was in the wrong format");
                    return;
                }
                if (!ValidateLoginRequest(req))
                {
                    UserCheckLoginStatusRequest req2 = JsonDataObjectUtil <UserCheckLoginStatusRequest> .ParseObject(reqString);

                    if (req2 != null && ValidateCheckLoginRequest(req2))
                    {
                        HandleCheckLoginRequest(ctx, req2);
                        return;
                    }
                    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.Count == 0)
                    {
                        WriteBodyResponse(ctx, 404, "Not Found", "User was not found on the server");
                        return;
                    }
                    if (!UserVerificationUtil.VerifyLogin(users[0], req.Email, req.Password))
                    {
                        WriteBodyResponse(ctx, 401, "Unauthorized", "Email or password was incorrect");
                        return;
                    }
                    OverallUser       loggedInUser = users[0];
                    LoginStatusTokens tokens       = UserVerificationUtil.ExtractLoginTokens(loggedInUser);
                    UserVerificationUtil.GenerateNewLoginToken(tokens);
                    if (!connection.UpdateUsersLoginToken(loggedInUser, tokens))
                    {
                        WriteBodyResponse(ctx, 500, "Unexpected Server Error", "Failed to write login token to database");
                        return;
                    }
                    JsonDictionaryStringConstructor retConstructor = new JsonDictionaryStringConstructor();
                    retConstructor.SetMapping("token", tokens.LoginToken);
                    retConstructor.SetMapping("userId", loggedInUser.UserId);
                    retConstructor.SetMapping("accessLevel", loggedInUser.AccessLevel);
                    WriteBodyResponse(ctx, 200, "OK", retConstructor.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 adding a repair job entry. Documention is found in the Web API Enumeration file
        /// in the /RepairJob 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;
                }
                RepairJobApiRequest entry = JsonDataObjectUtil <RepairJobApiRequest> .ParseObject(ctx);

                if (!ValidateFullRequest(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 Input Sanitation
                    if (entry.ContainedEntry.Complaint.Contains('<'))
                    {
                        WriteBodyResponse(ctx, 400, "Bad Request", "Request contained the < character, which is disallowed due to cross site scripting attacks");
                        return;
                    }
                    if (entry.ContainedEntry.Problem.Contains('<'))
                    {
                        WriteBodyResponse(ctx, 400, "Bad Request", "Request contained the < character, which is disallowed due to cross site scripting attacks");
                        return;
                    }
                    if (entry.ContainedEntry.Make.Contains('<'))
                    {
                        WriteBodyResponse(ctx, 400, "Bad Request", "Request contained the < character, which is disallowed due to cross site scripting attacks");
                        return;
                    }
                    if (entry.ContainedEntry.Model.Contains('<'))
                    {
                        WriteBodyResponse(ctx, 400, "Bad Request", "Request contained the < character, which is disallowed due to cross site scripting attacks");
                        return;
                    }
                    if (entry.ContainedEntry.JobId.Contains('<'))
                    {
                        WriteBodyResponse(ctx, 400, "Bad Request", "Request contained the < character, which is disallowed due to cross site scripting attacks");
                        return;
                    }
                    #endregion

                    #region Action Handling

                    #region Forced Upload
                    if (!(entry.Duplicate == 0))
                    {
                        //Now that we know the user is good, actually do the addition.
                        res = connection.AddDataEntry(mappedUser.Company, entry.ContainedEntry);
                        if (!res)
                        {
                            WriteBodyResponse(ctx, 500, "Unexpected Server Error", connection.LastException.Message);
                            return;
                        }
                        WriteBodylessResponse(ctx, 200, "OK");
                    }
                    #endregion

                    else
                    {
                        //test if there exists similar
                        string whereString = "Make =\"" + entry.ContainedEntry.Make + "\" AND " + "Model =\"" + entry.ContainedEntry.Model + "\"";
                        //whereString += "AND"+entry.ContainedEntry.Year+">="+(entry.ContainedEntry.Year-2)+"AND"+entry.ContainedEntry.Year+"<="+(entry.ContainedEntry.Year+2);
                        List <RepairJobEntry> dataCollectionsWhere = connection.GetDataEntriesWhere(mappedUser.Company, whereString, true);
                        List <RepairJobEntry> data2 = connection.GetDataEntriesWhere(mappedUser.Company, whereString, false);
                        foreach (RepairJobEntry x in data2)
                        {
                            dataCollectionsWhere.Add(x);
                        }
                        #region No Similar Jobs
                        //if none force through
                        if (dataCollectionsWhere.Count == 0)
                        {
                            res = connection.AddDataEntry(mappedUser.Company, entry.ContainedEntry);
                            if (!res)
                            {
                                WriteBodyResponse(ctx, 500, "Unexpected Server Error", connection.LastException.Message);
                                return;
                            }
                            WriteBodylessResponse(ctx, 200, "OK");
                        }
                        #endregion

                        #region Similar Jobs Return
                        //if yes 409 with similar jobs
                        else
                        {
                            JsonListStringConstructor retConstructor = new JsonListStringConstructor();
                            List <EntrySimilarity>    ret            = getSimilar(entry.ContainedEntry, dataCollectionsWhere, 3);
                            if (ret.Count == 0)
                            {
                                res = connection.AddDataEntry(mappedUser.Company, entry.ContainedEntry);
                                if (!res)
                                {
                                    WriteBodyResponse(ctx, 500, "Unexpected Server Error", connection.LastException.Message);
                                    return;
                                }
                                WriteBodylessResponse(ctx, 200, "OK");
                            }
                            ret.ForEach(obj => retConstructor.AddElement(ConvertEntrySimilarity(obj)));
                            WriteBodyResponse(ctx, 409, "Conflict", retConstructor.ToString(), "application/json");

                            JsonDictionaryStringConstructor ConvertEntrySimilarity(EntrySimilarity e)
                            {
                                JsonDictionaryStringConstructor r = new JsonDictionaryStringConstructor();

                                r.SetMapping("Make", e.Entry.Make);
                                r.SetMapping("Model", e.Entry.Model);
                                r.SetMapping("Complaint", e.Entry.Complaint);
                                r.SetMapping("Problem", e.Entry.Problem);
                                if (e.Entry.Year == -1)
                                {
                                    r.SetMapping("Year", "Unknown");
                                }
                                else
                                {
                                    r.SetMapping("Year", e.Entry.Year);
                                }
                                r.SetMapping("Id", e.Entry.Id);
                                return(r);
                            }
                        }
                        #endregion
                    }
                    #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);
            }
        }