Exemplo n.º 1
0
 public void CanCheckPassword()
 {
     Password p = new Password("1", "alibalibi");
       Assert.IsTrue(p.Matches("1", "alibalibi"));
       Assert.IsFalse(p.Matches("1", "alibalibi1"));
       Assert.IsFalse(p.Matches("1", " alibalibi"));
 }
        /// Create a new web application profile.
        /// </summary>
        /// <param name="Options">Command line parameters</param>
        public override void Password(Password Options) {
            SetReporting(Options.Report, Options.Verbose);
            GetProfile(Options.Portal, Options.UDF);
            GetMeshClient();

            var DeviceProfile = GetDevice(SignedPersonalProfile);
            Utils.Assert(DeviceProfile, "Could not locate a device profile on this device");

            var PersonalProfile = SignedPersonalProfile.Signed;

            var PasswordProfile = new PasswordProfile(true);

            var ApplicationProfileEntry = PersonalProfile.Add(PasswordProfile);
            ApplicationProfileEntry.AddDevice(DeviceProfile);

            PasswordProfile.Link(PersonalProfile, ApplicationProfileEntry);

            var SignedPasswordProfile = PasswordProfile.Signed;

            Machine.Add(SignedPasswordProfile);
            RegistrationPersonal.Update();

            MeshClient.Publish(SignedPasswordProfile);
            MeshClient.Publish(RegistrationPersonal.Profile);

            }
Exemplo n.º 3
0
		public static void Main()
		{
			LastLog ll = new LastLog();

			Password pw	= new Password();

			LastLogEntry llent;
			Console.WriteLine("Username         Port     From             Latest");
			while((llent = ll.GetLlEnt()) != null )
			{
				PasswordEntry pwent;
			
				if ((pwent = pw.GetPWUid((int)llent.Uid)) != null)
				{
					String dt;
					if ( llent.ll_time != 0 )
					{
						dt = llent.Time.ToString("F");
					}
					else
					{
						dt = "**Never logged in**";
					}
					Console.WriteLine("{0,-17}{1,-9}{2,-17}{3}", pwent.Name, llent.Line, llent.Host, dt);
				}
			}

		}
Exemplo n.º 4
0
 public void ErrorChecks()
 {
     Password p = new Password("1", "alibalibi");
       AssertThrows<ArgumentNullException>(() => new Password(null, null));
       AssertThrows<ArgumentNullException>(() => p.Matches(null, "11"));
       AssertThrows<ArgumentNullException>(() => p.Matches("1", null));
 }
Exemplo n.º 5
0
 public static void Login_Start(User user, Password password)
 {
     if (password == Password.Correct)
         activeLoginRequests = activeLoginRequests.Add(user, LoginStatus.Success);
     else
         activeLoginRequests = activeLoginRequests.Add(user, LoginStatus.Failure);
 }
Exemplo n.º 6
0
        static void Main()
        {
            Directory.CreateDirectory("_test");

            using (var stream = new FileStream(@"_test\test.7z", FileMode.Create, FileAccess.ReadWrite, FileShare.Delete))
            using (var encryption = new AESEncryptionProvider("test"))
            using (var encoder = new ArchiveWriter.Lzma2Encoder(null))
            {
                var writer = new ArchiveWriter(stream);
                writer.DefaultEncryptionProvider = encryption;
                writer.ConnectEncoder(encoder);
                string path = Path.GetDirectoryName(typeof(Program).Assembly.Location);
                var directory = new DirectoryInfo(path);
                foreach (string filename in Directory.EnumerateFiles(path))
                    writer.WriteFile(directory, new FileInfo(filename));
                writer.WriteFinalHeader();
            }

            {
                var pass = new Password("test");
                var db = new master._7zip.Legacy.CArchiveDatabaseEx();
                var x = new master._7zip.Legacy.ArchiveReader();
                x.Open(new FileStream(@"_test\test.7z", FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete));
                x.ReadDatabase(db, pass);
                db.Fill();
                x.Extract(db, null, pass);
            }
        }
Exemplo n.º 7
0
        static void Main(string[] args)
        {
            Password af = new Password();
            Console.WriteLine(af.randonPassword());

            // Suspend the console.
            Console.ReadKey();
        }
Exemplo n.º 8
0
 public static bool Execute(IWin32Window owner, Configuration configuration, Password.Classes.Password password)
 {
     using (var form = new EditPasswordForm())
     {
         form.Init(configuration, password);
         return form.ShowDialog(owner) == DialogResult.OK;
     }
 }
Exemplo n.º 9
0
        static void Main(string[] args)
        {
            var password = new Password();

            var pass = "******";

            var length = password.solution(pass);
        }
Exemplo n.º 10
0
    public static void Main(string [] args)
    {
        string message;
        System.Console.WriteLine("Your password has expired and you need to enter a new one");

        Password pass = new Password();
        message = pass.updatePassword();
        System.Console.WriteLine(message);
    }
Exemplo n.º 11
0
        public void CanCompare()
        {
            Password p1a = new Password("1", "alibalibi");
              Password p1b = new Password("1", "alibalibi");
              Password p2 = new Password("1", "qwerty");

              Assert.AreEqual(p1a, p1b);
              Assert.AreNotEqual(p1a, p2);
        }
        public void PasswordIsHashed()
        {
            const string password = "******";
            var sut = new Password(password);

            string hashedPassword = sut.Hash();

            Assert.IsNotNull(hashedPassword);
        }
 public void HashLengthShouldBeConst()
 {
     Password passwordSample = new Password("привет");
     
     for (int i = 1; i < 10000; i++)
     {
         Password checkedPassword = new Password(GetRandomString(i));
         Assert.AreEqual(passwordSample.Hash.Length, checkedPassword.Hash.Length);
     }
 }
Exemplo n.º 14
0
        public User(string login, UInt64 passwordHash, Int32 ID)
        {
            pLogin = login;
            pPassword = new Password(passwordHash);
            pID = ID;

            pStaticAddressess = new List<UnifiedAddress>();
            pDynamicAddressess = new List<UnifiedAddress>();
            pCurrentAddress = null;
        }
        public void does_not_restore_value_for_password_field()
        {
            stateDictionary.Add("Password", new ModelState() { Value = new ValueProviderResult("foo", "foo", CultureInfo.CurrentCulture) });

            var target = new ValidationBehavior(() => stateDictionary);
            expression = x => x.Password;
            var passwordField = new Password(expression.GetNameFor(), expression.GetMemberExpression(), new List<IBehaviorMarker> { target });
            var element = passwordField.ToString().ShouldHaveHtmlNode("Password");
            element.ShouldHaveAttribute(HtmlAttribute.Value).WithValue("");
        }
        public void when_creating_a_new_password()
        {
            context["from_the_string 'Pass'"] =
                () =>
                {
                    var password = TestData.Password.CreateValidPassword();
                    before = () => { password = new Password("Pass"); };

                    it["HashedPassword is not null"] = () => password.HashedPassword.Should().NotBeNull();
                    it["HashedPassword is not an empty array"] = () => password.HashedPassword.Should().NotBeEmpty();
                    it["Salt is not null"] = () => password.Salt.Should().NotBeNull();
                    it["Salt is not empty"] = () => password.Salt.Should().NotBeEmpty();
                    it["IsCorrectPassword('Pass') ==  true"] = () => password.IsCorrectPassword("Pass").Should().BeTrue();
                    it["IsCorrectPassword('pass') !=  true"] = () => password.IsCorrectPassword("pass").Should().BeFalse();
                    it["IsCorrectPassword('Pass ') !=  true"] = () => password.IsCorrectPassword("Pass ").Should().BeFalse();
                    it["IsCorrectPassword(' Pass') !=  true"] = () => password.IsCorrectPassword(" Pass").Should().BeFalse();
                    context["when comparing to another password created from the string 'otherPassword'"] =
                        () =>
                        {
                            var otherPassword = new Password("AnotherPassword1!");
                            before = () => otherPassword = new Password("otherPassword");
                            it["the Salt members are different"] = () => password.Salt.Should().NotEqual(otherPassword.Salt);
                            it["the HashedPassword members are different"] = () => password.HashedPassword.Should().NotEqual(otherPassword.HashedPassword);
                        };
                };

            context["allThesePasswordsAreInvalid with the mentioned failures"] =
                () =>
                {
                    it["[[null]]"] = () => Assert.Throws<PasswordDoesNotMatchPolicyException>(() => new Password(null))
                        .Failures.Should().Contain(Password.Policy.Failures.Null);
                    it["'' too short"] = () => Assert.Throws<PasswordDoesNotMatchPolicyException>(() => new Password(""))
                        .Failures.Should().Contain(Password.Policy.Failures.ShorterThanFourCharacters);
                    it["' ' whitespace and too short"] = () => Assert.Throws<PasswordDoesNotMatchPolicyException>(() => new Password(" "))
                        .Failures.Should()
                        .Contain(Password.Policy.Failures.ShorterThanFourCharacters)
                        .And
                        .Contain(Password.Policy.Failures.BorderedByWhitespace);
                    it["'Urdu ' whitespace"] = () => Assert.Throws<PasswordDoesNotMatchPolicyException>(() => new Password("Urdu "))
                        .Failures.Should()
                        .Contain(Password.Policy.Failures.BorderedByWhitespace);
                    it["' Urdu' whitespace"] = () => Assert.Throws<PasswordDoesNotMatchPolicyException>(() => new Password(" Urdu"))
                        .Failures.Should()
                        .Contain(Password.Policy.Failures.BorderedByWhitespace);
                    it["'urdu' lowercase"] = () => Assert.Throws<PasswordDoesNotMatchPolicyException>(() => new Password("urdu"))
                        .Failures.Should()
                        .Contain(Password.Policy.Failures.MissingUppercaseCharacter);
                    it["'URDU' uppercase"] = () => Assert.Throws<PasswordDoesNotMatchPolicyException>(() => new Password("URDU"))
                        .Failures.Should()
                        .Contain(Password.Policy.Failures.MissingLowerCaseCharacter);
                };


            it["from the string 'Urdu' no exception is thrown"] = () => new Password("Urdu");
        }
Exemplo n.º 17
0
        public Edit()
        {
            InitializeComponent();
            using (AchievmentsEntities ach=new AchievmentsEntities())
            {

                user = ach.Passwords.Find(App.curPnID);
                TBLog.Text = user.Name.Clone().ToString();
               
            }
        }
        public void PasswordIsMatching()
        {
            const string password = "******";
            var expectedPassword = new Password(password);
            string expectedHash = expectedPassword.Hash();

            var sut = new Password(password);
            PasswordMatch match = sut.MatchTo(expectedHash);

            Assert.AreEqual(PasswordMatch.Success, match);
        }
        public void PasswordIsMatchingButRehashNeeded()
        {
            const string password = "******";
            var expectedPassword = new Password(new AdaptivePasswordHasher(2), password);
            string expectedHash = expectedPassword.Hash();

            var sut = new Password(password);
            PasswordMatch match = sut.MatchTo(expectedHash);

            Assert.AreEqual(PasswordMatch.SuccessRehashNeeded, match);
        }
        public void PasswordIsNotMatching()
        {
            const string password = "******";
            var expectedPassword = new Password(password);
            string expectedHash = expectedPassword.Hash();

            var sut = new Password("AnotherPassword");
            PasswordMatch match = sut.MatchTo(expectedHash);

            Assert.AreEqual(PasswordMatch.Failed, match);
        }
Exemplo n.º 21
0
        // PUT api/awbuildversion/5
        public void Put(Password value)
        {
            var GetActionType = Request.Headers.Where(x => x.Key.Equals("ActionType")).FirstOrDefault();

            if (GetActionType.Key != null)
            {
                if (GetActionType.Value.ToList()[0].Equals("DELETE"))
                    adventureWorks_BC.PasswordDelete(value);
                if (GetActionType.Value.ToList()[0].Equals("UPDATE"))
                    adventureWorks_BC.PasswordUpdate(value);
            }
        }
Exemplo n.º 22
0
        public User(String login, string password, Int32 ID)
        {
            Random random = new Random();

            pLogin = login ;
            pPassword = new Password(password);
            pID = ID;

            pStaticAddressess = new List<UnifiedAddress>();
            pDynamicAddressess = new List<UnifiedAddress>();
            pCurrentAddress = null;
        }
Exemplo n.º 23
0
        public void CheckPassword_WrongPassword_Test()
        {
            var userId = "user1";
            var password = "******";
            var passwordHash = String.Concat(password, HardcodedSalt).GetHashCode().ToString();
            var passwordFromRepo = new Password() { UserId = userId, ExpiryTime = DateTime.UtcNow.AddSeconds(30), PasswordHash = passwordHash, PasswordSalt = HardcodedSalt };

            var passwordRepository = new Mock<IRepository<Password>>();
            passwordRepository.Setup(u => u.Load(userId)).Returns(passwordFromRepo);

            var passwordGenerator = new PasswordManager(passwordRepository.Object);
            var isPasswordCorrect = passwordGenerator.CheckPassword(userId, "chicken");

            Assert.IsFalse(isPasswordCorrect);
        }
Exemplo n.º 24
0
        public void CanSerialize()
        {
            IFormatter formatter = new BinaryFormatter();
              Password p1 = new Password("1", "alibalibi");
              using (MemoryStream s = new MemoryStream())
              {
            formatter.Serialize(s, p1);
            s.Seek(0, SeekOrigin.Begin);

            Password p2 = (Password)formatter.Deserialize(s);

            Assert.IsTrue(p2.Matches("1", "alibalibi"));
            Assert.IsFalse(p2.Matches("1", "alibalibi1"));
              }
        }
Exemplo n.º 25
0
        private void Init(Configuration configuration, Password.Classes.Password password)
        {
            tpMain.RowCount = password.Values.Count + 1;

            int i = 0;
            foreach (var passwordValue in password.Values)
            {
                tpMain.RowStyles[i].SizeType = SizeType.AutoSize;

                Control editor;

                if (passwordValue.Field.IsEncrypt)
                {
                    editor = new PasswordTextBox
                    {
                        Configuration = configuration,
                        Title = passwordValue.Field.Name
                    };
                }
                else
                {
                    editor = new LabeledTextBox
                    {
                        Title = passwordValue.Field.Name
                    };
                }

                editor.Dock = DockStyle.Fill;
                editor.Margin = new Padding(8, i == 0 ? 8 : 3, 8, 0);
                editor.Text = passwordValue.Value;
                editor.Tag = passwordValue;

                tpMain.Controls.Add(editor, 0, i);
                tpMain.SetColumnSpan(editor, 2);

                i++;
            }

            CreateButtons(password.Values.Count);

            ClientSize = tpMain.Size;
            MinimumSize = new Size(200, Size.Height);
            MaximumSize = new Size(800, Size.Height);
        }
Exemplo n.º 26
0
        void CreateNewPass()
        {
            if (PBNP.Password!=PBRNP.Password)
            {
                MessageBox.Show("Пароли не совпадают");
                return;
            }
            using (AchievmentsEntities ach=new AchievmentsEntities())
            {
                user = ach.Passwords.Find(App.curPnID);
                if (user.Name != TBLog.Text)
                    user.Name = TBLog.Text;

                MD5 md = new MD5CryptoServiceProvider();
                byte[] bt = Encoding.UTF8.GetBytes(PBNP.Password);

                user.Password1 = bt;
                ach.SaveChanges();
            }
        }
 public void Secure(string user, Password password)
 {
 }
Exemplo n.º 28
0
 public bool ValidatePassword(string password, IEncrypter encrypter) =>
 Password.Equals(encrypter.GetHash(password, Salt));
        //Checking usuer and pass
        //-----------------------
        private void btnOK_Click(object sender, EventArgs e)
        {
            if (UserID.Text == "")
            {
                MessageBox.Show("Please enter user id", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                UserID.Focus();
                return;
            }
            if (Password.Text == "")
            {
                MessageBox.Show("Please enter password", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                Password.Focus();
                return;
            }

            //Matching is the usuer and pass is correct or not
            try
            {
                cc.con = new SqlConnection(cs.DBConn);
                cc.con.Open();
                cc.cmd             = cc.con.CreateCommand();
                cc.cmd.CommandText = "SELECT RTRIM(UserID),RTRIM(Password) FROM Registration where UserID = @d1 and Password=@d2";
                cc.cmd.Parameters.AddWithValue("@d1", UserID.Text);
                cc.cmd.Parameters.AddWithValue("@d2", Password.Text);
                cc.rdr = cc.cmd.ExecuteReader();
                if (cc.rdr.Read())
                {
                    cc.con = new SqlConnection(cs.DBConn);
                    cc.con.Open();
                    cc.cmd             = cc.con.CreateCommand();
                    cc.cmd.CommandText = "SELECT usertype FROM Registration where UserID=@d3 and Password=@d4";
                    cc.cmd.Parameters.AddWithValue("@d3", UserID.Text);
                    cc.cmd.Parameters.AddWithValue("@d4", Password.Text);
                    cc.rdr = cc.cmd.ExecuteReader();
                    if (cc.rdr.Read())
                    {
                        UserType.Text = cc.rdr.GetValue(0).ToString().Trim();
                    }
                    if ((cc.rdr != null))
                    {
                        cc.rdr.Close();
                    }
                    if (cc.con.State == ConnectionState.Open)
                    {
                        cc.con.Close();
                    }

                    //Log in panel for admin
                    if ((UserType.Text == "Admin"))
                    {
                        //frm.lblUser.Text = UserID.Text;
                        // frm.lblUserType.Text = UserType.Text;

                        //Code for log in progress bar
                        ProgressBar1.Visible = true;
                        ProgressBar1.Maximum = 5000;
                        ProgressBar1.Minimum = 0;
                        ProgressBar1.Value   = 4;
                        ProgressBar1.Step    = 1;
                        for (int i = 0; i <= 5000; i++)
                        {
                            ProgressBar1.PerformStep();
                        }
                        st1 = UserID.Text;
                        st2 = "Successfully logged in";
                        cf.LogFunc(st1, System.DateTime.Now, st2);
                        this.Hide();
                        frm.Show();
                    }

                    //llog in panel for operator
                    if ((UserType.Text == "Operator"))
                    {
                        //frm.lblUser.Text = UserID.Text;
                        //frm.lblUserType.Text = UserType.Text;
                        ProgressBar1.Visible = true;
                        ProgressBar1.Maximum = 5000;
                        ProgressBar1.Minimum = 0;
                        ProgressBar1.Value   = 4;
                        ProgressBar1.Step    = 1;
                        for (int i = 0; i <= 5000; i++)
                        {
                            ProgressBar1.PerformStep();
                        }
                        st1 = UserID.Text;
                        st2 = "Successfully logged in";
                        cf.LogFunc(st1, System.DateTime.Now, st2);
                        this.Hide();
                        frm.Show();
                    }
                }
                else
                {
                    MessageBox.Show("Login is Failed...Try again !", "Login Denied", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    UserID.Text   = "";
                    Password.Text = "";
                    UserID.Focus();
                }
                cc.cmd.Dispose();
                cc.con.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemplo n.º 30
0
        private void Connect()
        {
            if (UsageTimer == null)
            {
                //Save Timer Resource for licensed usage
                if (!LicenseUtils.HasLicensedFeature(LicenseFeature.Redis))
                {
                    UsageTimer = new Timer(delegate
                    {
                        __requestsPerHour = 0;
                    }, null, TimeSpan.FromMilliseconds(0), TimeSpan.FromHours(1));
                }
            }

            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            {
                SendTimeout    = SendTimeout,
                ReceiveTimeout = ReceiveTimeout
            };
            try
            {
                if (ConnectTimeout == 0)
                {
                    socket.Connect(Host, Port);
                }
                else
                {
                    var connectResult = socket.BeginConnect(Host, Port, null, null);
                    connectResult.AsyncWaitHandle.WaitOne(ConnectTimeout, true);
                }

                if (!socket.Connected)
                {
                    socket.Close();
                    socket        = null;
                    HadExceptions = true;
                    return;
                }
                Bstream = new BufferedStream(new NetworkStream(socket), 16 * 1024);

                if (Password != null)
                {
                    SendExpectSuccess(Commands.Auth, Password.ToUtf8Bytes());
                }

                if (db != 0)
                {
                    SendExpectSuccess(Commands.Select, db.ToUtf8Bytes());
                }

                try
                {
                    if (ServerVersionNumber == 0)
                    {
                        var parts   = ServerVersion.Split('.');
                        var version = int.Parse(parts[0]) * 1000;
                        if (parts.Length > 1)
                        {
                            version += int.Parse(parts[1]) * 100;
                        }
                        if (parts.Length > 2)
                        {
                            version += int.Parse(parts[2]);
                        }

                        ServerVersionNumber = version;
                    }
                }
                catch (Exception)
                {
                    //Twemproxy doesn't support the INFO command so automatically closes the socket
                    //Fallback to ServerVersionNumber=Unknown then try re-connecting
                    ServerVersionNumber = Unknown;
                    Connect();
                    return;
                }

                var ipEndpoint = socket.LocalEndPoint as IPEndPoint;
                clientPort               = ipEndpoint != null ? ipEndpoint.Port : -1;
                lastCommand              = null;
                lastSocketException      = null;
                LastConnectedAtTimestamp = Stopwatch.GetTimestamp();

                OnConnected();

                if (ConnectionFilter != null)
                {
                    ConnectionFilter(this);
                }
            }
            catch (SocketException ex)
            {
                if (socket != null)
                {
                    socket.Close();
                }
                socket = null;

                HadExceptions = true;
                var throwEx = new RedisException("could not connect to redis Instance at " + Host + ":" + Port, ex);
                log.Error(throwEx.Message, ex);
                throw throwEx;
            }
        }
Exemplo n.º 31
0
        /// <summary>
        /// SimpleBind
        /// This action is used for doing simple authentication.
        /// This method is used for authenticating the Domain user and anonymous user
        /// on both regular and protected LDAP ports
        /// </summary>
        /// <param name="userName">Contains username in Domain</param>
        /// <param name="passWord">Contains the password to the username</param>
        /// <param name="portNum">Contains the port number over which the bind will accomplish</param>
        /// <param name="enableTLS">This variable i used to state when we are using TLS </param>
        /// <returns>Returns Success if the method is successful
        ///  Returns InvalidCredentials if the passed in credentials are invalid</returns>
        public errorstatus SimpleBind(name userName,
                                      Password passWord,
                                      Port portNum,
                                      bool enableTLS)
        {
            //Assigning Authorization mechanism to Bind
            strAuthMech = authenticationMech.simple;

            //Assigning port number .
            enumPortNum = portNum;

            //Valid nameMapsMoreThanOneObject user and valid password
            if ((userName == name.nameMapsMoreThanOneObject) && (passWord == Password.validPassword))
            {
                //name maps more than one object.
                //To validate if name maps more than object
                user = MS_ADTS_SecurityRequirementsValidator.NameMapsMorethanOneObject;

                //Create  an AD User.
                ADTSHelper.CreateActiveDirUser(PdcFqdn, userName, ClientUserPassword, PdcDN);
                //Change the attribute
                ADTSHelper.ModifyOperation(PdcFqdn, userName, adTestType, ClientUserName, ClientUserPassword, PrimaryDomainDnsName, PDCOSVersion);
            }

            else if ((userName == name.nameMapsMoreThanOneObject) && (passWord == Password.invalidPassword))
            {
                //name maps more than one object.
                user = MS_ADTS_SecurityRequirementsValidator.NameMapsMorethanOneObject;
                //Invalid password
                userPassword = MS_ADTS_SecurityRequirementsValidator.InvalidPassword;
            }
            //if invalid user name
            else if (userName == name.nonexistUserName)
            {
                //get from config file
                user = MS_ADTS_SecurityRequirementsValidator.NonExistUserName;
            }
            //valid user
            else if (userName == name.validUserName)
            {
                //get the Current username from config file
                user = ClientUserName;
            }
            //Anonymous user
            else if (userName == name.anonymousUser)
            {
                //Empty user name and Empty password
                //Anonymous user should have (null,null) credentials
                //Setting the credentials to null
                user = null;
            }
            //invalid password
            if ((passWord == Password.invalidPassword) && (userName != name.anonymousUser))
            {
                //get from config file
                userPassword = MS_ADTS_SecurityRequirementsValidator.InvalidPassword;
            }

            if ((passWord == Password.invalidPassword) && (userName == name.anonymousUser))
            {
                //Anonymous user passowrd.
                userPassword = null;
            }

            else if (passWord == Password.validPassword)
            {
                //get from config file
                userPassword = ClientUserPassword;

                if (userName == name.anonymousUser)
                {
                    //anonymous user password.
                    userPassword = null;
                }
            }

            //SimpleBind Authentication
            strResult = adtsRequirementsValidation.SimpleBind(PdcFqdn, (uint)enumPortNum, user, userPassword, enableTLS, adTestType);

            return(strResult);
        }
Exemplo n.º 32
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (Id.Length != 0)
            {
                hash ^= Id.GetHashCode();
            }
            if (Login.Length != 0)
            {
                hash ^= Login.GetHashCode();
            }
            if (Password.Length != 0)
            {
                hash ^= Password.GetHashCode();
            }
            if (created_ != null)
            {
                hash ^= Created.GetHashCode();
            }
            if (passwordUpdate_ != null)
            {
                hash ^= PasswordUpdate.GetHashCode();
            }
            if (agreementAccepted_ != null)
            {
                hash ^= AgreementAccepted.GetHashCode();
            }
            if (IsLocked != false)
            {
                hash ^= IsLocked.GetHashCode();
            }
            if (IsInactive != false)
            {
                hash ^= IsInactive.GetHashCode();
            }
            if (EmailAddress.Length != 0)
            {
                hash ^= EmailAddress.GetHashCode();
            }
            if (PhoneNumber.Length != 0)
            {
                hash ^= PhoneNumber.GetHashCode();
            }
            if (FullName.Length != 0)
            {
                hash ^= FullName.GetHashCode();
            }
            if (ForceChangePassword != false)
            {
                hash ^= ForceChangePassword.GetHashCode();
            }
            if (PrefferredLanguage.Length != 0)
            {
                hash ^= PrefferredLanguage.GetHashCode();
            }
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
Exemplo n.º 33
0
 bool ShouldPromptForPassword()
 {
     return(!WindowsAuthentication.IsBuiltInUsername(Username) && Password.ShouldPrompt());
 }
        private void doDudPasswordTest(string password, int index, string message)
        {
            // illegal state exception check - in this case the wrong password will
            // cause an underlying class cast exception.
            try
            {
                IPasswordFinder pGet = new Password(password.ToCharArray());
                PemReader pemRd = OpenPemResource("test.pem", pGet);

                Object o;
                while ((o = pemRd.ReadObject()) != null)
                {
                }

                Fail("issue not detected: " + index);
            }
            catch (IOException e)
            {
                if (e.Message.IndexOf(message) < 0)
                {
                    Console.Error.WriteLine(message);
                    Console.Error.WriteLine(e.Message);
                    Fail("issue " + index + " exception thrown, but wrong message");
                }
            }
        }
Exemplo n.º 35
0
Arquivo: User.cs Projeto: bagheera/tax
 public User(string id, Password password, IRepository repository)
 {
     this.repository = repository;
     Id = id;
     Password = password;
 }
Exemplo n.º 36
0
 private PasswordFluentBuilder(DifficultyEnum difficulty)
 {
     _password = new Password {
         Difficulty = difficulty
     };
 }
Exemplo n.º 37
0
        /// <summary>
        /// Send message.
        /// </summary>
        /// <param name="message">Message.</param>
        protected override void OnSendInMessage(Message message)
        {
            switch (message.Type)
            {
            case MessageTypes.Reset:
            {
                _subscriptions.Clear();

                if (_client != null)
                {
                    try
                    {
                        DisposeClient();
                    }
                    catch (Exception ex)
                    {
                        SendOutError(ex);
                    }

                    _client = null;
                }

                SendOutMessage(new ResetMessage());

                break;
            }

            case MessageTypes.Connect:
            {
                if (_client != null)
                {
                    throw new InvalidOperationException(LocalizedStrings.Str1619);
                }

                _subscriptions.Clear();

                switch (Remoting)
                {
                case OpenECryRemoting.None:
                case OpenECryRemoting.Primary:
                    _client = new OECClient(new InPlaceThreadPolicy())
                    {
                        UUID = Uuid,
                        EventBatchInterval   = 0,
                        RemoteHostingEnabled = Remoting == OpenECryRemoting.Primary,
                        //PriceHost = "",
                        //AutoSubscribe = false
                    };
                    break;

                case OpenECryRemoting.Secondary:
                    _client = OECClient.CreateInstance(true);
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }

                if (EnableOECLogging)
                {
                    if (Remoting == OpenECryRemoting.Secondary)
                    {
                        this.AddWarningLog(LocalizedStrings.Str2552);
                    }
                    else
                    {
                        OEC.Log.ConsoleOutput = false;
                        _client.SetLoggingConfig(new LoggingConfiguration {
                                Level = OEC.API.LogLevel.All
                            });
                        OEC.Log.Initialize(new OECLogger(this));
                        OEC.Log.Start();
                    }
                }

                _client.OnLoginComplete += SessionOnLoginComplete;
                _client.OnLoginFailed   += SessionOnLoginFailed;
                _client.OnDisconnected  += SessionOnDisconnected;
                _client.OnBeginEvents   += SessionOnBeginEvents;
                _client.OnEndEvents     += SessionOnEndEvents;
                _client.OnError         += SessionOnError;

                _client.OnAccountRiskLimitChanged      += SessionOnAccountRiskLimitChanged;
                _client.OnAccountSummaryChanged        += SessionOnAccountSummaryChanged;
                _client.OnAllocationBlocksChanged      += SessionOnAllocationBlocksChanged;
                _client.OnAvgPositionChanged           += SessionOnAvgPositionChanged;
                _client.OnBalanceChanged               += SessionOnBalanceChanged;
                _client.OnCommandUpdated               += SessionOnCommandUpdated;
                _client.OnCompoundPositionGroupChanged += SessionOnCompoundPositionGroupChanged;
                _client.OnOrderConfirmed               += SessionOnOrderConfirmed;
                _client.OnOrderFilled                += SessionOnOrderFilled;
                _client.OnOrderStateChanged          += SessionOnOrderStateChanged;
                _client.OnDetailedPositionChanged    += SessionOnDetailedPositionChanged;
                _client.OnMarginCalculationCompleted += SessionOnMarginCalculationCompleted;
                _client.OnPortfolioMarginChanged     += SessionOnPortfolioMarginChanged;
                _client.OnPostAllocation             += SessionOnPostAllocation;
                _client.OnRiskLimitDetailsReceived   += SessionOnRiskLimitDetailsReceived;

                _client.OnBarsReceived += SessionOnBarsReceived;
                _client.OnContinuousContractRuleChanged += SessionOnContinuousContractRuleChanged;
                _client.OnContractChanged          += SessionOnContractChanged;
                _client.OnContractCreated          += SessionOnContractCreated;
                _client.OnContractRiskLimitChanged += SessionOnContractRiskLimitChanged;
                _client.OnContractsChanged         += SessionOnContractsChanged;
                _client.OnCurrencyPriceChanged     += SessionOnCurrencyPriceChanged;
                _client.OnDOMChanged               += SessionOnDomChanged;
                _client.OnDealQuoteUpdated         += SessionOnDealQuoteUpdated;
                _client.OnHistogramReceived        += SessionOnHistogramReceived;
                _client.OnHistoryReceived          += SessionOnHistoryReceived;
                _client.OnIndexComponentsReceived  += SessionOnIndexComponentsReceived;
                _client.OnLoggedUserClientsChanged += SessionOnLoggedUserClientsChanged;
                _client.OnNewsMessage              += SessionOnNewsMessage;
                _client.OnOsmAlgoListLoaded        += SessionOnOsmAlgoListLoaded;
                _client.OnOsmAlgoListUpdated       += SessionOnOsmAlgoListUpdated;
                _client.OnPitGroupsChanged         += SessionOnPitGroupsChanged;
                _client.OnPriceChanged             += SessionOnPriceChanged;
                _client.OnPriceTick += SessionOnPriceTick;
                _client.OnProductCalendarUpdated += SessionOnProductCalendarUpdated;
                _client.OnQuoteDetailsChanged    += SessionOnQuoteDetailsChanged;
                _client.OnRelationsChanged       += SessionOnRelationsChanged;
                _client.OnSymbolLookupReceived   += SessionOnSymbolLookupReceived;
                _client.OnTicksReceived          += SessionOnTicksReceived;
                _client.OnTradersChanged         += SessionOnTradersChanged;
                _client.OnUserMessage            += SessionOnUserMessage;
                _client.OnUserStatusChanged      += SessionOnUserStatusChanged;

                _client.Connect(Address.GetHost(), Address.GetPort(), Login, Password.To <string>(), UseNativeReconnect);

                break;
            }

            case MessageTypes.Disconnect:
            {
                if (_client == null)
                {
                    throw new InvalidOperationException(LocalizedStrings.Str1856);
                }

                DisposeClient();
                _client.Disconnect();
                break;
            }

            case MessageTypes.SecurityLookup:
            {
                ProcessSecurityLookup((SecurityLookupMessage)message);
                break;
            }

            case MessageTypes.OrderRegister:
            {
                ProcessOrderRegister((OrderRegisterMessage)message);
                break;
            }

            case MessageTypes.OrderCancel:
            {
                ProcessOrderCancel((OrderCancelMessage)message);
                break;
            }

            case MessageTypes.OrderReplace:
            {
                ProcessOrderReplace((OrderReplaceMessage)message);
                break;
            }

            case MessageTypes.PortfolioLookup:
            {
                ProcessPortfolioLookupMessage((PortfolioLookupMessage)message);
                break;
            }

            case MessageTypes.OrderStatus:
            {
                ProcessOrderStatusMessage();
                break;
            }

            case MessageTypes.MarketData:
            {
                ProcessMarketDataMessage((MarketDataMessage)message);
                break;
            }

            case MessageTypes.News:
            {
                var newsMsg = (Messages.NewsMessage)message;
                _client.SendMessage(_client.Users[newsMsg.Source], newsMsg.Headline);
                break;
            }
            }
        }
Exemplo n.º 38
0
        public override BaseNode GetSPStructure(string siteUrl)
        {
            this.Endpoint = siteUrl;

            if (string.IsNullOrEmpty(this.Endpoint) || string.IsNullOrEmpty(this.Username) || string.IsNullOrEmpty(this.Password))
            {
                LoginWindow loginWindow = new LoginWindow();
                loginWindow.PortalUrl = siteUrl;
                loginWindow.Username  = Username;
                loginWindow.Password  = Password;

                if (this.AuthenticationType == SPCoderConstants.O365_APP)
                {
                    loginWindow.lblUsername.Text = "Client Id";
                    loginWindow.lblPassword.Text = "Client Secret";
                }

                loginWindow.StartPosition = FormStartPosition.CenterParent;
                var rez = loginWindow.ShowDialog();
                if (rez == DialogResult.OK)
                {
                    Username      = loginWindow.Username;
                    Password      = loginWindow.Password;
                    this.Endpoint = siteUrl = loginWindow.PortalUrl;
                    if (this.AuthenticationType == SPCoderConstants.O365_APP && !String.IsNullOrEmpty(Username) && !String.IsNullOrEmpty(Password))
                    {
                        ConfigurationManager.AppSettings["ClientId"]     = Username;
                        ConfigurationManager.AppSettings["ClientSecret"] = Password;
                    }
                }
                else
                {
                    //If Close/Cancel has been clicked
                    return(null);
                }
            }


            if (this.AuthenticationType == SPCoderConstants.O365)
            {
                Context = new ClientContext(siteUrl);
                SecureString pass = new SecureString();
                foreach (char c in Password.ToCharArray())
                {
                    pass.AppendChar(c);
                }
                Context.Credentials = new SharePointOnlineCredentials(Username, pass);
            }
            else if (this.AuthenticationType == SPCoderConstants.O365_APP)
            {
                //Get the realm for the URL
                string realm       = SPCoder.SharePoint.Client.TokenHelper.GetRealmFromTargetUrl(new Uri(siteUrl));
                string accessToken = SPCoder.SharePoint.Client.TokenHelper.GetAppOnlyAccessToken(SPCoder.SharePoint.Client.TokenHelper.SharePointPrincipal, new Uri(siteUrl).Authority, realm).AccessToken;
                Context = SPCoder.SharePoint.Client.TokenHelper.GetClientContextWithAccessToken(siteUrl, accessToken);
            }
            else if (this.AuthenticationType == SPCoderConstants.FBA)
            {
                Context = new ClientContext(siteUrl);
                Context.AuthenticationMode           = ClientAuthenticationMode.FormsAuthentication;
                Context.FormsAuthenticationLoginInfo = new FormsAuthenticationLoginInfo(Username, Password);
            }
            else if (this.AuthenticationType == SPCoderConstants.WIN)
            {
                Context = new ClientContext(siteUrl);
                Context.AuthenticationMode = ClientAuthenticationMode.Default;
                Context.Credentials        = new NetworkCredential(Username, Password);
            }

            var rootNode = this.GenerateRootNode();

            return(rootNode);
        }
Exemplo n.º 39
0
        public LoginViewModel(
            IUserAccessManager userAccessManager,
            IAnalyticsService analyticsService,
            IOnboardingStorage onboardingStorage,
            INavigationService navigationService,
            IErrorHandlingService errorHandlingService,
            ILastTimeUsageStorage lastTimeUsageStorage,
            ITimeService timeService,
            ISchedulerProvider schedulerProvider,
            IRxActionFactory rxActionFactory,
            IInteractorFactory interactorFactory)
            : base(navigationService)
        {
            Ensure.Argument.IsNotNull(userAccessManager, nameof(userAccessManager));
            Ensure.Argument.IsNotNull(analyticsService, nameof(analyticsService));
            Ensure.Argument.IsNotNull(onboardingStorage, nameof(onboardingStorage));
            Ensure.Argument.IsNotNull(errorHandlingService, nameof(errorHandlingService));
            Ensure.Argument.IsNotNull(lastTimeUsageStorage, nameof(lastTimeUsageStorage));
            Ensure.Argument.IsNotNull(timeService, nameof(timeService));
            Ensure.Argument.IsNotNull(schedulerProvider, nameof(schedulerProvider));
            Ensure.Argument.IsNotNull(rxActionFactory, nameof(rxActionFactory));
            Ensure.Argument.IsNotNull(interactorFactory, nameof(interactorFactory));

            this.timeService          = timeService;
            this.userAccessManager    = userAccessManager;
            this.analyticsService     = analyticsService;
            this.onboardingStorage    = onboardingStorage;
            this.errorHandlingService = errorHandlingService;
            this.lastTimeUsageStorage = lastTimeUsageStorage;
            this.schedulerProvider    = schedulerProvider;
            this.interactorFactory    = interactorFactory;

            var emailObservable = emailSubject.Select(email => email.TrimmedEnd());

            Signup         = rxActionFactory.FromAsync(signup);
            ForgotPassword = rxActionFactory.FromAsync(forgotPassword);

            Shake = shakeSubject.AsDriver(this.schedulerProvider);

            Email = emailObservable
                    .Select(email => email.ToString())
                    .DistinctUntilChanged()
                    .AsDriver(this.schedulerProvider);

            Password = passwordSubject
                       .Select(password => password.ToString())
                       .DistinctUntilChanged()
                       .AsDriver(this.schedulerProvider);

            IsLoading = isLoadingSubject
                        .DistinctUntilChanged()
                        .AsDriver(this.schedulerProvider);

            ErrorMessage = errorMessageSubject
                           .DistinctUntilChanged()
                           .AsDriver(this.schedulerProvider);

            IsPasswordMasked = isPasswordMaskedSubject
                               .DistinctUntilChanged()
                               .AsDriver(this.schedulerProvider);

            IsShowPasswordButtonVisible = Password
                                          .Select(password => password.Length > 1)
                                          .CombineLatest(isShowPasswordButtonVisibleSubject.AsObservable(), CommonFunctions.And)
                                          .DistinctUntilChanged()
                                          .AsDriver(this.schedulerProvider);

            HasError = ErrorMessage
                       .Select(string.IsNullOrEmpty)
                       .Select(CommonFunctions.Invert)
                       .AsDriver(this.schedulerProvider);

            LoginEnabled = emailObservable
                           .CombineLatest(
                passwordSubject.AsObservable(),
                IsLoading,
                (email, password, isLoading) => email.IsValid && password.IsValid && !isLoading)
                           .DistinctUntilChanged()
                           .AsDriver(this.schedulerProvider);
        }
Exemplo n.º 40
0
 public override int GetHashCode()
 {
     return(UserName.GetHashCode() & Password.GetHashCode());
 }
Exemplo n.º 41
0
 /// <summary>
 /// Cria um novo usuário no sistema
 /// </summary>
 /// <param name="name">Nome do usuário</param>
 /// <param name="email">E-mail de acesso</param>
 /// <param name="password">Senha de acesso</param>
 public User(string name, string email, string password)
 {
     Name     = name;
     Email    = email;
     Password = new Password(password);
 }
        private void Connect()
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            {
                SendTimeout    = SendTimeout,
                ReceiveTimeout = ReceiveTimeout
            };
            try
            {
                if (ConnectTimeout == 0)
                {
                    socket.Connect(Host, Port);
                }
                else
                {
                    var connectResult = socket.BeginConnect(Host, Port, null, null);
                    connectResult.AsyncWaitHandle.WaitOne(ConnectTimeout, true);
                }

                if (!socket.Connected)
                {
                    socket.Close();
                    socket = null;
                    return;
                }
                Bstream = new BufferedStream(new NetworkStream(socket), 16 * 1024);

                if (Password != null)
                {
                    SendExpectSuccess(Commands.Auth, Password.ToUtf8Bytes());
                }

                if (db != 0)
                {
                    SendExpectSuccess(Commands.Select, db.ToUtf8Bytes());
                }

                var ipEndpoint = socket.LocalEndPoint as IPEndPoint;
                clientPort               = ipEndpoint != null ? ipEndpoint.Port : -1;
                lastCommand              = null;
                lastSocketException      = null;
                LastConnectedAtTimestamp = Stopwatch.GetTimestamp();

                if (ConnectionFilter != null)
                {
                    ConnectionFilter(this);
                }
            }
            catch (SocketException ex)
            {
                if (socket != null)
                {
                    socket.Close();
                }
                socket = null;

                HadExceptions = true;
                var throwEx = new RedisException("could not connect to redis Instance at " + Host + ":" + Port, ex);
                log.Error(throwEx.Message, ex);
                throw throwEx;
            }
        }
 public void PromptSecure(Password password)
 {
 }
Exemplo n.º 44
0
        public async Task<IActionResult> Forgotpassword(string email)
        {
            //generating new password
            var pwdb = new Password();
            var new_password = pwdb.Next();

            // Calling identity methods or functions for change password
            var user = await userManager.FindByEmailAsync(email);

            if (user == null)
            {
                TempData["flash"] = "1";
                TempData["error"] = "User is unavailable in system";
                return View();
            }
            else
            {
                string code = await userManager.GeneratePasswordResetTokenAsync(user);
                var result = await userManager.ResetPasswordAsync(user, code, new_password);

                if (result.Succeeded)
                {

                    SmtpClient client = new SmtpClient("mail.ttcsglobal.com");
                    client.UseDefaultCredentials = false;
                    client.Credentials = new NetworkCredential("companiesonlinezw", "N3wPr0ducts@1");
                    // client.Credentials = new NetworkCredential("username", "password");

                    MailMessage mailMessage = new MailMessage();
                    mailMessage.From = new MailAddress("*****@*****.**");
                    mailMessage.To.Add(email);
                    mailMessage.IsBodyHtml = true;
                    mailMessage.Body = ("<!DOCTYPE html> " +
                        "<html xmlns=\"http://www.w3.org/1999/xhtml\">" +
                        "<head>" +
                            "<title>Email</title>" +
                        "</head>" +

                        "<body style=\"font-family:'Century Gothic'\">" +
                        "<p><b>Hi Dear valued Customer</b></p>" +
                            "<p>Your new password is " + new_password + ".</p>" +
                        "<p>Kindly use the link below to access your account.</p>" +

                        "<a>https://deedsapp.ttcsglobal.com:6868/Auth/Login </a>" +
                        "<p>as a security measure we recomend a that you change your password afterlogin</p>" +
                       "<p> Enjoy our services.</p> " +

                        "<p>Regards</p>" +

                        "<p>DCIP</p>" +

                        "</body>" +
                        "</html>");//GetFormattedMessageHTML();
                    mailMessage.Subject = "Password successfully changed";
                    client.Send(mailMessage);

                    TempData["error"] = "Password has been changed, please check email..=";
                    TempData["flash"] = "2";
                    return View();
                }
                else
                {
                    TempData["error"] = "Password Changed Failed";
                    TempData["flash"] = "1";
                    return View();
                }
            }


            ViewBag.title = "Forgot Password";
            return RedirectToAction("Login", "Auth");

        }
        public override int GetHashCode()
        {
            int hash = 1;

            if (entityId_ != null)
            {
                hash ^= EntityId.GetHashCode();
            }
            if (Name.Length != 0)
            {
                hash ^= Name.GetHashCode();
            }
            if (CardProcessor != 0)
            {
                hash ^= CardProcessor.GetHashCode();
            }
            if (CardAgreement.Length != 0)
            {
                hash ^= CardAgreement.GetHashCode();
            }
            if (LicenseId != 0)
            {
                hash ^= LicenseId.GetHashCode();
            }
            if (SiteId != 0)
            {
                hash ^= SiteId.GetHashCode();
            }
            if (DeviceId != 0)
            {
                hash ^= DeviceId.GetHashCode();
            }
            if (Username.Length != 0)
            {
                hash ^= Username.GetHashCode();
            }
            if (Password.Length != 0)
            {
                hash ^= Password.GetHashCode();
            }
            if (ServiceURI.Length != 0)
            {
                hash ^= ServiceURI.GetHashCode();
            }
            if (DebugLoggingEnabled != false)
            {
                hash ^= DebugLoggingEnabled.GetHashCode();
            }
            if (PorticoDeveloperId.Length != 0)
            {
                hash ^= PorticoDeveloperId.GetHashCode();
            }
            if (PorticoVersionNumber.Length != 0)
            {
                hash ^= PorticoVersionNumber.GetHashCode();
            }
            if (SuppressAuthorizationsInFolio != false)
            {
                hash ^= SuppressAuthorizationsInFolio.GetHashCode();
            }
            return(hash);
        }
 public Input(Name name, Password password)
 {
     Name     = name;
     Password = password;
 }
Exemplo n.º 47
0
 private void TryEnableOk()
 {
     Ok.IsEnabled = !Login.IsEmpty() && !Password.IsEmpty();
 }
Exemplo n.º 48
0
        public async Task <IList <User> > AddParticipants(ParticipantsViewModel participants)
        {
            var          userEvent            = new UserEvent();
            IList <User> participantsToReturn = new List <User>();
            var          eventDB = await _context.Events.FirstOrDefaultAsync(x => x.Id == participants.EventId);

            foreach (var participant in participants.Participants)
            {
                var userDB = _context.Users.FirstOrDefault(x => x.Email == participant.Email);
                if (userDB == null)
                {
                    userDB = new User()
                    {
                        Email    = participant.Email,
                        UserName = participant.Name,
                        IsActive = true
                    };
                    var    password = Password.PasswordGenerator();
                    byte[] passwordSalt, passwordHash;
                    Password.CreateHashPassword(password, out passwordSalt, out passwordHash);
                    userDB.PasswordHash = passwordHash;
                    userDB.PasswordSalt = passwordSalt;

                    _context.Users.Add(userDB);
                    _context.SaveChanges();

                    var claims = new[] {
                        new Claim(ClaimTypes.NameIdentifier, userDB.Id.ToString()),
                        new Claim(ClaimTypes.Name, participant.Email),
                    };

                    var token = _jwtToken.GenerateJwtToken(claims, 336);

                    _sendEmail.CreatingNewUser(participant.Email, eventDB.EventName, token);
                }


                //Check to see where a user was already added and then removed from event
                bool wasAlreadyAdded = false;
                userEvent = _context.UserEvent.FirstOrDefault(x => x.EventId == eventDB.Id && x.UserId == userDB.Id);

                if (!(userEvent == null))
                {
                    userEvent.Participats = true;
                    wasAlreadyAdded       = true;
                }
                else
                {
                    userEvent = new UserEvent()
                    {
                        UserId      = userDB.Id,
                        User        = userDB,
                        EventId     = eventDB.Id,
                        Event       = eventDB,
                        Participats = true
                    };
                }



                if (eventDB.CreatedBy == userDB.Id)
                {
                    userEvent.RoleId = Roles.AdminRole();
                }
                else if (participant.SemiAdmin == true)
                {
                    userEvent.RoleId = Roles.SemiAdminRole();
                }
                else
                {
                    userEvent.RoleId = Roles.UserRole();
                }

                _sendEmail.UserAddToEvent(userDB.Email, userDB.UserName);

                if (wasAlreadyAdded == false)
                {
                    _context.UserEvent.Add(userEvent);
                }



                participantsToReturn.Add(userDB);
            }

            _context.SaveChanges();

            return(participantsToReturn);
        }
Exemplo n.º 49
0
 public void SignIntoAccount(string user, string password)
 {
     UserName.InputText(user);
     Password.InputText(password);
     SignIn.Click();
 }
Exemplo n.º 50
0
        protected void UpdateInformation()
        {
            bool Editing     = Localization.ParseBoolean(ViewState["EditingAffiliate"].ToString());
            int  AffiliateID = Localization.ParseNativeInt(ViewState["EditingAffiliateID"].ToString());

            StringBuilder sql  = new StringBuilder();
            String        Name = txtNickName.Text;

            if (Name.Length == 0)
            {
                if (txtFirstName.Text.Length != 0)
                {
                    Name = (txtFirstName.Text + " " + txtLastName.Text).Trim();
                }
                else
                {
                    Name = txtLastName.Text;
                }
            }
            int ParID = Localization.ParseNativeInt(ddParent.SelectedValue);

            if (ParID == AffiliateID)  // prevent case which causes endless recursion
            {
                ParID = 0;
            }

            if (txtEmail.Text.Trim().Length > 0 && !(new EmailAddressValidator()).IsValidEmailAddress(txtEmail.Text.Trim()))
            {
                resetError(AppLogic.GetString("admin.editAffiliates.InvalidEmailFormat", SkinID, LocaleSetting), true);
                return;
            }

            if (txtEmail.Text.Trim().Length > 0 && Affiliate.EmailInUse(txtEmail.Text.Trim(), AffiliateID))
            {
                resetError(AppLogic.GetString("admin.editAffiliates.TakenEmailAddress", SkinID, LocaleSetting), true);
                return;
            }



            if (!Editing)
            {
                // ok to add them:
                String NewGUID = DB.GetNewGUID();
                sql.Append("insert Affiliate(AffiliateGUID,EMail,Password,SaltKey,DateOfBirth,TrackingOnly,IsOnline,DefaultSkinID,FirstName,LastName,[Name],ParentAffiliateID,[Company],Address1,Address2,Suite,City,State,Zip,Country,Phone,WebSiteName,WebSiteDescription,URL) values(");
                sql.Append(CommonLogic.SQuote(NewGUID) + ",");
                sql.Append(CommonLogic.SQuote(CommonLogic.Left(txtEmail.Text.Trim(), 100)) + ",");

                Password p = new Password(CommonLogic.IsNull(ViewState["affpwd"], "").ToString());
                sql.Append(CommonLogic.SQuote(p.SaltedPassword) + ",");
                sql.Append(p.Salt.ToString() + ",");


                try
                {
                    if (txtBirthdate.Text.Length != 0)
                    {
                        DateTime dob = Localization.ParseNativeDateTime(txtBirthdate.Text);
                        sql.Append(DB.SQuote(Localization.ToDBShortDateString(dob)) + ",");
                    }
                    else
                    {
                        sql.Append("NULL,");
                    }
                }
                catch
                {
                    sql.Append("NULL,");
                }
                if (rblAdTracking.SelectedValue == "0")
                {
                    sql.Append("0,");
                }
                else
                {
                    sql.Append("1,");
                }
                if (txtWebURL.Text.Length != 0)
                {
                    sql.Append("1,");
                }
                else
                {
                    sql.Append("0,");
                }
                sql.Append(Localization.ParseNativeInt(txtSkin.Text) + ",");
                sql.Append(CommonLogic.SQuote(CommonLogic.Left(txtFirstName.Text, 100)) + ",");
                sql.Append(CommonLogic.SQuote(CommonLogic.Left(txtLastName.Text, 100)) + ",");
                sql.Append(CommonLogic.SQuote(CommonLogic.Left(Name, 100)) + ",");
                sql.Append(ParID.ToString() + ",");
                sql.Append(CommonLogic.SQuote(CommonLogic.Left(txtCompany.Text, 100)) + ",");
                if (txtAddress1.Text.Length != 0)
                {
                    sql.Append(CommonLogic.SQuote(txtAddress1.Text.Replace("\x0D\x0A", "")) + ",");
                }
                else
                {
                    sql.Append("NULL,");
                }
                if (txtAddress2.Text.Length != 0)
                {
                    sql.Append(CommonLogic.SQuote(txtAddress2.Text.Replace("\x0D\x0A", "")) + ",");
                }
                else
                {
                    sql.Append("NULL,");
                }
                if (txtSuite.Text.Length != 0)
                {
                    sql.Append(CommonLogic.SQuote(txtSuite.Text) + ",");
                }
                else
                {
                    sql.Append("NULL,");
                }
                if (txtCity.Text.Length != 0)
                {
                    sql.Append(CommonLogic.SQuote(txtCity.Text) + ",");
                }
                else
                {
                    sql.Append("NULL,");
                }
                if (ddState.SelectedValue != "0")
                {
                    sql.Append(CommonLogic.SQuote(ddState.SelectedValue) + ",");
                }
                else
                {
                    sql.Append("NULL,");
                }
                if (txtZip.Text.Length != 0)
                {
                    sql.Append(CommonLogic.SQuote(txtZip.Text) + ",");
                }
                else
                {
                    sql.Append("NULL,");
                }
                if (ddCountry.SelectedValue != "0")
                {
                    sql.Append(CommonLogic.SQuote(ddCountry.SelectedValue) + ",");
                }
                else
                {
                    sql.Append("NULL,");
                }
                if (txtPhone.Text.Length != 0)
                {
                    sql.Append(CommonLogic.SQuote(txtPhone.Text) + ",");
                }
                else
                {
                    sql.Append("NULL,");
                }
                if (txtWebName.Text.Length != 0)
                {
                    sql.Append(CommonLogic.SQuote(txtWebName.Text) + ",");
                }
                else
                {
                    sql.Append("NULL,");
                }
                if (txtWebDescription.Text.Length != 0)
                {
                    sql.Append(CommonLogic.SQuote(txtWebDescription.Text) + ",");
                }
                else
                {
                    sql.Append("NULL,");
                }
                if (txtWebURL.Text.Length != 0)
                {
                    String theUrl = CommonLogic.Left(txtWebURL.Text, 80);
                    if (theUrl.IndexOf("http://") == -1 && theUrl.Length != 0)
                    {
                        theUrl = "http://" + theUrl;
                    }
                    if (theUrl.Length == 0)
                    {
                        sql.Append("NULL");
                    }
                    else
                    {
                        sql.Append(CommonLogic.SQuote(theUrl) + " ");
                    }
                }
                else
                {
                    sql.Append("NULL");
                }

                sql.Append(")");

                DB.ExecuteSQL(sql.ToString());

                resetError("Affiliate added.", false);

                ResetPasswordRow.Visible  = true;
                CreatePasswordRow.Visible = false;

                using (SqlConnection dbconn = DB.dbConn())
                {
                    dbconn.Open();
                    using (IDataReader rs = DB.GetRS("select AffiliateID from Affiliate where deleted=0 and AffiliateGUID=" + CommonLogic.SQuote(NewGUID), dbconn))
                    {
                        rs.Read();
                        AffiliateID = DB.RSFieldInt(rs, "AffiliateID");
                        ViewState["EditingAffiliate"]   = true;
                        ViewState["EditingAffiliateID"] = AffiliateID.ToString();
                    }
                }

                getAffiliateDetails();
            }
            else
            {
                // ok to update:
                sql.Append("update Affiliate set ");
                sql.Append("EMail=" + CommonLogic.SQuote(CommonLogic.Left(txtEmail.Text, 100)) + ",");

                try
                {
                    if (txtBirthdate.Text.Length != 0)
                    {
                        DateTime dob = Localization.ParseNativeDateTime(txtBirthdate.Text);
                        sql.Append("DateOfBirth=" + DB.SQuote(Localization.ToDBShortDateString(dob)) + ",");
                    }
                }
                catch { }
                sql.Append("TrackingOnly=" + CommonLogic.IIF(rblAdTracking.SelectedValue == "1", "1", "0") + ",");
                sql.Append("IsOnline=" + CommonLogic.IIF(txtWebURL.Text.Length == 0, "0", "1") + ",");
                sql.Append("DefaultSkinID=" + Localization.ParseNativeInt(txtSkin.Text) + ",");
                sql.Append("FirstName=" + CommonLogic.SQuote(CommonLogic.Left(txtFirstName.Text, 100)) + ",");
                sql.Append("LastName=" + CommonLogic.SQuote(CommonLogic.Left(txtLastName.Text, 100)) + ",");
                sql.Append("Name=" + CommonLogic.SQuote(CommonLogic.Left(Name, 100)) + ",");
                sql.Append("ParentAffiliateID=" + ParID + ",");
                if (txtCompany.Text.Length != 0)
                {
                    sql.Append("Company=" + CommonLogic.SQuote(txtCompany.Text) + ",");
                }
                else
                {
                    sql.Append("Company=NULL,");
                }
                if (txtAddress1.Text.Length != 0)
                {
                    sql.Append("Address1=" + CommonLogic.SQuote(txtAddress1.Text.Replace("\x0D\x0A", "")) + ",");
                }
                else
                {
                    sql.Append("Address1=NULL,");
                }
                if (txtAddress2.Text.Length != 0)
                {
                    sql.Append("Address2=" + CommonLogic.SQuote(txtAddress2.Text.Replace("\x0D\x0A", "")) + ",");
                }
                else
                {
                    sql.Append("Address2=NULL,");
                }
                if (txtSuite.Text.Length != 0)
                {
                    sql.Append("Suite=" + CommonLogic.SQuote(txtSuite.Text) + ",");
                }
                else
                {
                    sql.Append("Suite=NULL,");
                }
                if (txtCity.Text.Length != 0)
                {
                    sql.Append("City=" + CommonLogic.SQuote(txtCity.Text) + ",");
                }
                else
                {
                    sql.Append("City=NULL,");
                }
                if (ddState.SelectedValue != "0")
                {
                    sql.Append("State=" + CommonLogic.SQuote(ddState.SelectedValue) + ",");
                }
                else
                {
                    sql.Append("State=NULL,");
                }
                if (txtZip.Text.Length != 0)
                {
                    sql.Append("Zip=" + CommonLogic.SQuote(txtZip.Text) + ",");
                }
                else
                {
                    sql.Append("Zip=NULL,");
                }
                if (ddCountry.SelectedValue != "0")
                {
                    sql.Append("Country=" + CommonLogic.SQuote(ddCountry.SelectedValue) + ",");
                }
                else
                {
                    sql.Append("Country=NULL,");
                }
                if (txtPhone.Text.Length != 0)
                {
                    sql.Append("Phone=" + CommonLogic.SQuote(AppLogic.MakeProperPhoneFormat(txtPhone.Text)) + ",");
                }
                else
                {
                    sql.Append("Phone=NULL,");
                }
                if (txtWebName.Text.Length != 0)
                {
                    sql.Append("WebSiteName=" + CommonLogic.SQuote(txtWebName.Text) + ",");
                }
                else
                {
                    sql.Append("WebSiteName=NULL,");
                }
                if (txtWebDescription.Text.Length != 0)
                {
                    sql.Append("WebSiteDescription=" + CommonLogic.SQuote(txtWebDescription.Text) + ",");
                }
                else
                {
                    sql.Append("WebSiteDescription=NULL,");
                }
                if (txtWebURL.Text.Length != 0)
                {
                    String theUrl2 = CommonLogic.Left(txtWebURL.Text, 80);
                    if (theUrl2.IndexOf("http://") == -1 && theUrl2.Length != 0)
                    {
                        theUrl2 = "http://" + theUrl2;
                    }
                    if (theUrl2.Length != 0)
                    {
                        sql.Append("URL=" + CommonLogic.SQuote(theUrl2) + " ");
                    }
                    else
                    {
                        sql.Append("URL=NULL");
                    }
                }
                else
                {
                    sql.Append("URL=NULL");
                }

                sql.Append(" where AffiliateID=" + AffiliateID.ToString());
                DB.ExecuteSQL(sql.ToString());

                resetError("Affiliate updated.", false);

                getAffiliateDetails();
            }
        }
Exemplo n.º 51
0
			public bool Validate()
			{
				int count = Password.Count(c => c == Policy.Char);
				return count >= Policy.Min && count <= Policy.Max;
			}
Exemplo n.º 52
0
 /// <summary>
 /// Metoda wywoływana na deaktywację okna
 /// </summary>
 /// <param name="close"></param>
 protected override void OnDeactivate(bool close)
 {
     Password?.Dispose();
     base.OnDeactivate(close);
 }
Exemplo n.º 53
0
        public ActionResult Register(LoginRegisterModel id)
        {
            //Check if we already have a user registered with the same email address
            if (customerTable.SelectRecord(new SelectCustomerModel()
            {
                Email = id.email
            }).CustomerUUID != null)
            {
                return(Json(new { result = "Fail", reason = "Email address is already registered" }));
            }

            //Generate Password's Salt and Hash
            byte[] salt       = Password.ComputeSaltBytes();
            string hashString = Password.ComputeHash(id.password, salt);
            string saltString = Convert.ToBase64String(salt);

            //Insert into Customer table
            InsertCustomerModel newCustomer = new InsertCustomerModel()
            {
                FirstName = id.firstName,
                LastName  = id.lastName,
                Phone     = id.phone,
                Email     = id.email,
                Hash      = hashString,
                Salt      = saltString
            };
            CustomerResultModel customerResult = customerTable.InsertRecord(newCustomer);

            //If it didn't insert, then we won't get a UUID back
            if (customerResult.CustomerUUID == null)
            {
                return(Json(new { result = "Fail", reason = "Insert into the database was not successful" }));
            }

            //Insert customer's address into the address table
            InsertAddressModel customerAddress = new InsertAddressModel()
            {
                CustomerUUID = customerResult.CustomerUUID,

                BillingAddress  = id.address,
                BillingAddress2 = id.address2,
                BillingCity     = id.city,
                BillingState    = id.state,
                BillingZip      = Int32.Parse(id.postalCode),

                ShippingAddress  = id.address,
                ShippingAddress2 = id.address2,
                ShippingCity     = id.city,
                ShippingState    = id.state,
                ShippingZip      = Int32.Parse(id.postalCode)
            };

            NonQueryResultModel addressResult = addressTable.InsertRecord(customerAddress); //We have the option to 'do something' if the insert fails

            //Insert into Query table
            InsertQueryModel customerQuery = new InsertQueryModel()
            {
                CustomerUUID = customerResult.CustomerUUID,

                Category   = "",
                CategoryID = "",
                Frequency  = "",
                PriceLimit = ""
            };
            NonQueryResultModel queryResult = queryTable.InsertRecord(customerQuery); //If this fails, we have the option of doing something

            //Aaaand we're done.
            return(Json(new { result = "Success" }));
        }
Exemplo n.º 54
0
 private string GeneratePass()
 {
     return(Password.GeneratePassword(8, 2));
 }
Exemplo n.º 55
0
        public ActionResult SignupIFrameSubmit(string email, string password, string password2, string realname, string background, string color)
        {
            if (email.IsNullOrEmpty())
            {
                // Can't use standard RecoverableError things in affiliate forms, do it by hand
                ViewData["error_message"] = "Email is required";
                ViewData["affId"]         = CurrentAffiliate.Id;
                ViewData["realname"]      = realname;
                ViewData["password"]      = password;
                ViewData["password2"]     = password2;

                return(SignupIFrame(null, background, color));
            }

            if (!Models.User.IsValidEmail(ref email))
            {
                // Can't use standard RecoverableError things in affiliate forms, do it by hand
                ViewData["error_message"] = "Email is not valid";
                ViewData["affId"]         = CurrentAffiliate.Id;
                ViewData["realname"]      = realname;
                ViewData["email"]         = email;
                ViewData["password"]      = password;
                ViewData["password2"]     = password2;

                return(SignupIFrame(null, background, color));
            }

            // Check that the captcha succeeded
            string error;

            if (!Captcha.Verify(Request.Form, out error) || !Password.CheckPassword(password, password2, email, null, null, out error))
            {
                // Can't use standard RecoverableError things in affiliate forms, do it by hand
                ViewData["error_message"] = error;
                ViewData["affId"]         = CurrentAffiliate.Id;
                ViewData["email"]         = email;
                ViewData["realname"]      = realname;
                ViewData["password"]      = password;
                ViewData["password2"]     = password2;

                return(SignupIFrame(null, background, color));
            }

            var cookie = System.Web.HttpContext.Current.CookieSentOrReceived(Current.AnonymousCookieName);

            var callback = Current.GetFromCache <string>(CallbackKey(cookie));

            string token, authCode;

            if (!PendingUser.CreatePendingUser(email, password, realname, out token, out authCode, out error))
            {
                // Can't use standard RecoverableError things in affiliate forms, do it by hand
                ViewData["error_message"] = error;
                ViewData["affId"]         = CurrentAffiliate.Id;
                ViewData["email"]         = email;
                ViewData["realname"]      = realname;
                ViewData["password"]      = password;
                ViewData["password2"]     = password2;

                return(SignupIFrame(null, background, color));
            }

            var complete =
                SafeRedirect(
                    (Func <string, string, string, string, string, string, ActionResult>)
                        (new AccountController()).CompleteAffiliateTriggeredRegistration,
                    new
            {
                email,
                affId = CurrentAffiliate.Id,
                token,
                callback,
                realname,
                authCode
            }
                    );

            var completeLink = Current.Url(complete.Url);

            string affName = CurrentAffiliate.HostFilter;
            Uri    callbackUri;

            if (Uri.TryCreate(callback, UriKind.Absolute, out callbackUri))
            {
                affName = callbackUri.Host;
            }

            var success =
                Current.Email.SendEmail(
                    email,
                    Email.Template.CompleteRegistrationViaAffiliate,
                    new {
                AffiliateName    = affName,
                RegistrationLink = completeLink.AsLink()
            });

            if (!success)
            {
                return(IrrecoverableError("An error occurred sending the email", "This has been recorded, and will be looked into shortly"));
            }

            ViewData["Background"] = background;
            ViewData["Color"]      = color;

            return(SuccessEmail("Registration Email Sent to " + email, "Check your email for the link to complete your registration."));
        }
Exemplo n.º 56
0
 public void SetPassword(Password password)
 => passwordSubject.OnNext(password);
Exemplo n.º 57
0
        public static void Main(string[] cmdArgs)
        {
            Console.Title = "Bang# Command-Line Client";
            ConsoleHelper.PrintLine("Bang# Command-Line Client");
            ConsoleHelper.PrintLine("-------------------------");
            ConsoleHelper.PrintLine("Interface version: {0}.{1}", Utils.InterfaceVersionMajor, Utils.InterfaceVersionMinor);
            ConsoleHelper.PrintLine("Operating system: {0}", Environment.OSVersion);
            ConsoleHelper.PrintLine("-------------------------");
            string address;
            string portString;
            if(cmdArgs.Length != 2)
            {
                ConsoleHelper.Print("Server Address: ");
                address = ConsoleHelper.ReadLine();
                ConsoleHelper.Print("Server Port: ");
                portString = ConsoleHelper.ReadLine();
            }
            else
            {
                address = cmdArgs[0];
                portString = cmdArgs[1];
            }
            int port;
            try
            {
                port = int.Parse(portString);
            }
            catch(FormatException)
            {
                ConsoleHelper.ErrorLine("Bad number format!");
                return;
            }
            try
            {
                ConsoleHelper.PrintLine("Connecting to {0} on port {1}...", address, port);
                Utils.OpenClientChannel();
                IServer _server = Utils.Connect(address, port);

                ConsoleHelper.PrintLine();

                if(!Utils.IsServerCompatible(_server))
                {
                    ConsoleHelper.ErrorLine("Server version {0}.{1} not compatible with client version {2}.{3}!",
                        _server.InterfaceVersionMajor, _server.InterfaceVersionMinor,
                        Utils.InterfaceVersionMajor, Utils.InterfaceVersionMinor);
                    return;
                }
                ConsoleHelper.PrintLine("Server name: {0}", _server.Name);
                ConsoleHelper.PrintLine("Server description: {0}", _server.Description);
                _server.RegisterListener(Instance);
                ConsoleHelper.SuccessLine("Connection estabilished!");

                ConsoleHelper.PrintLine();

                NestedCommand rootCmd = new NestedCommand();
                NestedCommand<IServer> serverCmd = new NestedCommand<IServer>(cmd => _server);
                serverCmd.MakeServerCommand();
                NestedCommand<IServer, ISession> sessionCmd = (NestedCommand<IServer, ISession>)serverCmd["session"];
                sessionCmd["join"] = new FinalCommand<ISession>((session, cmd) =>
                {
                    CreatePlayerData cpd;
                    string playerName;
                    Password playerPassword;
                    Password password;
                    if(Instance.sessionControl != null)
                    {
                        ConsoleHelper.ErrorLine("Already connected to a session!");
                        return;
                    }

                    ConsoleHelper.Print("Session Password: "******"Player Name: ");
                    playerName = ConsoleHelper.ReadLine();
                    ConsoleHelper.Print("Player Password: "******"Joined session!");
                    }
                    catch(GameException e)
                    {
                        ConsoleHelper.ErrorLine("Cannot join session: {0}", e.GetType());
                    }
                });
                sessionCmd["joinai"] = new FinalCommand<ISession>((session, cmd) =>
                {
                    CreatePlayerData cpd;
                    Password password;
                    if(Instance.sessionControl != null)
                    {
                        ConsoleHelper.ErrorLine("Already connected to a session!");
                        return;
                    }

                    ConsoleHelper.Print("Session Password: "******"TestAI";

                    try
                    {
                        Instance.SetAI(ai);
                        session.Join(password, cpd, Instance.mainSessionListener);
                        ConsoleHelper.SuccessLine("Joined session!");
                    }
                    catch(GameException e)
                    {
                        Instance.UnsetAI();
                        ConsoleHelper.ErrorLine("Cannot join session: {0}", e.GetType());
                    }
                });
                sessionCmd["replace"] = new FinalCommand<ISession>((session, cmd) =>
                {
                    CreatePlayerData cpd;
                    string playerName;
                    Password playerPassword;
                    Password password;
                    int id;
                    try
                    {
                        id = int.Parse(cmd.Dequeue());
                    }
                    catch(FormatException)
                    {
                        ConsoleHelper.ErrorLine("Bad number format!");
                        return;
                    }

                    if(Instance.sessionControl != null)
                    {
                        ConsoleHelper.ErrorLine("Already connected to a session!");
                        return;
                    }

                    ConsoleHelper.Print("Session Password: "******"Player Name: ");
                    playerName = ConsoleHelper.ReadLine();
                    ConsoleHelper.Print("Player Password: "******"Joined session!");
                    }
                    catch(GameException e)
                    {
                        ConsoleHelper.ErrorLine("Cannot join session: {0}", e.GetType());
                    }
                });
                sessionCmd["replaceai"] = new FinalCommand<ISession>((session, cmd) =>
                {
                    CreatePlayerData cpd;
                    Password playerPassword;
                    Password password;
                    int id;
                    try
                    {
                        id = int.Parse(cmd.Dequeue());
                    }
                    catch(FormatException)
                    {
                        ConsoleHelper.ErrorLine("Bad number format!");
                        return;
                    }

                    if(Instance.sessionControl != null)
                    {
                        ConsoleHelper.ErrorLine("Already connected to a session!");
                        return;
                    }

                    ConsoleHelper.Print("Session Password: "******"Player Password: "******"TestAI";
                    cpd.Password = playerPassword;

                    try
                    {
                        Instance.SetAI(ai);
                        session.Replace(id, password, cpd, Instance.mainSessionListener);
                        ConsoleHelper.SuccessLine("Joined session!");
                    }
                    catch(GameException e)
                    {
                        Instance.UnsetAI();
                        ConsoleHelper.ErrorLine("Cannot join session: {0}", e.GetType());
                    }
                });
                sessionCmd["aitestcontinue"] = new FinalCommand<ISession>((session, cmd) =>
                {
                    CreatePlayerData cpd;
                    Password password;
                    int id;
                    try
                    {
                        id = int.Parse(cmd.Dequeue());
                    }
                    catch(FormatException)
                    {
                        ConsoleHelper.ErrorLine("Bad number format!");
                        return;
                    }

                    if(Instance.sessionControl != null)
                    {
                        ConsoleHelper.ErrorLine("Already connected to a session!");
                        return;
                    }

                    password = new Password("_aitest");

                    AI.AIPlayer ai = new AI.AIPlayer();
                    cpd = ai.CreateData;
                    cpd.Name = "TestAI";
                    cpd.Password = new Password("_aitest");

                    try
                    {
                        Instance.SetAI(ai);
                        Instance.aiTest = true;
                        session.Replace(id, password, cpd, Instance.mainSessionListener);
                        if(Instance.sessionControl.Session.State != SessionState.Playing)
                            Instance.sessionControl.StartGame();
                        ConsoleHelper.SuccessLine("Joined AI Test session!");
                        Console.ReadKey(true);
                        Instance.sessionControl.Disconnect();
                        Instance.sessionControl = null;
                        Instance.gameControl = null;
                        ConsoleHelper.SuccessLine("AI test session disconnected!");
                    }
                    catch(GameException e)
                    {
                        ConsoleHelper.ErrorLine("Cannot join session: {0}", e.GetType());
                    }
                    Instance.UnsetAI();
                    Instance.aiTest = false;
                });
                serverCmd["session"] = sessionCmd;
                serverCmd["test"] = new FinalCommand<IServer>((server, cmd) =>
                {
                    if(Instance.sessionControl != null)
                    {
                        ConsoleHelper.ErrorLine("Already connected to a session!");
                        return;
                    }
                    int playerCount = 4;
                    if(cmd.Count != 0)
                    {
                        try
                        {
                            playerCount = int.Parse(cmd.Dequeue());
                        }
                        catch(FormatException)
                        {
                            ConsoleHelper.ErrorLine("Bad number format!");
                            return;
                        }
                    }

                    CreateSessionData csd = new CreateSessionData { Name = "Test", Description = "", MinPlayers = playerCount, MaxPlayers = playerCount, MaxSpectators = 0, DodgeCity = true };
                    CreatePlayerData cpd = new CreatePlayerData { Name = "Human" };
                    try
                    {
                        server.CreateSession(csd, cpd, Instance.mainSessionListener);
                        ConsoleHelper.SuccessLine("Test session created!");
                    }
                    catch(GameException e)
                    {
                        ConsoleHelper.ErrorLine("Cannot create session: {0}", e.GetType());
                    }
                });
                serverCmd["testai"] = new FinalCommand<IServer>((server, cmd) =>
                {
                    if(Instance.sessionControl != null)
                    {
                        ConsoleHelper.ErrorLine("Already connected to a session!");
                        return;
                    }
                    int playerCount = 4;
                    if(cmd.Count != 0)
                    {
                        try
                        {
                            playerCount = int.Parse(cmd.Dequeue());
                        }
                        catch(FormatException)
                        {
                            ConsoleHelper.ErrorLine("Bad number format!");
                            return;
                        }
                    }

                    CreateSessionData csd = new CreateSessionData { Name = "Test", Description = "", MaxPlayers = playerCount, MinPlayers = playerCount, MaxSpectators = 0, DodgeCity = true };
                    AI.AIPlayer ai = new AI.AIPlayer();
                    CreatePlayerData cpd = ai.CreateData;
                    cpd.Name = "TestAI";
                    try
                    {
                        server.CreateSession(csd, cpd, Instance.mainSessionListener);
                        Instance.SetAI(ai);
                        ConsoleHelper.SuccessLine("Test AI session created!");
                    }
                    catch(GameException e)
                    {
                        ConsoleHelper.ErrorLine("Cannot create session: {0}", e.GetType());
                    }
                });
                serverCmd["aitest"] = new FinalCommand<IServer>((server, cmd) =>
                {
                    if(Instance.sessionControl != null)
                    {
                        ConsoleHelper.ErrorLine("Already connected to a session!");
                        return;
                    }
                    int playerCount = 4;
                    if(cmd.Count != 0)
                    {
                        try
                        {
                            playerCount = int.Parse(cmd.Dequeue());
                        }
                        catch(FormatException)
                        {
                            ConsoleHelper.ErrorLine("Bad number format!");
                            return;
                        }
                    }

                    CreateSessionData csd = new CreateSessionData
                    {
                        Name = "AI Test",
                        Description = "An AI testing session.",
                        MaxPlayers = playerCount,
                        MinPlayers = playerCount,
                        MaxSpectators = 0,
                        PlayerPassword = new Password("_aitest"),
                        DodgeCity = true
                    };
                    AI.AIPlayer ai = new AI.AIPlayer();
                    CreatePlayerData cpd = ai.CreateData;
                    cpd.Name = "TestAI";
                    cpd.Password = new Password("_aitest");
                    try
                    {
                        server.CreateSession(csd, cpd, Instance.mainSessionListener);
                        Instance.SetAI(ai);
                        Instance.aiTest = true;
                        Instance.sessionControl.StartGame();
                        ConsoleHelper.SuccessLine("AI test session created!");
                        Console.ReadKey(true);
                        Instance.sessionControl.Disconnect();
                        Instance.sessionControl = null;
                        Instance.gameControl = null;
                        Instance.UnsetAI();
                        Instance.aiTest = false;
                        ConsoleHelper.SuccessLine("AI test session disconnected!");
                    }
                    catch(GameException e)
                    {
                        ConsoleHelper.ErrorLine("Cannot create session: {0}", e.GetType());
                    }
                });
                serverCmd["createsession"] = new FinalCommand<IServer>((server, cmd) =>
                {
                    if(Instance.sessionControl != null)
                    {
                        ConsoleHelper.ErrorLine("Already connected to a session!");
                        return;
                    }

                    ConsoleHelper.Print("Session Name: ");
                    string sessionName = ConsoleHelper.ReadLine();
                    ConsoleHelper.Print("Session Description: ");
                    string sessionDescription = ConsoleHelper.ReadLine();
                    int sessionMinPlayers;
                    int sessionMaxPlayers;
                    int sessionMaxSpectators;
                    try
                    {
                        ConsoleHelper.Print("Session MinPlayers: ");
                        sessionMinPlayers = int.Parse(ConsoleHelper.ReadLine());
                        ConsoleHelper.Print("Session MaxPlayers: ");
                        sessionMaxPlayers = int.Parse(ConsoleHelper.ReadLine());
                        ConsoleHelper.Print("Session MaxSpectators: ");
                        sessionMaxSpectators = int.Parse(ConsoleHelper.ReadLine());
                    }
                    catch(FormatException)
                    {
                        ConsoleHelper.ErrorLine("Bad number format!");
                        return;
                    }

                    ConsoleHelper.Print("Session PlayerPassword: "******"Session SpectatorPassword: "******"Session ShufflePlayers: ");
                    bool sessionShufflePlayers = ConsoleHelper.ReadLine().ToLower() == "y";
                    ConsoleHelper.Print("Session DodgeCity: ");
                    bool sessionDodgeCity = ConsoleHelper.ReadLine().ToLower() == "y";
                    ConsoleHelper.Print("Session HighNoon: ");
                    bool sessionHighNoon = ConsoleHelper.ReadLine().ToLower() == "y";
                    ConsoleHelper.Print("Session FistfulOfCards: ");
                    bool sessionFistfulOfCards = ConsoleHelper.ReadLine().ToLower() == "y";
                    ConsoleHelper.Print("Session WildWestShow: ");
                    bool sessionWildWestShow = ConsoleHelper.ReadLine().ToLower() == "y";
                    CreateSessionData csd = new CreateSessionData { Name = sessionName, Description = sessionDescription, MinPlayers = sessionMinPlayers, MaxPlayers = sessionMaxPlayers, MaxSpectators = sessionMaxSpectators, PlayerPassword = sessionPlayerPassword, SpectatorPassword = sessionSpectatorPassword, ShufflePlayers = sessionShufflePlayers, DodgeCity = sessionDodgeCity, HighNoon = sessionHighNoon,
                    FistfulOfCards = sessionFistfulOfCards, WildWestShow = sessionWildWestShow };

                    ConsoleHelper.Print("Player Name: ");
                    string playerName = ConsoleHelper.ReadLine();
                    ConsoleHelper.Print("Player Password: "******"Session created!");
                    }
                    catch(GameException e)
                    {
                        ConsoleHelper.ErrorLine("Cannot create session: {0}", e.GetType());
                    }
                });
                rootCmd["server"] = serverCmd;
                NestedCommand<IPlayerSessionControl> sessionControlCommand = new NestedCommand<IPlayerSessionControl>(cmd =>
                {
                    IPlayerSessionControl sessionControl = Instance.sessionControl;
                    if(sessionControl == null)
                    {
                        ConsoleHelper.ErrorLine("Not connected to any session!");
                        return null;
                    }
                    return sessionControl;
                });
                sessionControlCommand.MakePlayerSessionControlCommand(() =>
                {
                    Instance.sessionControl = null;
                    Instance.gameControl = null;
                });
                rootCmd["sessioncontrol"] = sessionControlCommand;
                NestedCommand<IPlayerControl> gameControlCommand = new NestedCommand<IPlayerControl>(cmd =>
                {
                    IPlayerControl gameControl = Instance.gameControl;
                    if(gameControl == null)
                    {
                        ConsoleHelper.ErrorLine("Not playing any game!");
                        return null;
                    }
                    return gameControl;
                });
                gameControlCommand.MakePlayerGameControlCommand();
                rootCmd["gamecontrol"] = gameControlCommand;
                rootCmd["exit"] = new FinalCommand(cmd =>
                {
                    _server.UnregisterListener(Instance);
                    Environment.Exit(0);
                });
                while(true) // command-line loop
                {
                    try
                    {
                        rootCmd.ReadAndExecute();
                    }
                    catch(InvalidOperationException)
                    {
                        ConsoleHelper.ErrorLine("Invalid command!");
                    }
                }
            }
            catch(RemotingException e)
            {
                ConsoleHelper.ErrorLine("Remoting error!");
            #if DEBUG
                ConsoleHelper.DebugLine(e.ToString());
            #endif
                return;
            }
            catch(SerializationException e)
            {
                ConsoleHelper.ErrorLine("Serialization error!");
            #if DEBUG
                ConsoleHelper.DebugLine(e.ToString());
            #endif
                return;
            }
        }
Exemplo n.º 58
0
        public bool ValidateCredentials(string password)
        {
            string passwordHash = BCrypts.HashPassword(password, Salt);

            return(Password.Equals(passwordHash));
        }
        public override void PerformTest()
        {
            IPasswordFinder pGet = new Password("secret".ToCharArray());
            PemReader pemRd = OpenPemResource("test.pem", pGet);
            IAsymmetricCipherKeyPair pair;

            object o;
            while ((o = pemRd.ReadObject()) != null)
            {
            //				if (o is AsymmetricCipherKeyPair)
            //				{
            //					ackp = (AsymmetricCipherKeyPair)o;
            //
            //					Console.WriteLine(ackp.Public);
            //					Console.WriteLine(ackp.Private);
            //				}
            //				else
            //				{
            //					Console.WriteLine(o.ToString());
            //				}
            }

            //
            // pkcs 7 data
            //
            pemRd = OpenPemResource("pkcs7.pem", null);

            ContentInfo d = (ContentInfo)pemRd.ReadObject();

            if (!d.ContentType.Equals(CmsObjectIdentifiers.EnvelopedData))
            {
                Fail("failed envelopedData check");
            }

            /*
            {
                //
                // ECKey
                //
                pemRd = OpenPemResource("eckey.pem", null);

                // TODO Resolve return type issue with EC keys and fix PemReader to return parameters
            //				ECNamedCurveParameterSpec spec = (ECNamedCurveParameterSpec)pemRd.ReadObject();

                pair = (AsymmetricCipherKeyPair)pemRd.ReadObject();
                ISigner sgr = SignerUtilities.GetSigner("ECDSA");

                sgr.Init(true, pair.Private);

                byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' };

                sgr.BlockUpdate(message, 0, message.Length);

                byte[] sigBytes = sgr.GenerateSignature();

                sgr.Init(false, pair.Public);

                sgr.BlockUpdate(message, 0, message.Length);

                if (!sgr.VerifySignature(sigBytes))
                {
                    Fail("EC verification failed");
                }

                // TODO Resolve this issue with the algorithm name, study Java version
            //				if (!((ECPublicKeyParameters) pair.Public).AlgorithmName.Equals("ECDSA"))
            //				{
            //					Fail("wrong algorithm name on public got: " + ((ECPublicKeyParameters) pair.Public).AlgorithmName);
            //				}
            //
            //				if (!((ECPrivateKeyParameters) pair.Private).AlgorithmName.Equals("ECDSA"))
            //				{
            //					Fail("wrong algorithm name on private got: " + ((ECPrivateKeyParameters) pair.Private).AlgorithmName);
            //				}
            }
            */

            //
            // writer/parser test
            //
            IAsymmetricCipherKeyPairGenerator kpGen = GeneratorUtilities.GetKeyPairGenerator("RSA");
            kpGen.Init(
                new RsaKeyGenerationParameters(
                BigInteger.ValueOf(0x10001),
                new SecureRandom(),
                768,
                25));

            pair = kpGen.GenerateKeyPair();

            keyPairTest("RSA", pair);

            //			kpGen = KeyPairGenerator.getInstance("DSA");
            //			kpGen.initialize(512, new SecureRandom());
            DsaParametersGenerator pGen = new DsaParametersGenerator();
            pGen.Init(512, 80, new SecureRandom());

            kpGen = GeneratorUtilities.GetKeyPairGenerator("DSA");
            kpGen.Init(
                new DsaKeyGenerationParameters(
                    new SecureRandom(),
                    pGen.GenerateParameters()));

            pair = kpGen.GenerateKeyPair();

            keyPairTest("DSA", pair);

            //
            // PKCS7
            //
            MemoryStream bOut = new MemoryStream();
            PemWriter pWrt = new PemWriter(new StreamWriter(bOut));

            pWrt.WriteObject(d);
            pWrt.Writer.Close();

            pemRd = new PemReader(new StreamReader(new MemoryStream(bOut.ToArray(), false)));
            d = (ContentInfo)pemRd.ReadObject();

            if (!d.ContentType.Equals(CmsObjectIdentifiers.EnvelopedData))
            {
                Fail("failed envelopedData recode check");
            }

            // OpenSSL test cases (as embedded resources)
            doOpenSslDsaTest("unencrypted");
            doOpenSslRsaTest("unencrypted");

            doOpenSslTests("aes128");
            doOpenSslTests("aes192");
            doOpenSslTests("aes256");
            doOpenSslTests("blowfish");
            doOpenSslTests("des1");
            doOpenSslTests("des2");
            doOpenSslTests("des3");
            doOpenSslTests("rc2_128");

            doOpenSslDsaTest("rc2_40_cbc");
            doOpenSslRsaTest("rc2_40_cbc");
            doOpenSslDsaTest("rc2_64_cbc");
            doOpenSslRsaTest("rc2_64_cbc");

            // TODO Figure out why exceptions differ for commented out cases
            doDudPasswordTest("7fd98", 0, "Corrupted stream - out of bounds length found");
            doDudPasswordTest("ef677", 1, "Corrupted stream - out of bounds length found");
            //			doDudPasswordTest("800ce", 2, "cannot recognise object in stream");
            doDudPasswordTest("b6cd8", 3, "DEF length 81 object truncated by 56");
            doDudPasswordTest("28ce09", 4, "DEF length 110 object truncated by 28");
            doDudPasswordTest("2ac3b9", 5, "DER length more than 4 bytes: 11");
            doDudPasswordTest("2cba96", 6, "DEF length 100 object truncated by 35");
            doDudPasswordTest("2e3354", 7, "DEF length 42 object truncated by 9");
            doDudPasswordTest("2f4142", 8, "DER length more than 4 bytes: 14");
            doDudPasswordTest("2fe9bb", 9, "DER length more than 4 bytes: 65");
            doDudPasswordTest("3ee7a8", 10, "DER length more than 4 bytes: 57");
            doDudPasswordTest("41af75", 11, "malformed sequence in DSA private key");
            doDudPasswordTest("1704a5", 12, "corrupted stream detected");
            //			doDudPasswordTest("1c5822", 13, "corrupted stream detected");
            //			doDudPasswordTest("5a3d16", 14, "corrupted stream detected");
            doDudPasswordTest("8d0c97", 15, "corrupted stream detected");
            doDudPasswordTest("bc0daf", 16, "corrupted stream detected");
            doDudPasswordTest("aaf9c4d",17, "Corrupted stream - out of bounds length found");

            // encrypted private key test
            pGet = new Password("password".ToCharArray());
            pemRd = OpenPemResource("enckey.pem", pGet);

            RsaPrivateCrtKeyParameters privKey = (RsaPrivateCrtKeyParameters)pemRd.ReadObject();

            if (!privKey.PublicExponent.Equals(new BigInteger("10001", 16)))
            {
                Fail("decryption of private key data check failed");
            }

            // general PKCS8 test
            pGet = new Password("password".ToCharArray());
            pemRd = OpenPemResource("pkcs8test.pem", pGet);

            while ((privKey = (RsaPrivateCrtKeyParameters)pemRd.ReadObject()) != null)
            {
                if (!privKey.PublicExponent.Equals(new BigInteger("10001", 16)))
                {
                    Fail("decryption of private key data check failed");
                }
            }
        }
Exemplo n.º 60
0
        private void SetupDialogForm_Load(object sender, EventArgs e)
        {
            try
            {
                TL.LogMessage("SetupForm Load", "Start");

                Version version = Assembly.GetExecutingAssembly().GetName().Version;
                this.Text = $"{DriverDisplayName} Configuration - Version {version} - {DeviceType}";

                // Initialise controls
                cmbServiceType.Text                     = ServiceType;
                numPort.Value                           = PortNumber;
                numRemoteDeviceNumber.Value             = RemoteDeviceNumber;
                numEstablishCommunicationsTimeout.Value = Convert.ToDecimal(EstablishConnectionTimeout);
                numStandardTimeout.Value                = Convert.ToDecimal(StandardTimeout);
                numLongTimeout.Value                    = Convert.ToDecimal(LongTimeout);
                txtUserName.Text                        = UserName.Unencrypt(TL);
                txtPassword.Text                        = Password.Unencrypt(TL);
                chkTrace.Checked                        = TraceState;
                chkDebugTrace.Checked                   = DebugTraceState;
                ChkEnableRediscovery.Checked            = EnableRediscovery;
                NumDiscoveryPort.Value                  = Convert.ToDecimal(DiscoveryPort);

                // Set the IP v4 / v6 radio boxes
                if (IpV4Enabled & IpV6Enabled) // Both IPv4 and v6 are enabled so set the "both" button
                {
                    RadIpV4AndV6.Checked = true;
                }
                else // Only one of v4 or v6 is enabled so set accordingly
                {
                    RadIpV4.Checked = IpV4Enabled;
                    RadIpV6.Checked = IpV6Enabled;
                }

                // Populate the address list combo box
                PopulateAddressList();

                if (ManageConnectLocally)
                {
                    radManageConnectLocally.Checked = true;
                }
                else
                {
                    radManageConnectRemotely.Checked = true;
                }

                CmbImageArrayTransferType.Items.Add(SharedConstants.ImageArrayTransferType.JSON);
                CmbImageArrayTransferType.Items.Add(SharedConstants.ImageArrayTransferType.Base64HandOff);
                CmbImageArrayTransferType.SelectedItem = ImageArrayTransferType;

                cmbImageArrayCompression.Items.Add(SharedConstants.ImageArrayCompression.None);
                cmbImageArrayCompression.Items.Add(SharedConstants.ImageArrayCompression.Deflate);
                cmbImageArrayCompression.Items.Add(SharedConstants.ImageArrayCompression.GZip);
                cmbImageArrayCompression.Items.Add(SharedConstants.ImageArrayCompression.GZipOrDeflate);
                cmbImageArrayCompression.SelectedItem = ImageArrayCompression;

                // Make the ImageArray transfer configuration drop-downs visible only when a camera driver is being accessed.
                if (DeviceType == "Camera")
                {
                    cmbImageArrayCompression.Visible    = true;
                    CmbImageArrayTransferType.Visible   = true;
                    LabImageArrayConfiguration1.Visible = true;
                    LabImageArrayConfiguration2.Visible = true;
                }
                else
                {
                    cmbImageArrayCompression.Visible    = false;
                    CmbImageArrayTransferType.Visible   = false;
                    LabImageArrayConfiguration1.Visible = false;
                    LabImageArrayConfiguration2.Visible = false;
                }

                // Handle cases where the stored registry value is not one of the currently supported modes
                if (CmbImageArrayTransferType.SelectedItem == null)
                {
                    CmbImageArrayTransferType.SelectedItem = SharedConstants.IMAGE_ARRAY_TRANSFER_TYPE_DEFAULT;
                }
                if (cmbImageArrayCompression.SelectedItem == null)
                {
                    cmbImageArrayCompression.SelectedItem = SharedConstants.IMAGE_ARRAY_COMPRESSION_DEFAULT;
                }

                // Bring this form to the front of the screen
                this.WindowState = FormWindowState.Minimized;
                this.Show();
                this.WindowState = FormWindowState.Normal;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception initialising Dynamic Driver: " + ex.ToString());
            }
        }