Example #1
0
        private static ServiceCallStatus SendFinalResponse(
            [CanBeNull] QualityVerification verification,
            [CanBeNull] string qaServiceCancellationMessage,
            ConcurrentBag <IssueMsg> issues,
            List <GdbObjRefMsg> deletableAllowedErrors,
            [CanBeNull] IEnvelope verifiedPerimeter,
            Action <VerificationResponse> writeAction)
        {
            var response = new VerificationResponse();

            while (issues.TryTake(out IssueMsg issue))
            {
                response.Issues.Add(issue);
            }

            response.ObsoleteExceptions.AddRange(deletableAllowedErrors);

            ServiceCallStatus finalStatus =
                GetFinalCallStatus(verification, qaServiceCancellationMessage);

            response.ServiceCallStatus = (int)finalStatus;

            if (!string.IsNullOrEmpty(qaServiceCancellationMessage))
            {
                response.Progress = new VerificationProgressMsg
                {
                    Message = qaServiceCancellationMessage
                };
            }

            PackVerification(verification, response);

            if (verifiedPerimeter != null)
            {
                response.VerifiedPerimeter =
                    ProtobufGeometryUtils.ToShapeMsg(verifiedPerimeter);
            }

            _msg.DebugFormat(
                "Sending final message with {0} errors back to client...",
                issues.Count);

            try
            {
                writeAction(response);
            }
            catch (InvalidOperationException ex)
            {
                // For example: System.InvalidOperationException: Only one write can be pending at a time
                _msg.Warn(
                    "Error sending progress to the client. Retrying the last response in 1s...",
                    ex);

                // Re-try (only for final message)
                Task.Delay(1000);
                writeAction(response);
            }

            return(finalStatus);
        }
Example #2
0
        public void GetVerificationResponse_WhenResourceIsFoundMultipleTimes_ReturnsVerificationResponsesWithCorrectInvocationCount()
        {
            var sut = CreateSut();

            sut.PurgeData <Requests>();
            sut.PurgeData <Responses>();

            var requestId1 = sut.StoreRequest("/testResource", HttpMethod.Get, "test".ToAsciiBytes());
            var requestId2 = sut.StoreRequest("/testResource", HttpMethod.Get, "test".ToAsciiBytes());

            Expression <Func <Request, bool> > expr = r => r.Content.Contains("test");

            sut.StoreResponse(requestId1, "test", expr.ToString(), "test".ToAsciiBytes());
            sut.StoreResponse(requestId2, "test", expr.ToString(), "test".ToAsciiBytes());

            var verificationReponses = sut.GetVerificationResponse("/testResource", HttpMethod.Get, "test".ToAsciiBytes());

            var expectedObject =
                new VerificationResponse()
            {
                Resource        = "/testResource",
                InvocationCount = 2,
                RequestPayload  = "test"
            };

            verificationReponses
            .Should().BeEquivalentTo(expectedObject);
        }
Example #3
0
        private void HandleProgressMsg(VerificationResponse responseMsg)
        {
            Progress.RemoteCallStatus =
                (ServiceCallStatus)responseMsg.ServiceCallStatus;

            foreach (IssueMsg issueMessage in responseMsg.Issues)
            {
                ResultIssueCollector?.AddIssueMessage(issueMessage);
            }

            foreach (GdbObjRefMsg objRefMsg in responseMsg.ObsoleteExceptions)
            {
                ResultIssueCollector?.AddObsoleteException(objRefMsg);
            }

            UpdateServiceProgress(Progress, responseMsg);

            if (responseMsg.ServiceCallStatus != (int)ServiceCallStatus.Running)
            {
                // Final message: Finished, Failed or Cancelled

                if (QualityVerificationResult != null)
                {
                    QualityVerificationResult.VerificationMsg =
                        responseMsg.QualityVerification;

                    ResultIssueCollector?.SetVerifiedPerimeter(
                        responseMsg.VerifiedPerimeter);
                }
            }

            LogProgress(responseMsg.Progress);
        }
Example #4
0
 private static void HandleOnVerificationComplete(VerificationResponse res)
 {
     if (res.Status != 0)
     {
         VerificationFailed();
     }
 }
Example #5
0
        private async Task <HttpStatusCode> VerifyCaptcha(string token)
        {
            HttpResponseMessage verifyHTTPResponse = await this.recaptchaService.VerifyTokenASync(token);

            string verifyBody = await verifyHTTPResponse.Content.ReadAsStringAsync();

            VerificationResponse verifyResponse = JsonConvert.DeserializeObject <VerificationResponse>(verifyBody);

            double threshold  = this.recaptchaOptions.ScoreThreshold;
            string actionName = this.recaptchaOptions.ActionName;

            if (!verifyResponse.Success)
            {
                this.logger.LogWarning("Recaptcha was not successful: {0}", JsonConvert.SerializeObject(verifyResponse));
                return(HttpStatusCode.Unauthorized);
            }

            if (verifyResponse.Score < threshold || verifyResponse.Action != actionName)
            {
                this.logger.LogWarning("Recaptcha could not verify humanity: {0}", JsonConvert.SerializeObject(verifyResponse));
                return(HttpStatusCode.Forbidden);
            }

            return(HttpStatusCode.OK);
        }
Example #6
0
        private static void UpdateSubProgress([NotNull] VerificationResponse responseMsg,
                                              [NotNull] SubResponse subResponse)
        {
            VerificationProgressMsg progressMsg = responseMsg.Progress;

            if (progressMsg == null)
            {
                return;
            }

            if (subResponse.Status != ServiceCallStatus.Running &&
                subResponse.Status != ServiceCallStatus.Finished)
            {
                subResponse.CancellationMessage = progressMsg.Message;
            }

            // TODO: More stuff? Box?
            subResponse.ProgressTotal   = progressMsg.OverallProgressTotalSteps;
            subResponse.ProgressCurrent = progressMsg.OverallProgressCurrentStep;

            if (progressMsg.CurrentBox != null)
            {
                subResponse.CurrentBox = progressMsg.CurrentBox;
            }
        }
Example #7
0
        private static void SendFatalException(
            [NotNull] Exception exception,
            Action <VerificationResponse> writeAsync)
        {
            var response = new VerificationResponse();

            response.ServiceCallStatus = (int)ServiceCallStatus.Failed;

            if (!string.IsNullOrEmpty(exception.Message))
            {
                response.Progress = new VerificationProgressMsg
                {
                    Message = exception.Message
                };
            }

            try
            {
                writeAsync(response);
            }
            catch (InvalidOperationException ex)
            {
                // For example: System.InvalidOperationException: Only one write can be pending at a time
                _msg.Warn("Error sending progress to the client", ex);
            }
        }
Example #8
0
        public void CanAssignSuccess(bool value)
        {
            var model = new VerificationResponse
            {
                Success = value
            };

            Assert.Equal(value, model.Success);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ProgressEventArgs"/> class.
 /// </summary>
 /// <param name="totalCountInList">
 /// The total count in list.
 /// </param>
 /// <param name="percentageDone">
 /// The percentage done.
 /// </param>
 /// <param name="currentVerificationResponse">
 /// The current verification response.
 /// </param>
 public ProgressEventArgs(
     int totalCountInList, 
     int percentageDone, 
     VerificationResponse currentVerificationResponse)
 {
     this.TotalCountInList = totalCountInList;
     this.PercentageDone = percentageDone;
     this.CurrentVerificationResponse = currentVerificationResponse;
 }
Example #10
0
        private void FaceID_Worker()
        {
            for (int i = 0; i <= 15; i++)
            {
                Thread.Sleep(1000);
                Console.WriteLine("Tick");
                if (listener.nedded_user_id != null && listener.nedded_user_id != "0")
                {
                    break;
                }
            }

            listener.StopListen();

            if (listener.nedded_user_id != null)
            {
                try
                {
                    verificationOrder.UserId = Int32.Parse(listener.nedded_user_id);
                }
                catch (Exception)
                {
                    listener.StartListen();
                    Thread t = new Thread(new ThreadStart(this.FaceID_Worker));
                    t.Start();

                    return;
                }

                APIClient client = new APIClient();
                response = client.verificationPost(verificationOrder);
                this.Dispatcher.Invoke(new Action(() => this.AuthorizationText.Visibility = Visibility.Hidden));

                if (response.Status == "True")
                {
                    this.Dispatcher.Invoke(new Action(() => {
                        this.PersonNameText.Text       = "Приятного аппетита " + response.Name + "!";
                        this.PersonNameText.Visibility = Visibility.Visible;

                        this.OrderIdText.Text          = "Номер заказа: " + response.Id;
                        this.OrderIdText.Visibility    = Visibility.Visible;
                        this.TakeChequeText.Visibility = Visibility.Visible;
                    }));
                    PrintCheque();
                }
                else
                {
                    this.Dispatcher.Invoke(new Action(() => {
                        this.OrderIdText.Text       = response.Message;
                        this.OrderIdText.Visibility = Visibility.Visible;
                    }));
                }
            }

            Console.WriteLine("USER ID = " + listener.nedded_user_id);
        }
Example #11
0
        public void CanAssignScore()
        {
            var value = 0.5;
            var model = new VerificationResponse
            {
                Score = value
            };

            Assert.Equal(value, model.Score);
        }
Example #12
0
        private static void UpdateServiceProgress(
            IQualityVerificationProgressTracker serviceProgress,
            VerificationResponse messageProto)
        {
            // No access to COM objects here (we're on the background thread!)

            serviceProgress.ErrorCount += messageProto.Issues.Count(i => !i.Allowable);

            serviceProgress.WarningCount += messageProto.Issues.Count(i => i.Allowable);

            VerificationProgressMsg progressMsg = messageProto.Progress;

            if (progressMsg == null)
            {
                return;
            }

            serviceProgress.ProgressType = (VerificationProgressType)progressMsg.ProgressType;
            serviceProgress.ProgressStep = (VerificationProgressStep)progressMsg.ProgressStep;

            serviceProgress.ProcessingMessage =
                progressMsg.ProcessingStepMessage;

            if (progressMsg.OverallProgressTotalSteps > 0)
            {
                serviceProgress.OverallProgressTotalSteps =
                    progressMsg.OverallProgressTotalSteps;
            }

            serviceProgress.OverallProgressCurrentStep =
                progressMsg.OverallProgressCurrentStep;

            if (progressMsg.DetailedProgressTotalSteps > 0)
            {
                serviceProgress.DetailedProgressTotalSteps =
                    progressMsg.DetailedProgressTotalSteps;
            }

            serviceProgress.DetailedProgressCurrentStep =
                progressMsg.DetailedProgressCurrentStep;

            if (progressMsg.CurrentBox != null &&
                progressMsg.CurrentBox.XMax > 0 &&
                progressMsg.CurrentBox.YMax > 0)
            {
                serviceProgress.CurrentTile = new EnvelopeXY(
                    progressMsg.CurrentBox.XMin, progressMsg.CurrentBox.YMin,
                    progressMsg.CurrentBox.XMax, progressMsg.CurrentBox.YMax);
            }

            serviceProgress.StatusMessage = progressMsg.Message;

            serviceProgress.RemoteCallStatus = (ServiceCallStatus)messageProto.ServiceCallStatus;
        }
        public VerificationResponse SendAccountVerificationCode(string Email)
        {
            VerificationResponse response = new VerificationResponse();

            if (Email == null || Email == "")
            {
                response.SetStatus(Constants.ResponseCode.FAILED);
                return(response);
            }

            User user = _userRepository.Get(t => t.Email == Email).FirstOrDefault();

            if (user == null)
            {
                response.SetStatus(Constants.ResponseCode.FAILED);
                return(response);
            }

            AccountVerification accountVerification = CreateAccountVerificationCode();

            MailRequest mailRequest = new MailRequest
            {
                ToMail      = user.Email,
                ToName      = user.FullName(),
                Subject     = "B-Commerce E-Mail Onayı",
                Body        = $"Merhaba {user.FullName()}\n Email onaylama kodunuz: {accountVerification.VerificationCode}",
                ProjectCode = "123456"
            };

            HttpClient httpClient = new HttpClient();

            httpClient.BaseAddress = new Uri(Constants.NOTIFICATION_API_BASE_URI);

            Task <HttpResponseMessage> httpResponse = httpClient.PostAsJsonAsync(Constants.NOTIFICATION_API_MAIL_URI, mailRequest);

            if (!httpResponse.Result.IsSuccessStatusCode)
            {
                response.SetStatus(Constants.ResponseCode.FAILED);
                return(response);
            }

            try
            {
                user.AccountVerifications.Add(accountVerification);
                _unitOfWork.SaveChanges();
                response.SetStatus(Constants.ResponseCode.SUCCESS);
                return(response);
            }
            catch (Exception)
            {
                response.SetStatus(Constants.ResponseCode.SYSTEM_ERROR);
                return(response);
            }
        }
Example #14
0
        public async Task <DatabaseResponse> ValidateVerificationToken(string verificationToken)
        {
            try
            {
                SqlParameter[] parameters =
                {
                    new SqlParameter("@verificationToken", SqlDbType.NVarChar),
                };

                parameters[0].Value = verificationToken;

                _DataHelper = new DataAccessHelper("Orders_VerifyVerificationToken", parameters, _configuration);
                DataTable dt = new DataTable();

                var result = await _DataHelper.RunAsync(dt);

                var response = new VerificationResponse();

                if (dt.Rows.Count > 0)
                {
                    response = (from model in dt.AsEnumerable()
                                select new VerificationResponse()
                    {
                        CustomerID = model.Field <int?>("CustomerID"),
                        OrderID = model.Field <int?>("OrderID"),
                        OrderNumber = model.Field <string>("OrderNumber"),
                        Name = model.Field <string>("Name"),
                        Email = model.Field <string>("Email")
                    }).FirstOrDefault();
                }

                return(new DatabaseResponse()
                {
                    ResponseCode = result, Results = response
                });
            }

            catch (Exception ex)
            {
                Log.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical));

                throw ex;
            }
            finally
            {
                _DataHelper.Dispose();
            }
        }
Example #15
0
        private async Task <bool> VerifyAsync(
            [NotNull] QualityVerificationGrpc.QualityVerificationGrpcClient rpcClient,
            CancellationTokenSource cancellationSource)
        {
            using (var call = rpcClient.VerifyQuality(VerificationRequest))
            {
                while (await call.ResponseStream.MoveNext(cancellationSource.Token))
                {
                    VerificationResponse responseMsg = call.ResponseStream.Current;

                    HandleProgressMsg(responseMsg);
                }
            }

            return(true);
        }
        public IActionResult Get()
        {
            _logger.LogInfo("Event EndpointVerify entered.");
            VerificationResponse response = new VerificationResponse();
            string verification           = Request.Headers[VERIFICATION_HEADER];

            if (verification == null)
            {
                verification = "header " + VERIFICATION_HEADER + " was not found in the Request Headers collection";
                _logger.LogWarn($"Event EndpointVerify BadRequest will be returned. {verification}");
                return(BadRequest(verification));
            }

            response.Verification = verification;
            Debug.WriteLine("Verification: \n" + verification);
            _logger.LogInfo($"Event EndpointVerify suceeded: {response.Verification}");
            return(Ok(response));
        }
        public string VerifyEmailAddress(string email)
        {
            VerificationResponse verificationResponse = new VerificationResponse();
            GeoStoreDBEntities   db = new GeoStoreDBEntities();
            var userObj             = user.getUserByEmail(email);

            if (userObj != null)
            {
                verificationResponse.status  = 0;
                verificationResponse.message = "This email is already registered. You might have already registered with us.";
            }
            else
            {
                verificationResponse.status  = 1;
                verificationResponse.message = "";
            }
            return(JsonConvert.SerializeObject(verificationResponse));
        }
        public string VerifyUser(string userName)
        {
            VerificationResponse verificationResponse = new VerificationResponse();
            GeoStoreDBEntities   db = new GeoStoreDBEntities();
            user userObj            = user.getUserByName(userName);

            if (userObj != null)
            {
                verificationResponse.status  = 0;
                verificationResponse.message = "This user name is not available. Please choose another name.";
            }
            else
            {
                verificationResponse.status  = 1;
                verificationResponse.message = "This User name is available.";
            }
            return(JsonConvert.SerializeObject(verificationResponse));
        }
        //check if open id exists in our system.
        private VerificationResponse VerifyOpenId(string openid)
        {
            VerificationResponse verificationResponse = new VerificationResponse();
            GeoStoreDBEntities   db = new GeoStoreDBEntities();
            user userObj            = user.getUserByOpenID(openid);

            if (userObj != null)
            {
                verificationResponse.status  = 0;
                verificationResponse.message = "This openid is already registered. You might have already registered with us.";
            }
            else
            {
                verificationResponse.status  = 1;
                verificationResponse.message = "The openid is successfully authenticated.";
            }
            return(verificationResponse);
        }
Example #20
0
        public async Task <VerificationResponse> VerifyDocket(CentralRegistry centralRegistry)
        {
            var verificationResponse = new VerificationResponse(string.Empty, false);

            var client = new HttpClient();

            string endpoint = $"api/{centralRegistry.DocketId}/Verify";


            var response = await client.PostAsJsonAsync($"{centralRegistry.Url.HasToEndsWith("/")}{endpoint}", centralRegistry);

            if (response.IsSuccessStatusCode)
            {
                verificationResponse.Verified     = true;
                verificationResponse.RegistryName = await response.Content.ReadAsStringAsync();
            }

            return(verificationResponse);
        }
Example #21
0
        private static void WriteProgressAndIssues(
            VerificationProgressEventArgs e,
            ConcurrentBag <IssueMsg> issues,
            VerificationProgressMsg currentProgress,
            Action <VerificationResponse> writeAction)
        {
            VerificationResponse response = new VerificationResponse
            {
                ServiceCallStatus = (int)ServiceCallStatus.Running
            };

            if (!UpdateProgress(currentProgress, e) && issues.Count == 0)
            {
                return;
            }

            response.Progress = currentProgress;

            //List<IssueMsg> sentIssues = new List<IssueMsg>(issues.Count);

            while (issues.TryTake(out IssueMsg issue))
            {
                response.Issues.Add(issue);
            }

            _msg.DebugFormat("Sending {0} errors back to client...", issues.Count);

            try
            {
                writeAction(response);
            }
            catch (InvalidOperationException ex)
            {
                // For example: System.InvalidOperationException: Only one write can be pending at a time
                _msg.VerboseDebug("Error sending progress to the client", ex);

                // The issues would be lost, so put them back into the collection
                foreach (IssueMsg issue in response.Issues)
                {
                    issues.Add(issue);
                }
            }
        }
Example #22
0
        public VerificationResponse verificationPost(OrderItems orderItems)
        {
            String jsonOrder = JsonConvert.SerializeObject(orderItems);

            Console.WriteLine(jsonOrder);

            VerificationResponse response = new VerificationResponse();

            try
            {
                var t = Task.Run(() => this.POST(configurations.data["API"]["backend"] + "api/order", jsonOrder));
                t.Wait();
                response = JsonConvert.DeserializeObject <VerificationResponse>(t.Result);
                return(response);
            } catch (Exception)
            {
                return(response);
            }
        }
Example #23
0
        private void HandleResponseMsg([NotNull] VerificationResponse responseMsg,
                                       [NotNull] SubResponse subResponse)
        {
            foreach (IssueMsg issueMessage in responseMsg.Issues)
            {
                subResponse.Issues.Add(issueMessage);
            }

            subResponse.Status = (ServiceCallStatus)responseMsg.ServiceCallStatus;

            UpdateSubProgress(responseMsg, subResponse);

            if (responseMsg.QualityVerification != null)
            {
                subResponse.VerificationMsg = responseMsg.QualityVerification;
            }

            LogProgress(responseMsg.Progress);
        }
        public CaptchaResponse Verify(string privateKey, string secret)
        {
            var response = new CaptchaResponse();
            var client   = clientItems.FirstOrDefault(x
                                                      => x.Value.PrivateKey == privateKey).Value;

            if (client == null)
            {
                response.AddError("Validation fail #001");
            }
            else
            {
                VerificationResponse verificationResponse = null;
                try
                {
                    var secretReal = stringHelper.FromSafeBase64(secret);
                    var data       = stringHelper.Decrypt(secretReal, privateKey);
                    verificationResponse = JsonConvert.DeserializeObject <VerificationResponse>(data);

                    if (!validationItems.ContainsKey(client.Id))
                    {
                        response.AddError("Validation fail #007");
                    }

                    if (validationItems.ContainsKey(client.Id) && validationItems[client.Id].FirstOrDefault(
                            x => x.Instance == verificationResponse.Instance)?.Response == secret)
                    {
                        // success
                    }
                    else
                    {
                        response.AddError("Validation fail #101");
                    }
                }
                catch (Exception)
                {
                    response.AddError("Validation fail #404");
                }
            }

            return(response);
        }
        public VerificationResponse Verification(VerificationRequest model)
        {
            VerificationResponse resp = new VerificationResponse();
            string         _con       = connection._DB_Master;
            DataTable      dt         = new DataTable();
            SqlConnection  oConn      = new SqlConnection(_con);
            SqlTransaction oTrans;

            oConn.Open();
            oTrans = oConn.BeginTransaction();
            SqlCommand oCmd = new SqlCommand();

            oCmd.Connection  = oConn;
            oCmd.Transaction = oTrans;
            try
            {
                SqlCommand nCmd = new SqlCommand();
                oCmd.CommandText = "users_verification";
                oCmd.CommandType = CommandType.StoredProcedure;
                oCmd.Parameters.Clear();
                oCmd.Parameters.AddWithValue("@user_id", Crypto.url_decrypt(model.id));

                SqlDataReader sdr = oCmd.ExecuteReader();
                while (sdr.Read())
                {
                    resp.id = Crypto.url_encrypt(sdr["user_id"].ToString());
                }
                sdr.Close();
                oTrans.Commit();
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.Message);
            }
            finally
            {
                oConn.Close();
            }

            return(resp);
        }
Example #26
0
        public async Task <VerificationResponse> Verify(CentralRegistry centralRegistry, string endpoint = "api/v1/test")
        {
            var verificationResponse = new VerificationResponse(string.Empty, false);

            var client = new HttpClient();

            client.DefaultRequestHeaders.Add("SubscriberId", $"{centralRegistry.SubscriberId}");
            if (centralRegistry.RequiresAuthentication())
            {
                client.DefaultRequestHeaders.Add("Token", $"{centralRegistry.AuthToken}");
            }

            var response = await client.GetAsync($"{centralRegistry.Url.HasToEndsWith("/")}{endpoint}");

            if (response.IsSuccessStatusCode)
            {
                verificationResponse.Verified     = true;
                verificationResponse.RegistryName = await response.Content.ReadAsStringAsync();
            }

            return(verificationResponse);
        }
Example #27
0
        private VerificationResponse SubmitVerificationInternal(string verificationCode)
        {
            var data = new NameValueCollection
            {
                { "code", verificationCode }
            };

            var verificationResponse = new VerificationResponse();

            using (var response = _Http.Post(Constants.URL_VERIFICATION, data))
            {
                verificationResponse.HttpStatusCode = response.StatusCode;
                if (response.StatusCode == HttpStatusCode.Found || response.StatusCode == HttpStatusCode.MovedPermanently)
                {
                    verificationResponse.Success = true;
                }
                else
                {
                    verificationResponse.Success = false;
                }
            }

            return(verificationResponse);
        }
        public IHttpActionResult Post([FromBody] VerificationData postData)
        {
            VerificationResponse obj = new VerificationResponse();
            var appid = "";

            #region 1) check the appid header
            try
            {
                // get the authentication/appid header
                IEnumerable <string> headerValues = Request.Headers.GetValues("appid");
                appid = headerValues.FirstOrDefault();

                // 2) validate the format of appid
                if (!IsValidGuid(appid))
                {
                    // appid is not formatted correctly or null or empty
                    return(BadRequest("The value provided for one of the HTTP headers was not in the correct format"));
                }
            }
            catch (Exception)
            {
                // no appid header
                return(BadRequest("a required HTTP header was not supplied"));
            }
            #endregion

            #region 2) check the mobile parameter
            if (!IsDigitsOnly(postData.mobile))
            {
                return(BadRequest("An invalid value was specified for one of the query parameters in the request URI"));
            }
            #endregion

            #region 3) check the pin parameter
            if (!IsDigitsOnly(postData.pin))
            {
                return(BadRequest("An invalid value was specified for one of the query parameters in the request URI"));
            }
            else
            {
                // check the pin is 5 digits long
                if (postData.pin.Length != 5)
                {
                    return(BadRequest("An invalid value was specified for one of the query parameters in the request URI"));
                }
            }
            #endregion


            #region 4) call verification stored proc
            string dbRetVal       = "";
            string dbErrorMessage = "";
            try
            {
                using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connMobVerify"].ConnectionString))
                {
                    conn.Open();
                    using (SqlCommand cmd = new SqlCommand("app.verify", conn))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("appid", appid);
                        cmd.Parameters.AddWithValue("mobile", postData.mobile);
                        cmd.Parameters.AddWithValue("pin", postData.pin);

                        using (SqlDataReader reader = cmd.ExecuteReader())
                        {
                            if (reader.HasRows)
                            {
                                while (reader.Read())
                                {
                                    dbRetVal = reader["retVal"].ToString();
                                }
                            }
                        }
                    }
                }
            }
            catch (SqlException dbex)
            {
                // database error
                dbRetVal       = "dbError";
                dbErrorMessage = dbex.ToString();
            }
            #endregion

            string json = "";

            switch (dbRetVal)
            {
            case "success":
                obj.Message = "success";
                json        = JsonConvert.SerializeObject(obj);
                return(Ok(json));

            //break;
            case "failed":
                obj.Message = "failed";
                json        = JsonConvert.SerializeObject(obj);
                return(Ok(json));

            //break;
            case "unauthorised":
                return(BadRequest("Unauthorised"));

            //break;
            case "dbError":
                obj.Message = dbErrorMessage;
                json        = JsonConvert.SerializeObject(obj);
                return(Ok(json));

            //break;
            case "":
                obj.Message = "database returned nothing";
                json        = JsonConvert.SerializeObject(obj);
                return(Ok(json));

            //break;
            default:
                obj.Message = "unknown error";
                json        = JsonConvert.SerializeObject(obj);
                return(Ok(json));
                //break;
            }
        }
Example #29
0
        private static void PackVerification([CanBeNull] QualityVerification verification,
                                             [NotNull] VerificationResponse response)
        {
            if (verification == null)
            {
                return;
            }

            QualityVerificationMsg result = new QualityVerificationMsg();

            result.SavedVerificationId = verification.Id;
            result.SpecificationId     = verification.SpecificationId;

            CallbackUtils.DoWithNonNull(
                verification.SpecificationName, s => result.SpecificationName = s);

            CallbackUtils.DoWithNonNull(
                verification.SpecificationDescription,
                s => result.SpecificationDescription = s);

            CallbackUtils.DoWithNonNull(verification.Operator, s => result.UserName = s);

            result.StartTimeTicks = verification.StartDate.Ticks;
            result.EndTimeTicks   = verification.EndDate.Ticks;

            result.Fulfilled = verification.Fulfilled;
            result.Cancelled = verification.Cancelled;

            result.ProcessorTimeSeconds = verification.ProcessorTimeSeconds;

            CallbackUtils.DoWithNonNull(verification.ContextType, (s) => result.ContextType = s);
            CallbackUtils.DoWithNonNull(verification.ContextName, (s) => result.ContextName = s);

            result.RowsWithStopConditions = verification.RowsWithStopConditions;

            foreach (var conditionVerification in verification.ConditionVerifications)
            {
                var conditionVerificationMsg =
                    new QualityConditionVerificationMsg
                {
                    QualityConditionId =
                        Assert.NotNull(conditionVerification.QualityCondition).Id,
                    StopConditionId = conditionVerification.StopCondition?.Id ?? -1,
                    Fulfilled       = conditionVerification.Fulfilled,
                    ErrorCount      = conditionVerification.ErrorCount,
                    ExecuteTime     = conditionVerification.ExecuteTime,
                    RowExecuteTime  = conditionVerification.RowExecuteTime,
                    TileExecuteTime = conditionVerification.TileExecuteTime
                };

                result.ConditionVerifications.Add(conditionVerificationMsg);
            }

            foreach (var verificationDataset in verification.VerificationDatasets)
            {
                var verificationDatasetMsg =
                    new QualityVerificationDatasetMsg
                {
                    DatasetId = verificationDataset.Dataset.Id,
                    LoadTime  = verificationDataset.LoadTime
                };

                result.VerificationDatasets.Add(verificationDatasetMsg);
            }

            response.QualityVerification = result;
        }
        public string VerifyEmailAddress(string email)
        {
            VerificationResponse verificationResponse = new VerificationResponse();
            GeoStoreDBEntities db = new GeoStoreDBEntities();
            var userObj = user.getUserByEmail(email);

            if (userObj != null)
            {
                verificationResponse.status = 0;
                verificationResponse.message = "This email is already registered. You might have already registered with us.";
            }
            else
            {
                verificationResponse.status = 1;
                verificationResponse.message = "";
            }
            return JsonConvert.SerializeObject(verificationResponse);
        }
 public void SubscribeVerificationResult(VerificationResponse listener)
 {
     emailVerification.EmailVerificationEvent       += listener.OnEmailVerificationSucces;
     whatsaapVerification.WhatsappVerificationEvent += listener.OnWhatsaapVerificationSucces;
 }
        //check if open id exists in our system.
        private VerificationResponse VerifyOpenId(string openid)
        {
            VerificationResponse verificationResponse = new VerificationResponse();
            GeoStoreDBEntities db = new GeoStoreDBEntities();
            user userObj = user.getUserByOpenID(openid);

            if (userObj != null)
            {
                verificationResponse.status = 0;
                verificationResponse.message = "This openid is already registered. You might have already registered with us.";
            }
            else
            {
                verificationResponse.status = 1;
                verificationResponse.message = "The openid is successfully authenticated.";
            }
            return verificationResponse;
        }
Example #33
0
 public void SubcribeVerificationResult(VerificationResponse listener)
 {
     whatsappVerification.waVerificationEvent += listener.OnWaVerificationSucceed;
     emailVerification.emailVerificationEvent += listener.OnEmailVerificationSucceed;
 }
        public string VerifyUser(string userName)
        {
            VerificationResponse verificationResponse = new VerificationResponse();
            GeoStoreDBEntities db = new GeoStoreDBEntities();
            user userObj = user.getUserByName(userName);

            if (userObj != null)
            {
                verificationResponse.status = 0;
                verificationResponse.message = "This user name is not available. Please choose another name.";
            }
            else
            {
                verificationResponse.status = 1;
                verificationResponse.message = "This User name is available.";
            }
            return JsonConvert.SerializeObject(verificationResponse);
        }