예제 #1
0
        protected void Page_Load(object sender, EventArgs e)
        {
            //POST Example = verify pin
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Add("appId", "D11E5CFD-4528-4547-A13E-F9E62772142D");

                VerificationData data = new VerificationData();
                data.mobile = "07890664662";
                data.pin    = "12345";

                var json = Newtonsoft.Json.JsonConvert.SerializeObject(data);

                HttpResponseMessage response = client.PostAsJsonAsync("http://127.0.0.1/api/verify", data).Result;

                //var reply = Newtonsoft.Json.JsonConvert.DeserializeObject<VerificationResponse>(response.ToString());

                if (response.IsSuccessStatusCode)
                {
                    // we have validated this pin and mobile
                    //Label1.Text = "StatusCode:" + response.StatusCode.ToString() + "<br/>Message:" + reply.Message;
                    Label1.Text = response.ToString();
                }
                else
                {
                    // failed validation with response phrase:
                    //
                    //Label1.Text = "StatusCode:" + response.StatusCode.ToString() + "<br/>Message:" + reply.Message;
                    Label1.Text = response.ToString();
                }
            }
        }
예제 #2
0
        public ManualStepResultModel PerformManualStep(int?verificationNumber)
        {
            var result = _gameManager.PerformManualStep(
                verificationNumber != null
                    ? new VerificationManualStepResult {
                VerificationNumber = verificationNumber.Value
            }
                    : null);
            var verificationnumberResult      = result as VerificationRequiredResult;
            VerificationData verificationData = null;
            CashModel        modifiedCounters = null;

            if (verificationnumberResult != null)
            {
                verificationData = new VerificationData
                {
                    FirstNumber  = verificationnumberResult.FirstNumber,
                    SecondNumber = verificationnumberResult.SecondNumber
                };
            }

            var noVerficationRequiredResult = result as NoVerficationRequiredResult;

            if (noVerficationRequiredResult != null)
            {
                modifiedCounters = _fundsCounterModelMapper.Map(noVerficationRequiredResult.ModifiedCash);
                verificationData = null;
            }

            return(new ManualStepResultModel
            {
                VerificationData = verificationData,
                ModifiedCountersInfo = modifiedCounters
            });
        }
예제 #3
0
        public bool Verify(Deposit deposit)
        {
            // TODO: need to be able to delete?
            // generally need to understand how the verification would work here and the current code at least
            // encapsulates deposits creation and verification

            Root    depositDataRoot = _crypto.HashTreeRoot(deposit.Data);
            Bytes32 rootBytes       = new Bytes32(depositDataRoot.AsSpan());

            VerificationData.Insert(Bytes32.Wrap(deposit.Data.Root.Bytes));
            bool isValid = VerificationData.VerifyProof(rootBytes, deposit.Proof, VerificationData.Count - 1);

            return(isValid);
        }
예제 #4
0
        static LocalPurchaseVerification()
        {
            VerificationData apple, google;

            if (Core.isTNT)
            {
                apple = new VerificationData()
                {
                    data  = Convert.FromBase64String("24qcqvSq5qIMK0hJIyFw7wV+5+/t2tPW3tHc2p/Q0Z/L19bMn9zazYkm85LHCFIzJGNMyCRNyW3Ij/B+oDo8OqQmgviITRYk/zGTaw4vrWfR25/c0NHb1svW0NHMn9DZn8rM2uYYurbDqP/prqHLbAg0nIT4HGrQPb6/ubaVOfc5SNzbur6PPk2PlbmVOfc5SLK+vrq6v4/djrSPtrm86rfhjz2+rrm86qKfuz2+t489vruPuY+wubzqoqy+vkC7uo+8vr5Aj6KQjz58ubeUub66uri9vY8+CaU+DAFLzCRRbduwdMbwi2cdgUbHQNR3MMw+33mk5LaQLQ1H+/dP34chqkqPrrm86ru1rLX+z8/T2p/20dyRjp/8/o89vp2Psrm2lTn3OUiyvr6+zd7cy9bc2p/My97L2tLa0cvMkY/T2p/20dyRjpmPm7m86ru0rKL+z8/T2p/82s3L1tnW3N7L1tDRn/7Kxp/ezMzK0trMn97c3NrPy97R3Nr2Z8kgjKvaHsgrdpK9vL6/vhw9voqNjouPjInlqLKMio+Nj4aNjouPt5S5vrq6uL2+qaHXy8vPzIWQkMjFjz2+yY+xubzqorC+vkC7u7y9vrq/vD2+sL+PPb61vT2+vr9bLha2jz27BI89vBwfvL2+vb2+vY+yubaMieWP3Y60j7a5vOq7uay96uyOrBQczi347Op+EJD+DEdEXM9yWRzz3dPan8zL3tHb3s3bn8vazdLMn96Tn9zazcvW2dbc3svan8/Q09bcxnamzUrisWrA4CRNmrwF6jDy4rJOoC5kofjvVLpS4cY7klSJHejz6lPW2dbc3svW0NGf/srL19DN1svGjpmPm7m86ru0rKL+z8/T2p/82s3Lu7msversjqyPrrm86ru1rLX+z880pjZhRvTTSrgUnY+9V6eBR++2bAqFEkuwsb8ttA6eqZHLaoOyZN2pn9DZn8vX2p/L19rRn97Pz9PW3N6pj6u5vOq7vKyy/s/P09qf7dDQy7K5tpU59zlIsr6+urq/vD2+vr/jgpnYnzWM1UiyPXBhVByQRuzV5NsqIcWzG/g05GupiIx0e7DycavWbptdVG4Iz2Cw+l6YdU7Sx1JYCqiowP4XJ0Zuddkjm9SubxwEW6SVfKDL19DN1svGjqmPq7m86ru8rLL+z7m86qKxu6m7q5Rv1vgrybZBS9Qy2DC3C59IdBOTn9DPCYC+jzMI/HCwIoJMlPaXpXdBcQoGsWbho2l0gsjIkd7Pz9PakdzQ0pDez8/T2tzeuFPChjw07J9sh3sOACXwtdRAlEOR/xlI+PLAt+GPoLm86qKcu6ePqcvW2dbc3svan93Gn97Rxp/P3s3LZonAfjjqZhgmBo39RGdqziHBHu36waDz1O8p/jZ7y920rzz+OIw1Pj+rlG/W+CvJtkFL1DKR/xlI+PLADo/nU+W7jTPXDDCiYdrMQNjh2gMIpAIs/ZutlXiwognyI+Hcd/Q/qH/cjMhIhbiT6VRlsJ6xZQXMpvAKn97R25/c2s3L1tnW3N7L1tDRn8/P09qf7dDQy5/8/o+hqLKPiY+LjRdjwZ2KdZpqZrBp1Gsdm5yuSB4T7xU1amVbQ2+2uIgPysqe"),
                    order = new int[] { 20, 38, 48, 49, 43, 52, 34, 38, 33, 29, 37, 50, 55, 29, 29, 46, 49, 43, 40, 27, 38, 35, 28, 29, 38, 33, 38, 42, 44, 42, 46, 50, 37, 48, 49, 42, 41, 55, 47, 56, 40, 53, 43, 52, 46, 52, 46, 53, 51, 50, 56, 58, 58, 55, 55, 59, 57, 58, 58, 59, 60 },
                    key   = 191,
                };

                google = new VerificationData()
                {
                    // Google Play public key: MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApYVJg8zM05pRbUlVojlxrTYtuVEhnBR4Yazxcs6vkyDNC98JpP8gIZoPtvXAD1IpaqTBz2xFq29hee/Mqi2H8cuF9IgmVMLHtwxXa0sg7CXw3oHvW+aXY5+yv4BiC5DdoLbNsqj8OiFhMF+XNICbVBXP64I0v18zbYOJyvM/0pNV0iETuTOO8N8aMXRlZ/EU/YCcrXS/O3Rj8ax9z/lR0npMN+CjZVRJw3F4gT98DMPwfM5R//tZIbSEB55TDzNR4xiZEFxafwuGntRlVWVJqviLACRR3boUuR65jMIZEe++59Z8BjhnM6IOJsACeweN4I2qlMHSwCj2rdpXIxnhUQIDAQAB
                    data  = Convert.FromBase64String("3Fbk7RSq6ZlWZelbxGpuzLQhEZIPxPjcwDes5DijuCzEtAmB7fQ5ZBeUmpWlF5SflxeUlJUwENwWWVlGOOEqruH2ZDnoWmzER+/ZonU28ME/bR6VscRIL4EsiywZV4yEeityQ6UXlLelmJOcvxPdE2KYlJSUkJWW9gonKhX3ngVINSNYJz1pr7T0pcods8FXUiKZwv7etXmwZUsUes5zAgbAR7SGLKYbZUqPpOHw8mSBaBUJC8aapsR2jQyFyc/qnhMLQfDA8NznWzoGtVieSpwxarW0D5ojYFWaxwKhFQ7BgFp+F6Eqyqb4FhxfZqpH6ZOt8qY3m7NVl+6SGHUYPwFUR1W8/zFUWvnQPvr07HpZP7gSZF4QYb1jOE/Ctox0xJeWlJWU"),
                    order = new int[] { 10, 2, 2, 9, 12, 10, 6, 10, 8, 11, 11, 11, 13, 13, 14 },
                    key   = 149,
                };
            }
            else
            {
                apple = new VerificationData()
                {
                    data  = Convert.FromBase64String("DgXhlz/cEMBPjayoUF+U1lWP8krhqxma7auVnZjOhpSammSfn5iZmiqrw3fBn6kX8ygUhkX+6GT8xf4nk7Cdmp6enJmajYXz7+/r6KG0tOy/eXBKLOtElN56vFFq9uN2fC6MjIQeGB6AAqbcrGkyANsVt08qC4lD7Oy1+uvr9/61+PT2tPrr6/f++Pquqaqvq6itwYyWqK6rqauiqaqvqxCCEkVi0PdunDC5q5lzg6Vjy5JIM0flua5Rvk5ClE3wTzm/uIpsOjf/rriO0I7ChigPbG0HBVTLIVrDy+K7+ujo7vb+6Lv6+Pj+6+/69fj+0kPtBKiP/jrsD1K2mZiam5o4GZqorcGr+aqQq5KdmM6fnYiZzsiqiPwUky+7bFA3t7v06y2kmqsXLNhU7/P06fLv4qqNq4+dmM6fmIiW2usU6Br7XYDAkrQJKWPf02v7owWObre7+P7p7/L98vj67/676/T38vji6/f+u8n09O+72NqrhYyWq62rr6kZmpudkrEd0x1s+P+emqsaaauxnZx35qIYEMi7SKNfKiQB1JHwZLBnMDjqCdzIzlo0tNooY2B461Z9ONe7+vX/u/j+6e/y/fL4+u/y9PW7652rlJ2YzoaImppkn56rmJqaZKuGsR3THWyWmpqenpur+aqQq5KdmM7CPJ6S54zbzYqF70gsELig3DhO9JadkrEd0x1slpqanp6bmBmampvH9/670vX4taq9q7+dmM6fkIiG2uuTxasZmoqdmM6Gu58ZmpOrGZqfq0Kt5FoczkI8AiKp2WBDTuoF5TrJu9jaqxmauauWnZKxHdMdbJaamprk2jMDYkpR/Qe/8IpLOCB/gLFYhOn6+O/y+P676O/67/72/vXv6LWrq4qdmM6fkYiR2uvr9/670vX4tarr9/672P7p7/L98vj67/L09bva7p2YzoaVn42fj7BL8twP7ZJlb/AW8v3y+Prv8vT1u9ru7/P06fLv4qqfnYiZzsiqiKuKnZjOn5GIkdrr6/X/u/j09f/y7/L09ei79P277uj+npuYGZqUm6sZmpGZGZqam38KMpIsgCYI2b+JsVyUhi3WB8X4U9AbjC6hNm+UlZsJkCq6jbXvTqeWQPmNyf738vr1+P679PW77/Py6Lv4/unv8v3y+Prv/rv54rv69eK76/rp760C17bjLHYXAEdo7ABp7Unsq9Ratds9bNzW5JPFq4SdmM6GuJ+Dq42ECkCF3MtwnnbF4h+2cK05zNfOd1KC6W7GlU7kxABpvpghzhTWxpZq3uWE1/DLDdoSX+/5kIsY2hyoERobj7BL8twP7ZJlb/AWtds9bNzW5L2rv52Yzp+QiIba6+v3/rvY/unv+ff+u+jv+vX/+un/u+/+6fbou/q79P277/P+u+/z/vW7+uvr9/L4+pQGpmiw0rOBU2VVLiKVQsWHTVCmtKsaWJ2TsJ2anp6cmZmrGi2BGiimvfy7EajxbJYZVEVwOLRiyPHA/6sZnyCrGZg4O5iZmpmZmpmrlp2SW/io7GyhnLfNcEGUupVBIeiC1C4lb+gAdUn/lFDi1K9DOaVi42TwU42rj52Yzp+YiJba6+v3/rvJ9PTvyzERTkF/Z0uSnKwr7u66"),
                    order = new int[] { 18, 28, 26, 35, 53, 49, 36, 7, 16, 54, 20, 40, 27, 16, 21, 49, 55, 44, 36, 34, 51, 24, 45, 29, 28, 52, 47, 35, 33, 58, 55, 44, 46, 54, 53, 55, 40, 47, 43, 54, 59, 58, 43, 54, 48, 48, 49, 53, 52, 49, 51, 54, 58, 58, 58, 56, 59, 57, 58, 59, 60 },
                    key   = 155,
                };

                google = new VerificationData()
                {
                    // Google Play public key: MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0WWoOomW7wNujY1FWgcOtv1FaSLwN9xk/6t/8hFqX3LJNqIiRirET2ANLDj/NWMiJ68e+KJL6rqqJ0LXZAFvmluNiZYJZg3bpQaVafXrcUmYwB2PwiE8sLqv5t88UPQddYZ/Hmuwqto038JJsHZUxw3hGBd5k93DfOiZbZbbPv/XVpBB0pKVni8yb1Sdq1jmoAJz5sd9owOXYrWSyN9vo+OUuGGQ9OyAABHT1k3FFmm72h4g+lK2LvO+QLKEreQaPvxhI9RguXpdruMSqswb4Ny1OoH1sPBToxNLmu7rFhQZIUKjljPR4K+ue6My+qnJ9JoWYEvWkLK66pRsWVtoHwIDAQAB
                    data  = Convert.FromBase64String("xnT31Mb78P/ccL5wAfv39/fz9vUQMYtV9WGUQ2Q+KZlVFWJOl2YCGhYqQ8x3A0YGpVXlvWwYHeDi79e0RHJbEuzICpfVIpZPjKtYFeRcOu31mHt7s6zx+EALs5/UBsEqkgldiVVgxScWWViNVcQMXz8CbOCWvSBmdvbnJSC7M+CfTSzo1gykQNgFSLZg/5D7LVPwY58DHYe/bjbreTTXygkhoGa3JGRjaNnEmaJrXa4QVvSF1NFZ6A5UvRxMXNG0IZL3mWyte3909/n2xnT3/PR09/f2J5NezH9gGUZMWRApyqYC64NwieidRlwswik0v0aAojH7F+7hj2UrNYoeb5tgLcgE55yphD/AVNSw3DK5lvvazgnDlURMHGKar62e6fT19/b3"),
                    order = new int[] { 0, 9, 12, 11, 12, 13, 10, 13, 8, 12, 12, 12, 13, 13, 14 },
                    key   = 246,
                };
            }

            validator = new CrossPlatformValidator(google.DeObfuscate(), apple.DeObfuscate(), Application.identifier);
        }
예제 #5
0
		public void CreateNewTest ()
		{
			verif_data = new VerificationData (FileName);
			verif_data.IsNewSet = true;
		}
예제 #6
0
			public static VerificationData FromFile (string name, XmlReader r)
			{
				VerificationData tc = new VerificationData (name);
				ArrayList methods = new ArrayList ();
				r.Read ();
				while (r.ReadToNextSibling ("type")) {
					string type_name = r ["name"];
					r.Read ();
					while (r.ReadToNextSibling ("method")) {
						string m_name = r ["name"];
						int method_attrs = int.Parse (r["attrs"]);

						r.ReadToDescendant ("size");
						int il_size = r.ReadElementContentAsInt ();
						methods.Add (new MethodData (type_name, m_name, method_attrs, il_size));
						r.Read ();
					}
					r.Read ();
				}

				tc.methods = methods;
				return tc;
			}
예제 #7
0
 public override void verify(VerificationData data)
 {
     throw new Exception("Applies only to inorder verification");
 }
예제 #8
0
        OperationResult ChangeImpl(ChangeInput input)
        {
            if (input == null) throw new ArgumentNullException("input");

             var errors = new ErrorBuilder();

             if (errors.NotValid(input))
            return errors;

             UserWrapper user = this.repo.FindUserByName(this.CurrentUserName);

             string currentEmail = user.Email;
             string newEmail = input.NewEmail;

             if (errors.Not(currentEmail.HasValue(), AccountResources.Validation_MissingEmail))
            return errors;

             if (errors.Not(this.passServ.PasswordEquals(input.CurrentPassword, user.Password), AccountResources.Validation_CurrentPasswordIncorrect, () => input.CurrentPassword)
            | errors.Not(!EmailEquals(currentEmail, newEmail), AccountResources.Validation_NewEmailSameAsCurrent, () => input.NewEmail))
            return errors;

             if (errors.Not(this.repo.FindUserByEmail(newEmail) == null, AccountResources.Validation_EmailAlreadyExists, () => input.NewEmail))
            return errors;

             if (!this.Configuration.EnableEmailVerification) {

            user.Email = newEmail;

            this.repo.UpdateUser(user);

            return HttpStatusCode.OK;
             }

             user.EmailChangeTicketExpiration = this.Configuration.GetNow().Add(this.Configuration.EmailChangeTicketExpiration);

             this.repo.UpdateUser(user);

             var notifyModel = new NotificationMessageViewModel {
            SiteName = GetSiteName(),
            NewEmail = newEmail,
            OldEmail = currentEmail,
            HelpResource = this.Configuration.HelpResource
             };

             if (!EmailEquals(currentEmail, user.Username))
            notifyModel.Username = user.Username;

             var notifyMessage = new MailMessage {
            To = { user.Email },
            Subject = AccountResources.Model_EmailChangeNotificationMessageSubject,
            Body = RenderEmailView(Views.Email.Change._NotificationMessage, notifyModel)
             };

             string verificationTicket = new VerificationData(user.Id, newEmail).GetVerificationTicket();
             string verificationUrl = AbsoluteUrl(this.Url.Action(Verify, verificationTicket));

             var verifyModel = new VerificationMessageViewModel {
            SiteName = notifyModel.SiteName,
            Url = verificationUrl
             };

             var verifyMessage = new MailMessage {
            To = { newEmail },
            Subject = AccountResources.Model_EmailChangeVerificationMessageSubject,
            Body = RenderEmailView(Views.Email.Change._VerificationMessage, verifyModel)
             };

             SendEmail(notifyMessage);
             SendEmail(verifyMessage);

             return new OperationResult(HttpStatusCode.Accepted, new ChangeResult(newEmail));
        }
예제 #9
0
        OperationResult<ResetResult> ResetImpl(ResetInput input)
        {
            if (input == null) throw new ArgumentNullException("input");

             var errors = new ErrorBuilder();

             if (errors.NotValid(input))
            return errors;

             UserWrapper user = this.repo.FindUserByEmail(input.Email);

             MailMessage message;
             string destinationEmail;

             bool canResetPassword = user != null
            && !user.Disabled;

             if (canResetPassword) {

            user.PasswordResetTicketExpiration = this.Configuration.GetNow()
               .Add(this.Configuration.PasswordResetTicketExpiration);

            this.repo.UpdateUser(user);

            string verificationTicket = new VerificationData(user.Id, null).GetVerificationTicket();
            string verificationUrl = AbsoluteUrl(this.Url.Action(Finish, verificationTicket));

            var mailModel = new VerificationMessageViewModel {
               SiteName = GetSiteName(),
               Url = verificationUrl
            };

            if (!EmailEquals(user.Email, user.Username))
               mailModel.Username = user.Username;

            destinationEmail = user.Email;

            message = new MailMessage {
               To = { destinationEmail },
               Subject = AccountResources.Model_PasswordResetVerificationMessageSubject,
               Body = RenderEmailView(Views.Password.Reset._VerificationMessage, mailModel)
            };

             } else {

            destinationEmail = input.Email;

            var mailModel = new ErrorMessageViewModel {
               SiteName = GetSiteName(),
               ErrorReason = (user == null) ?
                  ErrorReason.AccountNotFound
                  : ErrorReason.AccountDisabled
            };

            message = new MailMessage {
               To = { destinationEmail },
               Subject = AccountResources.Model_PasswordResetVerificationMessageSubject,
               Body = RenderEmailView(Views.Password.Reset._ErrorMessage, mailModel)
            };
             }

             SendEmail(message);

             return new OperationResult<ResetResult>(HttpStatusCode.Accepted, new ResetResult(destinationEmail));
        }
예제 #10
0
        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;
            }
        }
예제 #11
0
        public async Task <PmErrorCode> VerifyUsersPm(Server server, List <UserData> users)
        {
            PmErrorCode     pmErrorCode     = PmErrorCode.Unknown;
            List <UserData> alreadyVerified = new List <UserData>();
            List <UserData> nulls           = new List <UserData>();

            foreach (UserData userData in users)
            {
                IGuildUser user = server.Guild.GetUser(userData.UserId);
                if (user == null)
                {
                    user = await this.Client.DiscordClient.Rest.GetGuildUserAsync(server.Id, userData.UserId);
                }

                if (user == null)
                {
                    nulls.Add(userData);
                    continue;
                }

                if (userData.Verified)
                {
                    alreadyVerified.Add(userData);
                    continue;
                }

                string verifyPm = "";
                string value    = "";
                if (server.Config.CaptchaVerificationEnabled)
                {
                    verifyPm = this.CaptchaPms[Utils.Random.Next(0, this.CaptchaPms.Length)];
                    value    = "captcha";
                }
                else
                {
                    verifyPm = string.Format(PmCodeInfoString, server.Config.CommandPrefix);
                    int           source      = Math.Abs((userData.UserId.ToString() + server.Id).GetHashCode());
                    int           chunkNum    = (int)Math.Ceiling(Math.Ceiling(Math.Log(source)) / 2);
                    StringBuilder hashBuilder = new StringBuilder(chunkNum);
                    for (int i = 0; i < chunkNum; i++)
                    {
                        char c = (char)((source % 100) / 4 + 97);
                        hashBuilder.Append(c);
                        source = source / 100;
                    }

                    string hash = hashBuilder.ToString();
                    hash = hash.Length > 5 ? hash.Substring(0, 5) : hash;

                    string[] lines        = server.Config.CodeVerifyMessage.Split('\n');
                    string[] words        = null;
                    bool     found        = false;
                    bool     theOtherHalf = false;
                    try
                    {
                        for (int i = Utils.Random.Next(lines.Length / 2, lines.Length); !theOtherHalf || i >= lines.Length / 2; i--)
                        {
                            if (i <= lines.Length / 2)
                            {
                                if (theOtherHalf)
                                {
                                    break;
                                }
                                theOtherHalf = true;
                                i            = lines.Length - 1;
                            }

                            if ((words = lines[i].Split(' ')).Length > 10)
                            {
                                int space = Math.Max(1, Utils.Random.Next(words.Length / 4, words.Length - 1));
                                lines[i] = lines[i].Insert(lines[i].IndexOf(words[space], StringComparison.Ordinal) - 1, $" the secret is: {hash} ");

                                hashBuilder = new StringBuilder();
                                hashBuilder.AppendLine(verifyPm).AppendLine("");
                                for (int j = 0; j < lines.Length; j++)
                                {
                                    hashBuilder.AppendLine(lines[j]);
                                }
                                verifyPm = hashBuilder.ToString();
                                value    = hash;
                                found    = true;
                                break;
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        // This is ignored because user. Send them a message to fix it.
                        found = false;

                        await this.HandleException(e, "VerifyUserPm.hash", server.Id);
                    }

                    if (!found)
                    {
                        verifyPm = PmHashErrorString;
                    }
                }

                if (!string.IsNullOrEmpty(value))
                {
                    ServerContext    dbContext = ServerContext.Create(this.Client.DbConnectionString);
                    VerificationData data      = dbContext.Verification.AsQueryable().FirstOrDefault(u => u.ServerId == server.Id && u.UserId == userData.UserId);
                    if (data == null)
                    {
                        data = new VerificationData()
                        {
                            ServerId = userData.ServerId,
                            UserId   = userData.UserId,
                            Value    = value
                        };
                        dbContext.Verification.Add(data);
                    }

                    data.Value = value;
                    dbContext.SaveChanges();
                }

                string message = string.Format(PmString, user.Username, server.Guild.Name, verifyPm);

                if (server.Config.VerifyKarma > 0)
                {
                    message += string.Format(PmKarmaString, server.Config.VerifyKarma,
                                             server.Config.CommandPrefix, server.Config.KarmaCurrency);
                }

                pmErrorCode = await this.Client.SendPmSafe(user, message);
            }

            if (alreadyVerified.Any())
            {
                await VerifyUsers(server, alreadyVerified, false);

                pmErrorCode = PmErrorCode.Undefined;
            }

            if (nulls.Count == users.Count)
            {
                pmErrorCode = PmErrorCode.UserNull;
            }

            return(pmErrorCode);
        }
예제 #12
0
 public async Task UpdateVerificationDataAsync(VerificationData verificationData)
 {
     _context.Entry(verificationData).State = EntityState.Modified;
     await _context.SaveChangesAsync();
 }
예제 #13
0
 public async Task AddVerificationDataAsync(VerificationData verificationData)
 {
     _context.VerificationData.Add(verificationData);
     await _context.SaveChangesAsync();
 }