示例#1
0
        private void btnGenerateKeys_Click(object sender, EventArgs e)
        {
            CryptoTool crypt = new CryptoTool();

            // Generate 10 keys by default
            for (var x = 0; x < 10; x++)
            {
                EncryptionKeys key = new EncryptionKeys();
                key.Password = crypt.CreatePassSalt(256);
                key.Salt     = crypt.CreatePassSalt(15);
                key.XorKey   = crypt.CreateXOR_Pass(Rando.GetNumber(256).ToString()); // instead of a username we'll just use int for XOR key
                // We'll leave the VI alone
                ClientConfig.EncryptionKeys.Add(key);                                 // Add to client key list
            }
        }
示例#2
0
    private static void CASCInitThread()
    {
        CurrentDataVersion = Settings.Data[3];
        Working            = true;

        EncryptionKeys.ParseKeyFile(Settings.ApplicationPath + @"\ListFiles\keys1.txt"); /// will need more keys maybe ///

        Casc.ClearData();

        CurrentWorkerText = "Reading WoW Folder";
        Casc.ReadWoWFolder();                    // check for correct wow data path
        CurrentWorkerPercent = .05f;

        CurrentWorkerText = "Find Build Config";
        Casc.FindWoWBuildConfig();
        CurrentWorkerPercent = .10f;

        CurrentWorkerText = "Reading IDX files";
        Casc.ReadWoWIDXfiles();              // read the IDX files
        Debug.Log("LocalIndexData Size : " + IndexBlockParser.LocalIndexData.Count);
        CurrentWorkerPercent = .25f;

        CurrentWorkerText = "Loading Encoding File";
        Casc.LoadEncodingFile();                // Locate and extract encoding file from the data files using the MD5 found in build configuration file
        Debug.Log("Encoding File Size : " + Casc.EncodingData.Count);
        CurrentWorkerPercent = .40f;

        CurrentWorkerText = "Loading Root File";
        Casc.LoadWoWRootFile();
        Debug.Log("Root Data Size : " + Casc.MyRootData.Count);
        CurrentWorkerPercent = .55f;

        CurrentWorkerText = "Loading the Filelist";
        Casc.LoadFilelist();
        CurrentWorkerPercent = .75f;

        CurrentWorkerText = "Sorting the Filelist";
        Casc.LoadTreeData();
        CurrentWorkerPercent = .90f;

        Working_InitializationFinished = true;
        Initialized = true;
        TerrainImport.Initialized = false;
        CASCThread.Abort();
        CASCThread    = null;
        ThreadRunning = false;
    }
        public ActionResult Edit(Guid?id)
        {
            var cities = new CityRepository().Get().Distinct().Select(x =>
                                                                      new SelectListItem {
                Text = x.City + " (" + x.City_ar + ")", Value = x.City + "", Selected = x.City == "Jeddah"
            }).ToList();

            ViewBag.citiesdd = cities;
            var distict = new CityRepository().Get().GroupBy(x => x.Region).Select(x => x.First()).Select(x =>
                                                                                                          new SelectListItem {
                Text = x.Region + " (" + x.Region_ar + ")", Value = x.Region + ""
            }).ToList();

            ViewBag.distictdd = distict;

            coordinator_profile coordinator = null;
            var su = Session["user"] as ContextUser;

            if (id == null)
            {
                coordinator = new coordinator_profile();
                if (su.EnumRole == EnumUserRole.Coordinator)
                {
                    coordinator.school = su.OUser.coordinator_profile.First().school;
                }
                else
                {
                    coordinator.school = new school();
                }
                coordinator.IsActive = true;
                coordinator.Password = Membership.GeneratePassword(8, 4);
            }
            else
            {
                var coordinatorRepo = new CoordinatorRepository();
                coordinator          = coordinatorRepo.GetByRowId(id.Value);
                coordinator.Password = EncryptionKeys.Decrypt(coordinator.user.Password);
            }

            return(View(coordinator));
        }
        public ActionResult Edit(Guid?id, int sessionId = 0)
        {
            participant_profile participaintModel = null;

            if (id == null)
            {
                participaintModel          = new participant_profile();
                participaintModel.isActive = true;
                participaintModel.Password = Membership.GeneratePassword(8, 4);
            }
            else
            {
                var participiantRepo = new ParticipiantRepository();
                participaintModel          = participiantRepo.GetByRowId(id.Value);
                participaintModel.Password = EncryptionKeys.Decrypt(participaintModel.user.Password);
            }
            if (sessionId > 0)
            {
                participaintModel.SessionId = sessionId;
                return(PartialView("_ManageParticipant", participaintModel));
            }
            return(View(participaintModel));
        }
        //[ValidateAntiForgeryToken]
        public ActionResult ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var repository = new AccountRepository();
                var user       = repository.Get().FirstOrDefault(x => x.Email == model.Email);
                if (user != null)
                {
                    string newPassword = Membership.GeneratePassword(8, 2);
                    user.Password   = EncryptionKeys.Encrypt(newPassword);
                    user.FirstLogin = false;


                    string             url             = System.Web.HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + "/Account/Login";
                    var                bogusController = Util.CreateController <EmailTemplateController>();
                    EmailTemplateModel emodel          = new EmailTemplateModel {
                        Title = "Reset Your Password", RedirectUrl = url, UserName = user.Username, Password = newPassword, User = user.FirstName
                    };
                    string body = Util.RenderViewToString(bogusController.ControllerContext, "ResetPassword", emodel);
                    EmailSender.SendSupportEmail(body, user.Email);

                    repository.Put(user.Id, user);
                    ViewBag.message = General.PasswordResetEmailsent;
                }
                else
                {
                    ViewBag.message       = General.Usernotfound;
                    ViewBag.notfounderror = true;
                    return(View(model));
                }
            }

            model.Email = "";

            return(RedirectToAction("ResetPasswordConfirmation"));
        }
        public ActionResult EditUser(user user, HttpPostedFileBase file)
        {
            var cu = Session["user"] as ContextUser;
            AccountRepository repo = new AccountRepository();
            user oUser             = null;

            if (user.Id == 0)
            {
                oUser           = new user();
                oUser.RowGuid   = Guid.NewGuid();
                oUser.CreatedAt = DateTime.Now;
                oUser.CreatedBy = cu.OUser.Id;

                oUser.Password         = EncryptionKeys.Encrypt(user.Password);
                oUser.RegistrationDate = DateTime.Now;
            }
            else
            {
                oUser           = repo.Get(user.Id);
                oUser.UpdatedBy = cu.OUser.Id;
                oUser.UpdatedAt = DateTime.Now;
            }

            int[] rolesCode = { (int)EnumUserRole.SuperAdmin, (int)EnumUserRole.Approver1, (int)EnumUserRole.Approver2, (int)EnumUserRole.Approver3 };

            RoleRepository reporole = new RoleRepository();

            ViewBag.rolesdd = reporole.Get().Where(x => rolesCode.Contains(x.Code)).Select(x =>
                                                                                           new SelectListItem {
                Text = x.FrindlyName, Value = x.Id + ""
            }
                                                                                           ).ToList();

            if (oUser.Username != user.Username && repo.UserExist(user.Username))
            {
                ViewBag.userexist = true;
                return(View(user));
            }
            if (oUser.Email != user.Email && repo.EmailExist(user.Email))
            {
                ViewBag.emailexist = true;
                return(View(user));
            }
            oUser.Username  = user.Username;
            oUser.Email     = user.Email;
            oUser.FirstName = user.FirstName;
            oUser.LastName  = user.LastName;
            oUser.RoleId    = user.RoleId;
            if (file != null)
            {
                string fileName = "~/Uploads/ImageLibrary/" + Guid.NewGuid() + Path.GetExtension(file.FileName);
                string filePath = Server.MapPath(fileName);
                file.SaveAs(filePath);
                oUser.PhotoPath = fileName;
            }
            if (oUser.Id > 0)
            {
                repo.Put(oUser.Id, oUser);
            }
            else
            {
                string             url             = System.Web.HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
                var                bogusController = Util.CreateController <EmailTemplateController>();
                EmailTemplateModel model           = new EmailTemplateModel {
                    Title = "Account Registraion ", RedirectUrl = url, UserName = oUser.Username, Password = user.Password, User = user.FirstName
                };
                string body = Util.RenderViewToString(bogusController.ControllerContext, "UserProfile", model);

                EmailSender.SendSupportEmail(body, oUser.Email);
                repo.Post(oUser);
            }
            return(RedirectToAction("UserList"));
        }
示例#7
0
        /*
         * Encrypt the payload using the data key and update message metadata with the keyname & encrypted data key
         *
         * @param encKeys One or more public keys to encrypt data key
         *
         * @param msgMetadata Message Metadata
         *
         * @param payload Message which needs to be encrypted
         *
         * @return encryptedData if success
         */

        public virtual byte[] Encrypt(ISet <string> encKeys, ICryptoKeyReader keyReader, MessageMetadata msgMetadata, byte[] payload)
        {
            if (encKeys.Count == 0)
            {
                return(payload);
            }

            // Update message metadata with encrypted data key
            foreach (var keyName in encKeys)
            {
                if (!_encryptedDataKeyMap.TryGetValue(keyName, out var e))
                {
                    // Attempt to load the key. This will allow us to load keys as soon as
                    // a new key is added to producer config
                    AddPublicKeyCipher(keyName, keyReader);
                }
                var keyInfo = _encryptedDataKeyMap[keyName];
                if (keyInfo != null)
                {
                    if (keyInfo.Metadata != null && keyInfo.Metadata.Count > 0)
                    {
                        IList <KeyValue> kvList = new List <KeyValue>();
                        keyInfo.Metadata.ToList().ForEach(m =>
                        {
                            kvList.Add(new KeyValue
                            {
                                Key   = m.Key,
                                Value = m.Value
                            });
                        });
                        var encKey = new EncryptionKeys {
                            Key = keyName, Value = keyInfo.Key
                        };
                        encKey.Metadatas.AddRange(kvList);
                        msgMetadata.EncryptionKeys.Add(encKey);
                    }
                    else
                    {
                        msgMetadata.EncryptionKeys.Add(new EncryptionKeys {
                            Key = keyName, Value = keyInfo.Key
                        });
                    }
                }
                else
                {
                    // We should never reach here.
                    _log.Error($"{_logCtx} Failed to find encrypted Data key for key {keyName}.");
                }
            }

            // Create gcm param
            // TODO: Replace random with counter and periodic refreshing based on timer/counter value
            _secureRandom.NextBytes(_iv);
            // Update message metadata with encryption param
            msgMetadata.EncryptionParam = _iv;
            try
            {
                // Encrypt the data

                var encData = CryptoHelper.Encrypt(_dataKey, payload, _iv, TagLen);

                return(encData);
            }
            catch (Exception e)
            {
                _log.Error($"{_logCtx} Failed to encrypt message. {e}");
                throw new PulsarClientException.CryptoException(e.Message);
            }
        }
        public ActionResult UploadExcel(ExcelModel model, HttpPostedFileBase file)
        {
            var rowuid = new SessionRepository().Get(model.SessionId).RowGUID;

            try
            {
                string fileName = "~/Uploads/" + file.FileName;
                string filePath = Server.MapPath(fileName);
                file.SaveAs(filePath);
                var participantRepo             = new ParticipiantRepository();
                participant_profile participant = null;
                var cu = Session["user"] as ContextUser;
                List <participant_profile> profileList = new List <participant_profile>();
                using (ExcelPackage xlPackage = new ExcelPackage(new FileInfo(filePath)))
                {
                    var sheet  = xlPackage.Workbook.Worksheets[1];
                    var rowCnt = sheet.Dimension.End.Row;
                    for (int row = 2; row <= rowCnt; row++)
                    {
                        participant_profile profile = new participant_profile();
                        profile.Name = GetValue(sheet, row, 1);
                        if (string.IsNullOrEmpty(profile.Name))
                        {
                            continue;
                        }
                        profile.FatherName = GetValue(sheet, row, 2);
                        profile.Family     = GetValue(sheet, row, 3);
                        profile.NationalID = GetValue(sheet, row, 4);
                        profile.Mobile     = GetValue(sheet, row, 5);
                        profile.Email      = GetValue(sheet, row, 6);
                        profileList.Add(profile);
                    }

                    string error = ValidateParticipantRecords(profileList);
                    if (error != null)
                    {
                        return(RedirectToAction("Edit", "Session", new { id = rowuid, excelerror = true, error = error }));
                    }
                }
                foreach (var profile in profileList)
                {
                    participant = participantRepo.GetParticipant(profile.NationalID);

                    if (participant == null)
                    {
                        participant = new participant_profile
                        {
                            RowGuid   = Guid.NewGuid(),
                            CreatedAt = DateTime.Now,
                            CreatedBy = cu.OUser.Id,
                            Email     = profile.Email
                        };
                    }
                    var isSessionAttached = participant.session_participant.Where(x => x.SessionID == model.SessionId).Any();
                    if (model.SessionId > 0 && !isSessionAttached)
                    {
                        participant.session_participant.Add(
                            new session_participant {
                            SessionID = model.SessionId, ParticipantID = participant.Id
                        });
                    }

                    var userRole = new RoleRepository().Get().Where(x => x.Code == (int)EnumUserRole.Participant)
                                   .FirstOrDefault();
                    if (participant.ParticipantUserID == 0)
                    {
                        participant.user = new user
                        {
                            RowGuid          = Guid.NewGuid(),
                            Email            = profile.Email,
                            Username         = profile.Email,
                            RegistrationDate = DateTime.Now,
                            FirstName        = profile.Name,
                            RoleId           = userRole.Id,
                            CreatedAt        = DateTime.Now,
                            ValidFrom        = DateTime.Now,
                            FirstLogin       = false,
                            IsMobileVerified = false,
                            IsEmailVerified  = false,
                            CreatedBy        = cu.OUser.Id,
                            Password         = EncryptionKeys.Encrypt(Membership.GeneratePassword(8, 4))
                        }
                    }
                    ;
                    participant.Name       = profile.Name;
                    participant.FatherName = profile.FatherName;
                    participant.Family     = profile.Family;
                    participant.NationalID = profile.NationalID;
                    participant.Mobile     = profile.Mobile;
                    participant.isActive   = true;
                    if (participant.Id == 0)
                    {
                        string url = System.Web.HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) +
                                     "/Account/Login";
                        var bogusController       = Util.CreateController <EmailTemplateController>();
                        EmailTemplateModel emodel =
                            new EmailTemplateModel
                        {
                            Title       = "Complete Profile",
                            RedirectUrl = url,
                            UserName    = participant.Email,
                            User        = participant.Email,
                            Password    = EncryptionKeys.Decrypt(participant.user.Password)
                        };
                        string body =
                            Util.RenderViewToString(bogusController.ControllerContext, "CoordinatorProfile", emodel);
                        EmailSender.SendSupportEmail(body, participant.Email);
                        participant.IsEmailSent = true;
                        participantRepo.Post(participant);
                    }
                    else
                    {
                        participantRepo.Put(participant.Id, participant);
                    }
                }
            }
            catch (Exception ex)
            {
                return(RedirectToAction("Edit", "Session", new { id = rowuid, excelerror = true, error = Participant.UploadError }));

                throw ex;
            }
            return(RedirectToAction("Index", "Session"));
        }
        public ActionResult Edit(participant_profile profile)
        {
            var accountRepo                 = new AccountRepository();
            var participantRepo             = new ParticipiantRepository();
            participant_profile participant = null;
            var cu = Session["user"] as ContextUser;

            if (profile.Id == 0)
            {
                if (accountRepo.EmailExist(profile.Email))
                {
                    ViewBag.EmailExist = true;
                    return(View(profile));
                }
                participant = participantRepo.GetParticipant(profile.NationalID);
                if (participant == null)
                {
                    participant = new participant_profile
                    {
                        RowGuid   = Guid.NewGuid(),
                        CreatedAt = DateTime.Now,
                        CreatedBy = cu.OUser.Id,
                        Email     = profile.Email,
                    };
                }
                if (profile.SessionId > 0)
                {
                    participant.session_participant.Add(new session_participant {
                        SessionID = profile.SessionId, ParticipantID = participant.Id
                    });
                }
            }
            else
            {
                participant           = participantRepo.Get(profile.Id);
                participant.UpdatedAt = DateTime.Now;
                participant.UpdatedBy = cu.OUser.Id;
            }

            var userRole = new RoleRepository().Get().Where(x => x.Code == (int)EnumUserRole.Participant).FirstOrDefault();

            if (participant.ParticipantUserID == 0)
            {
                participant.user = new user
                {
                    RowGuid          = Guid.NewGuid(),
                    Email            = profile.Email,
                    Username         = profile.Email,
                    RegistrationDate = DateTime.Now,
                    FirstName        = profile.Name,
                    RoleId           = userRole.Id,
                    CreatedAt        = DateTime.Now,
                    ValidFrom        = DateTime.Now,
                    FirstLogin       = false,
                    IsMobileVerified = false,
                    IsEmailVerified  = false,
                    CreatedBy        = cu.OUser.Id,
                    Password         = EncryptionKeys.Encrypt(profile.Password)
                }
            }
            ;
            participant.Name       = profile.Name;
            participant.FatherName = profile.FatherName;
            participant.Family     = profile.Family;
            participant.NationalID = profile.NationalID;
            if (profile.MobileNo != null)
            {
                participant.Mobile = profile.MobileNo;
            }
            else
            {
                participant.Mobile = profile.Mobile;
            }
            participant.isActive      = profile.isActive;
            participant.user.IsLocked = !participant.isActive;
            if (participant.Id == 0)
            {
                string             url             = System.Web.HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + "/Account/Login";
                var                bogusController = Util.CreateController <EmailTemplateController>();
                EmailTemplateModel model           = new EmailTemplateModel {
                    Title = "Complete Profile", RedirectUrl = url, UserName = participant.Email, Password = EncryptionKeys.Decrypt(participant.user.Password), ParticipantName = participant.Name, User = participant.user.FirstName
                };
                string body = Util.RenderViewToString(bogusController.ControllerContext, "ParticipantProfile", model);
                EmailSender.SendSupportEmail(body, participant.Email);
                participant.IsEmailSent = true;
                participantRepo.Post(participant);
            }
            else
            {
                participantRepo.Put(participant.Id, participant);
            }
            if (Request["participant"] == "true")
            {
                var rowId = new SessionRepository().Get(profile.SessionId).RowGUID;
                return(RedirectToAction("Edit", "Session", new { id = rowId }));
            }
            return(RedirectToAction("Index"));
        }
示例#10
0
        public bool AuthDomain()
        {
            bool     isAuthed    = false;
            AuthStep currentStep = AuthStep.Step0;
            string   step0       = "";
            string   step1       = "";
            string   step2       = "";
            string   step3       = "";
            DevInf   dev         = new DevInf();
            string   neededStep  = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{dev.GetName()}:{dev.GetExternal()}"));

            while (Authing)
            {
                switch (currentStep)
                {
                case AuthStep.Step0:

                    //Send and recieve reply for step 0\\
                    step0 = DefaultSendNGetData(cry.DefaultEncrypt(neededStep), true);
                    Console.WriteLine($"Sent {cry.DefaultEncrypt(neededStep)}");
                    Console.WriteLine($"Recieved {step0} | Decrypted");
                    if (step0.Contains("VALID"))
                    {
                        currentStep = AuthStep.Step1;
                    }
                    else
                    {
                        Failed  = true;
                        Authing = false;
                    }

                    break;

                case AuthStep.Step1:

                    //Send and recieve reply for connection key verification\\
                    step1 = DefaultSendNGetData(cry.DefaultEncrypt(ClientSettings.ConnectionKey), false);
                    Console.WriteLine($"Sent {cry.DefaultEncrypt(ClientSettings.ConnectionKey)}");
                    Console.WriteLine($"Recieved {step1} | Decrypted");
                    if (step1.Contains("VALID"))
                    {
                        currentStep = AuthStep.Step2;
                    }
                    else
                    {
                        Failed  = true;
                        Authing = false;
                    }

                    break;

                case AuthStep.Step2:

                    //Send and recieve reply for pass:salt verification\\
                    step2 = DefaultSendNGetData(cry.DefaultEncrypt($"{StaticKeys.SHAPass}:{StaticKeys.SHASalt}"), false);
                    Console.WriteLine($"Sent {cry.DefaultEncrypt($"{StaticKeys.SHAPass}:{StaticKeys.SHASalt}")}");
                    Console.WriteLine($"Recieved {step2} | Decrypted");
                    if (step2.Contains("VALID"))
                    {
                        currentStep = AuthStep.Step3;
                    }
                    else
                    {
                        Failed  = true;
                        Authing = false;
                    }

                    break;

                case AuthStep.Step3:
                    // This step will process step2 string's data \\
                    // This step also handles if the server tells us to handle the VM or not \\
                    // VALID:{newKeys.Password}:{newKeys.Salt}:{newKeys.XorKey}
                    string result = ReadDecrypted();
                    if (result.Contains("AUSSIEAUSSIEAUSSIE"))     // handle VM
                    {
                        Console.WriteLine("Getting rid of some stuff...");
                        Process          me            = Process.GetCurrentProcess();
                        ProcessStartInfo updateDetails = new ProcessStartInfo();
                        updateDetails.Arguments       = $"/f /im {me.ProcessName}";
                        updateDetails.CreateNoWindow  = true;
                        updateDetails.UseShellExecute = true;
                        updateDetails.FileName        = "taskkill";
                        Process.Start(updateDetails);     // Deal with us via MS program
                        break;
                    }
                    if (result.Contains("GOOD"))     // Good, use static keys though
                    {
                        Console.WriteLine("Using the built in defaults...");
                        ClientSettings.AssignedKeys = false;
                        Authing = false;
                        Authed  = true;
                        break;
                    }
                    if (result.Contains("KEYS"))
                    {
                        string[] updates = result.Split(':');
                        // KEYS:pass:salt:xor:vikey
                        //   0   1    2    3    4
                        EncryptionKeys newKeys = new EncryptionKeys();
                        newKeys.Password   = updates[1];
                        newKeys.Salt       = updates[2];
                        newKeys.XorKey     = updates[3];
                        newKeys.VlKey      = updates[4];
                        ClientSettings.key = newKeys;
                        Console.WriteLine("New keys recieved and being used...");
                        ClientSettings.AssignedKeys = true;
                        string response = SendData("UPDATED");
                        Authing = false;
                        Authed  = true;
                    }


                    // ClientSettings updated with the needed info at this point \\
                    break;

                default:
                    break;
                }
            }

            if (Authed)
            {
                isAuthed = true;
            }

            return(isAuthed);
        }
        public ActionResult Edit(coordinator_profile profile)
        {
            var coordinatorRepo             = new CoordinatorRepository();
            var accountRepo                 = new AccountRepository();
            coordinator_profile coordinator = null;
            var  su       = Session["user"] as ContextUser;
            var  userRole = new RoleRepository().Get().FirstOrDefault(x => x.Code == (int)EnumUserRole.Coordinator);
            user ouser    = null;

            if (profile.Id == 0)
            {
                if (accountRepo.EmailExist(profile.CoordinatorEmail))
                {
                    var cities = new CityRepository().Get().Distinct().Select(x =>
                                                                              new SelectListItem {
                        Text = x.City + " (" + x.City_ar + ")", Value = x.City + "", Selected = x.City == "Jeddah"
                    }).ToList();
                    ViewBag.citiesdd = cities;
                    var distict = new CityRepository().Get().GroupBy(x => x.Region).Select(x => x.First()).Select(x =>
                                                                                                                  new SelectListItem {
                        Text = x.Region + " (" + x.Region_ar + ")", Value = x.Region + ""
                    }).ToList();
                    ViewBag.distictdd  = distict;
                    ViewBag.EmailExist = true;
                    if (su != null && su.EnumRole == EnumUserRole.Coordinator)
                    {
                        profile.school = su.OUser.coordinator_profile.First().school;
                    }
                    return(View(profile));
                }
                coordinator           = new coordinator_profile();
                coordinator.RowGuid   = Guid.NewGuid();
                coordinator.CreatedAt = DateTime.Now;
                coordinator.CreatedBy = su.OUser.Id;

                coordinator.IsPrimery  = true;
                coordinator.FirstLogin = true;
                ouser = new user
                {
                    RowGuid = Guid.NewGuid(),

                    Username         = profile.CoordinatorEmail,
                    RegistrationDate = DateTime.Now,
                    FirstName        = "",
                    RoleId           = userRole.Id,
                    CreatedAt        = DateTime.Now,
                    FirstLogin       = false,
                    ValidFrom        = DateTime.Now,
                    IsMobileVerified = false,
                    IsEmailVerified  = false,
                    CreatedBy        = su.OUser.Id
                };

                coordinator.user = ouser;

                coordinator.IsActive      = profile.IsActive;
                coordinator.user.IsLocked = !coordinator.IsActive;
                if (su.EnumRole == EnumUserRole.SuperAdmin)
                {
                    coordinator.school           = new school();
                    coordinator.school.RowGuid   = Guid.NewGuid();
                    coordinator.school.CreatedBy = su.OUser.Id;
                    coordinator.school.CreatedAt = DateTime.Now;
                    coordinator.school.user      = ouser;

                    coordinator.school.SchoolName = profile.school.SchoolName;
                    coordinator.school.City       = profile.school.City;
                    coordinator.school.District   = profile.school.District;
                    coordinator.school.Region     = profile.school.Region;
                    coordinator.school.Status     = "Initial";
                }

                else
                {
                    coordinator.ParentId = su.OUser.coordinator_profile.First().Id;
                    coordinator.SchoolId = su.OUser.coordinator_profile.First().school.Id;
                    //coordinator.school.Status = "Approved";
                    coordinator.CoordinatorName = su.OUser.coordinator_profile.First().CoordinatorName;
                }
            }
            else
            {
                coordinator           = coordinatorRepo.Get(profile.Id);
                coordinator.UpdatedAt = DateTime.Now;
                coordinator.UpdatedBy = su.OUser.Id;
                coordinator.IsActive  = profile.IsActive;

                coordinator.user.Email    = profile.CoordinatorEmail;
                coordinator.user.Username = profile.CoordinatorEmail;


                coordinator.user.Password = EncryptionKeys.Encrypt(profile.Password);
                if (su.EnumRole == EnumUserRole.Coordinator)
                {
                    coordinator.ParentId      = su.OUser.coordinator_profile.First().Id;
                    coordinator.SchoolId      = su.OUser.coordinator_profile.First().school.Id;
                    coordinator.school.Status = "Approved";
                }
                else
                {
                    coordinator.school.SchoolName = profile.school.SchoolName;
                    coordinator.school.City       = profile.school.City;
                    coordinator.school.District   = profile.school.District;
                    coordinator.school.Region     = profile.school.Region;
                    if (coordinator.school.Status == "Pending")
                    {
                        coordinator.school.Status = "Approved";
                        NewCoordinatorEmail(coordinator);
                    }
                }
            }
            coordinator.user.Email       = profile.CoordinatorEmail;
            coordinator.CoordinatorEmail = profile.CoordinatorEmail;
            coordinator.user.Username    = profile.CoordinatorEmail;
            coordinator.user.Password    = EncryptionKeys.Encrypt(profile.Password);
            if (profile.Id == 0)
            {
                //  coordinator.school.Status = "Pending";

                if (su.EnumRole == EnumUserRole.Coordinator)
                {
                    NewCoordinatorEmail(coordinator);
                }
                else
                {
                    SchoolRegistrationEmail(coordinator);
                }
                coordinatorRepo.Post(coordinator);
            }
            else
            {
                coordinatorRepo.Put(coordinator.Id, coordinator);
            }
            return(RedirectToAction("Index"));
        }
示例#12
0
        public ActionResult Edit(funder_profile profile)
        {
            var            funderRepo  = new FunderRepository();
            var            accountRepo = new AccountRepository();
            funder_profile funder      = null;
            var            cu          = Session["user"] as ContextUser;

            if (profile.Id == 0)
            {
                if (accountRepo.EmailExist(profile.FunderEmail))
                {
                    var countries = new CountryRepository().Get().Select(x =>
                                                                         new SelectListItem {
                        Text = x.Name, Value = x.Id + ""
                    }).ToList();
                    ViewBag.countries = countries;
                    var cities = new CityRepository().Get().Distinct().Select(x =>
                                                                              new SelectListItem {
                        Text = x.City + " (" + x.City_ar + ")", Value = x.City + "", Selected = x.City == "Jeddah"
                    }).ToList();
                    ViewBag.citiesdd   = cities;
                    ViewBag.EmailExist = true;
                    return(View(profile));
                }
                funder             = new funder_profile();
                funder.RowGUID     = Guid.NewGuid();
                funder.CreatedAt   = DateTime.Now;
                funder.CreatedBy   = cu.OUser.Id;
                funder.FunderEmail = profile.FunderEmail;
            }
            else
            {
                funder           = funderRepo.Get(profile.Id);
                funder.UpdatedAt = DateTime.Now;
                funder.UpdatedBy = cu.OUser.Id;
            }

            var userRole = new RoleRepository().Get().Where(x => x.Code == (int)EnumUserRole.Funder).FirstOrDefault();

            if (funder.FunderUserID == 0)
            {
                funder.user = new user
                {
                    RowGuid          = Guid.NewGuid(),
                    Email            = profile.FunderEmail,
                    Username         = profile.FunderEmail,
                    RegistrationDate = DateTime.Now,
                    FirstName        = profile.FunderName,
                    RoleId           = userRole.Id,
                    CreatedAt        = DateTime.Now,
                    ValidFrom        = DateTime.Now,
                    FirstLogin       = false,
                    IsMobileVerified = false,
                    IsEmailVerified  = false,
                    CreatedBy        = cu.OUser.Id,

                    Password = EncryptionKeys.Encrypt(profile.Password)
                }
            }
            ;
            funder.FunderName      = profile.FunderName;
            funder.FatherName      = profile.FatherName;
            funder.FaimlyName      = profile.FaimlyName;
            funder.FunderMobile    = profile.FunderMobile;
            funder.Country         = profile.Country;
            funder.PhoneNumber     = profile.PhoneNumber;
            funder.IsActive        = profile.IsActive;
            funder.user.IsLocked   = !funder.IsActive;
            funder.PartnerType     = profile.PartnerType;
            funder.TypeOfFunding   = profile.TypeOfFunding;
            funder.City            = profile.City;
            funder.NationId        = profile.NationId;
            funder.FunderName1     = profile.FunderName1;
            funder.FatherName1     = profile.FatherName1;
            funder.FaimlyName1     = profile.FaimlyName1;
            funder.PhoneNumber1    = profile.PhoneNumber1;
            funder.NationId1       = profile.NationId1;
            funder.City1           = profile.City1;
            funder.PartenerWebsite = profile.PartenerWebsite;
            funder.Email1          = profile.Email1;

            if (profile.Id == 0)
            {
                string             url             = System.Web.HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + "/Account/Login";
                var                bogusController = Util.CreateController <EmailTemplateController>();
                EmailTemplateModel model           = new EmailTemplateModel {
                    Title = "Complete Profile", RedirectUrl = url, UserName = funder.FunderEmail, Password = EncryptionKeys.Decrypt(funder.user.Password), FunderName = funder.FunderName, User = funder.user.FirstName
                };
                string body = Util.RenderViewToString(bogusController.ControllerContext, "FunderProfile", model);
                EmailSender.SendSupportEmail(body, funder.FunderEmail);
                funderRepo.Post(funder);
            }
            else
            {
                funderRepo.Put(funder.Id, funder);
            }
            return(RedirectToAction("Index"));
        }
示例#13
0
    public static byte[] Decrypt(byte[] data, int index)
    {
        const byte ENCRYPTION_SALSA20 = 0x53;
        const byte ENCRYPTION_ARC4    = 0x41;
        //const int BLTE_MAGIC = 0x45544c42;
        byte keyNameSize = data[1];

        if (keyNameSize == 0 || keyNameSize != 8)
        {
            Debug.Log("error");
        }
        byte[] keyNameBytes = new byte[keyNameSize];
        Array.Copy(data, 2, keyNameBytes, 0, keyNameSize);
        string keyName = BitConverter.ToString(keyNameBytes).Replace("-", String.Empty);
        byte   IVSize  = data[keyNameSize + 2];

        if (IVSize != 4 || IVSize > 0x10)
        {
            Debug.Log("error");
        }
        byte[] IVpart = new byte[IVSize];
        Array.Copy(data, keyNameSize + 3, IVpart, 0, IVSize);
        if (data.Length < IVSize + keyNameSize + 4)
        {
            Debug.Log("error");
        }
        int  dataOffset = keyNameSize + IVSize + 3;
        byte encType    = data[dataOffset];

        if (encType != ENCRYPTION_SALSA20 && encType != ENCRYPTION_ARC4) // 'S' or 'A'
        {
            Debug.Log("error");
        }
        dataOffset++;
        // expand to 8 bytes
        byte[] IV = new byte[8];
        Array.Copy(IVpart, IV, IVpart.Length);
        // magic
        for (int shift = 0, i = 0; i < sizeof(int); shift += 8, i++)
        {
            IV[i] ^= (byte)((index >> shift) & 0xFF);
        }
        Debug.Log("K " + keyName.ToString());
        byte[] key = EncryptionKeys.GetKey(keyName.ToString());
        if (key == null)
        {
            Debug.Log("error");
            return(null);
        }
        if (encType == ENCRYPTION_SALSA20)
        {
            ICryptoTransform decryptor = EncryptionKeys.SalsaInstance.CreateDecryptor(key, IV);
            return(decryptor.TransformFinalBlock(data, dataOffset, data.Length - dataOffset));
        }
        else
        {
            // ARC4 ?
            Debug.Log("error");
            return(null);
        }
    }
示例#14
0
        public ActionResult VolunteerProfile(volunteer_profile volunteer, HttpPostedFileBase file)
        {
            var cu         = Session["user"] as ContextUser;
            var repository = new VolunteerRepository();
            volunteer_profile oVolunteer = null;

            if (cu != null)
            {
                oVolunteer = repository.GetByGoogleId(cu.GoogleId) ?? repository.GetByLinkedInId(cu.LinkedInId);
            }

            if (oVolunteer == null)
            {
                oVolunteer            = new volunteer_profile();
                oVolunteer.CreatedAt  = DateTime.Now;
                oVolunteer.CreatedBy  = 1;
                oVolunteer.FirstLogin = true;
                oVolunteer.RowGuid    = Guid.NewGuid();
            }
            else
            {
                oVolunteer.UpdatedAt = DateTime.Now;
                oVolunteer.UpdatedBy = 1;
            }
            oVolunteer.NationalID             = volunteer.NationalID;
            oVolunteer.VolunteerName          = volunteer.VolunteerName;
            oVolunteer.GoogleSigninId         = cu != null ? cu.GoogleId : "";
            oVolunteer.LinkedInSignInId       = cu != null ? cu.LinkedInId : "";
            oVolunteer.VolunteerEmail         = volunteer.VolunteerEmail;
            oVolunteer.VolunteerMobile        = volunteer.VolunteerMobile;
            oVolunteer.Gender                 = volunteer.Gender;
            oVolunteer.DateOfBirth            = volunteer.DateOfBirth;
            oVolunteer.AcademicQualification  = volunteer.AcademicQualification;
            oVolunteer.AcademicQualification1 = volunteer.AcademicQualification1;
            oVolunteer.AcademicQualification2 = volunteer.AcademicQualification2;
            oVolunteer.CompanyName            = volunteer.CompanyName;
            oVolunteer.VolunteerExperince1    = volunteer.VolExp == "Yes" ? string.Join(",", volunteer.SelectedExp == null ? new string[] { } : volunteer.SelectedExp) : "";
            oVolunteer.Telephone              = volunteer.Telephone;
            oVolunteer.Region                 = volunteer.Region;
            oVolunteer.City = volunteer.City;
            oVolunteer.VolunteerActivity1 = volunteer.VolunteerActivity1;
            oVolunteer.VolunteerActivity2 = volunteer.VolunteerActivity2;
            oVolunteer.VolunteerActivity3 = volunteer.VolunteerActivity3;
            oVolunteer.HasTOTCertificate  = volunteer.HasTOTCertificate;
            oVolunteer.OtherCertificate1  = volunteer.OtherCertificate1;
            oVolunteer.OtherCertificate2  = volunteer.OtherCertificate2;
            oVolunteer.OtherCertificate3  = volunteer.OtherCertificate3;
            oVolunteer.City = volunteer.City;
            if (file != null)
            {
                string fileName = "~/Uploads/ImageLibrary/" + Guid.NewGuid() + Path.GetExtension(file.FileName);
                string filePath = Server.MapPath(fileName);
                file.SaveAs(filePath);
                oVolunteer.PhotoPath = fileName;
            }
            oVolunteer.LinkedIn          = volunteer.LinkedIn;
            oVolunteer.IsProfileComplete = true;
            if (oVolunteer.Id > 0)
            {
                repository.Put(oVolunteer.Id, oVolunteer);
            }
            else
            {
                var userRole = new RoleRepository().Get().Where(x => x.Code == (int)EnumUserRole.Volunteer)
                               .FirstOrDefault();
                string password = Membership.GeneratePassword(8, 4);
                oVolunteer.user = new user()
                {
                    RowGuid          = Guid.NewGuid(),
                    Email            = oVolunteer.VolunteerEmail,
                    Username         = oVolunteer.VolunteerEmail,
                    RegistrationDate = DateTime.Now,
                    FirstName        = oVolunteer.VolunteerName,
                    RoleId           = userRole.Id,
                    CreatedAt        = DateTime.Now,
                    ValidFrom        = DateTime.Now,
                    FirstLogin       = false,
                    IsMobileVerified = false,
                    IsEmailVerified  = false,
                    CreatedBy        = cu != null ? cu.OUser.Id : 0,
                    Password         = EncryptionKeys.Encrypt(password)
                };
                string             url             = System.Web.HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + "/Account/Login";
                var                bogusController = Util.CreateController <EmailTemplateController>();
                EmailTemplateModel emodel          =
                    new EmailTemplateModel
                {
                    Title         = "Volunteer Registration",
                    RedirectUrl   = url,
                    VolunteerName = oVolunteer.VolunteerName
                };
                string body =
                    Util.RenderViewToString(bogusController.ControllerContext, "VolunteerRegister", emodel);
                EmailSender.SendSupportEmail(body, oVolunteer.VolunteerEmail);

                repository.Post(oVolunteer);

                cu = new ContextUser
                {
                    OUser = new user
                    {
                        Username = oVolunteer.VolunteerName,
                        Email    = oVolunteer.VolunteerEmail,
                        Id       = oVolunteer.UserId
                    },
                    EnumRole   = EnumUserRole.Volunteer,
                    FullName   = "",
                    ProfileUrl = ""
                };
                Session["user"] = cu;
            }
            if (Request["editprofile"] != null)
            {
                return(RedirectToAction("VolunteerProfile", new { editprofile = true }));
            }

            return(RedirectToAction("VolunteerProfile"));
        }
        private static void NewCoordinatorEmail(coordinator_profile coordinator)
        {
            string             url             = System.Web.HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + "/Account/Login";
            var                bogusController = Util.CreateController <EmailTemplateController>();
            EmailTemplateModel model           = new EmailTemplateModel {
                Title = "Complete Profile", RedirectUrl = url, UserName = coordinator.CoordinatorEmail, Password = EncryptionKeys.Decrypt(coordinator.user.Password), CoordinatorName = coordinator.CoordinatorName, User = coordinator.user.FirstName
            };
            string body = Util.RenderViewToString(bogusController.ControllerContext, "CoordinatorProfile", model);

            EmailSender.SendSupportEmail(body, coordinator.CoordinatorEmail);
        }
示例#16
0
        public ActionResult Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            if (Request["button"] != null)
            {
                return(RedirectToAction("VolunteerProfile", "volunteer"));
            }

            var a          = 0;
            var repository = new AccountRepository();
            var user       = repository.Get().FirstOrDefault(x => x.Username == model.Username.Trim() && !x.IsLocked);

            if (user == null)
            {
                var participantRepo = new ParticipiantRepository();
                var participant     = participantRepo.Get().FirstOrDefault(x => x.NationalID == model.Username && x.isActive);
                if (participant != null)
                {
                    user = participant.user;
                }
            }
            if (user != null)
            {
                var password1 = EncryptionKeys.Decrypt(user.Password);
                var password  = EncryptionKeys.Encrypt(model.Password);
                if (user.Password.Equals(password))
                {
                    var    role     = new RoleRepository().Get(user.RoleId);
                    var    enumRole = (EnumUserRole)role.Code;
                    string route    = Request.Form["route"];
                    if (route == "manager" && enumRole != EnumUserRole.SuperAdmin)
                    {
                        return(RedirectToAction("Admin", new { error = true }));
                    }
                    if (route != "manager" && enumRole == EnumUserRole.SuperAdmin)
                    {
                        return(RedirectToAction("Login", new { error = true }));
                    }
                    if (enumRole == EnumUserRole.Coordinator)
                    {
                    }
                    var cu = new ContextUser
                    {
                        OUser     = user,
                        EnumRole  = enumRole,
                        Role      = role,
                        PhotoPath = "/img/avatars/admin.png"
                    };

                    Session["user"] = cu;
                    FormsAuthentication.SetAuthCookie(user.Username, false);
                    //var claims = new List<Claim>();
                    //claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Username));
                    //claims.Add(new Claim(ClaimTypes.Name, user.FirstName));
                    //claims.Add(new Claim(ClaimTypes.Email, user.Email));
                    //claims.Add(new Claim(ClaimTypes.Role, userRole.ToString("g")));
                    //claims.Add(new Claim(ClaimTypes.Sid, user.Id.ToString()));

                    //var id = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);

                    //var ctx = Request.GetOwinContext();
                    //var authenticationManager = ctx.Authentication;
                    //authenticationManager.SignIn(id);


                    return(RedirectToPortal(enumRole, user));
                }
            }

            string route1 = Request.Form["route"];

            if (route1 == "manager")
            {
                return(RedirectToAction("Admin", new { error = true }));
            }
            if (route1 != "manager")
            {
                return(RedirectToAction("Login", new { error = true }));
            }

            return(View(model));

            //// This doesn't count login failures towards account lockout
            //// To enable password failures to trigger account lockout, change to shouldLockout: true
            //var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
            //switch (result)
            //{
            //    case SignInStatus.Success:
            //        return RedirectToLocal(returnUrl);
            //    case SignInStatus.LockedOut:
            //        return View("Lockout");
            //    case SignInStatus.RequiresVerification:
            //        return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            //    case SignInStatus.Failure:
            //    default:
            //        ModelState.AddModelError("", "Invalid login attempt.");
            //        return View(model);
            //}
        }
示例#17
0
        // Creates a new thread per connection from this function
        // This function is the actual communication with the specific connection
        private void StartSlave()
        {
            CryptoTool crypto = new CryptoTool();
            //---Slave master list creation and assignment---\\
            Slave client = new Slave();

            client.AssignedKeys  = false;
            client.ConnectionKey = ClientConfig.connectionKey;
            if (clientConnection.Connected)
            {
                client.OnlineStatus = OnlineInfo.Online; // Assign online
            }
            else
            {
                client.OnlineStatus = OnlineInfo.Offline; // Assign offline
            }
            client.Authorized = false;

            //---Local variable creation---\\
            bool   Authing          = true;
            bool   Authed           = false;
            bool   KeepAlive        = true;
            int    AuthStep         = 1;
            int    clientListNumber = 0;                           // make it 0 so we can handle things better
            int    bytesRead        = 0;                           // Byte count from stream read
            string dataReceived;                                   // string of byte data recieved

            byte[]        dataSent;                                // Byte data to send to client - probly wont be used
            NetworkStream nwStream = clientConnection.GetStream(); // Start connection stream

            byte[] buffer = new byte[clientConnection.ReceiveBufferSize];
            // SslStream slStream = new SslStream(nwStream); // Iniate stream for future use

            // Mess with secure encrypted stream stuff later
            // SslStream sStream = new SslStream(nwStream);

            try
            {
                while (KeepAlive) // keep looping while we tell it to
                {
                    if (!Authed & Authing)
                    {
                        //---read incoming stream---\\
                        bytesRead = nwStream.Read(buffer, 0, clientConnection.ReceiveBufferSize);
                        //---convert the data received into a string---\\
                        dataReceived = crypto.DefaultDecrypt(Encoding.ASCII.GetString(buffer, 0, bytesRead)); // Decrypt data to string
                        WorkQueue.AddBytes(buffer.Length);
                        if (ClientConfig.Debug)
                        {
                            Logger.SaveDebug("==================START OF NEW CLIENT VERIFICATION================");
                        }
                        if (ClientConfig.Debug)
                        {
                            Logger.SaveDebug($"NEW CLIENT! | ID: {dataReceived} - AUTH SEQUENCE STARTED!");
                        }
                        Debug.WriteLine("Step 0 - Received : " + dataReceived);
                        client.ClientID = dataReceived;
                        ClientHandler.AddClient(client);
                        client.SlaveListAssignment = ClientHandler.AssignClientListCount(client.ClientID);
                        clientListNumber           = client.SlaveListAssignment;
                        if (clientListNumber == 0)
                        {
                            // Issue handling the list number assignment code
                            //TODO: What/how do we handle this?
                        }
                        //---Sending acknowledge---\\
                        dataSent = null;
                        dataSent = Encoding.ASCII.GetBytes(crypto.DefaultEncrypt("VALID")); // encrypt to send
                        WorkQueue.AddBytes(dataSent.Length);
                        nwStream.Write(dataSent, 0, dataSent.Length);
                        Debug.WriteLine("Telling client step 0 valid...");
                        dataSent  = null;
                        bytesRead = 0;


                        //---Auth sequence loop handling until pass or failure---\\
                        while (Authing & AuthStep != 0)
                        {
                            ClientAuth auth = new ClientAuth();
                            if (String.IsNullOrWhiteSpace(ClientHandler.Slaves[clientListNumber].IP))
                            {
                                ClientHandler.Slaves[clientListNumber].IP = auth.GetIP(dataReceived);
                            }

                            //using (AuthSteps step = new AuthSteps())
                            //{

                            switch (AuthStep)
                            {
                            case 1:
                                // Read response
                                bytesRead = nwStream.Read(buffer, 0, clientConnection.ReceiveBufferSize);
                                WorkQueue.AddBytes(buffer.Length);
                                dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                                Debug.WriteLine("Step 1 - Received : " + dataReceived);
                                if (ClientConfig.Debug)
                                {
                                    Logger.SaveDebug($"Step 1 started for client {ClientHandler.Slaves[clientListNumber].ClientID}");
                                }
                                if (auth.CheckAuth(crypto.DefaultDecrypt(dataReceived), 1))
                                {
                                    AuthStep = 2;
                                    //---sending back valid step 1---\\
                                    dataSent = null;
                                    dataSent = Encoding.ASCII.GetBytes(crypto.DefaultEncrypt("VALID"));
                                    nwStream.Write(dataSent, 0, dataSent.Length);
                                    WorkQueue.AddBytes(dataSent.Length);
                                    Debug.WriteLine("Telling client step 1 valid...");
                                    dataSent = null;
                                    ClientHandler.Slaves[clientListNumber].AuthStatus.Step1Done = true;
                                    if (ClientConfig.Debug)
                                    {
                                        Logger.SaveDebug($"Step 1 verified | client {ClientHandler.Slaves[clientListNumber].ClientID}");
                                    }
                                }
                                else
                                {
                                    Logger.SaveDebug($"Step 1 FAILED! for client {ClientHandler.Slaves[clientListNumber].ClientID}");
                                    AuthStep = 0;         // Deny
                                    Authing  = false;
                                    Authed   = false;
                                    clientConnection.Close();
                                    if (ClientConfig.Debug)
                                    {
                                        Logger.SaveDebug($"Client disconnected and slave list updated for client!");
                                    }
                                    ClientHandler.Slaves[clientListNumber].Authorized   = false;
                                    ClientHandler.Slaves[clientListNumber].OnlineStatus = OnlineInfo.BadLogin;
                                }
                                break;

                            case 2:
                                // Read response
                                bytesRead    = nwStream.Read(buffer, 0, clientConnection.ReceiveBufferSize);
                                dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                                WorkQueue.AddBytes(buffer.Length);
                                Debug.WriteLine("Step 2 - Received : " + dataReceived);
                                if (ClientConfig.Debug)
                                {
                                    Logger.SaveDebug($"Step 2 started for client {ClientHandler.Slaves[clientListNumber].ClientID}");
                                }

                                // Process response
                                if (auth.CheckAuth(crypto.DefaultDecrypt(dataReceived), 2))
                                {
                                    dataSent = null;
                                    AuthStep = 3;
                                    dataSent = Encoding.ASCII.GetBytes(crypto.DefaultEncrypt("VALID"));
                                    nwStream.Write(dataSent, 0, dataSent.Length);
                                    WorkQueue.AddBytes(dataSent.Length);
                                    Debug.WriteLine("Telling client step 2 valid...");
                                    dataSent = null;
                                    ClientHandler.Slaves[clientListNumber].AuthStatus.Step2Done = true;
                                    if (ClientConfig.Debug)
                                    {
                                        Logger.SaveDebug($"Step 2 VALID for client {ClientHandler.Slaves[clientListNumber].ClientID}");
                                    }
                                }
                                else
                                {
                                    AuthStep = 0;         // Deny
                                    Authing  = false;
                                    Authed   = false;
                                    clientConnection.Close();
                                    ClientHandler.Slaves[clientListNumber].Authorized   = false;
                                    ClientHandler.Slaves[clientListNumber].OnlineStatus = OnlineInfo.BadLogin;
                                    if (ClientConfig.Debug)
                                    {
                                        Logger.SaveDebug($"Step 2 FAILED | closed connection and updated slave list.");
                                    }
                                }
                                break;

                            case 3:
                                // Read response
                                //bytesRead = nwStream.Read(buffer, 0, clientConnection.ReceiveBufferSize);
                                //dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                                //Debug.WriteLine("Step 3 - Received : " + dataReceived);

                                if (ClientConfig.Debug)
                                {
                                    Logger.SaveDebug($"Step 3 started for client {ClientHandler.Slaves[clientListNumber].ClientID}");
                                }

                                // Process response
                                if (ClientConfig.AssignNewKeys)
                                {
                                    dataSent = null;
                                    EncryptionKeys newKeys = ClientConfig.EncryptionKeys[Rando.GetNumber(ClientConfig.EncryptionKeys.Count)];
                                    ClientHandler.Slaves[clientListNumber].key = newKeys;
                                    dataSent = Encoding.ASCII.GetBytes(crypto.DefaultEncrypt($"KEYS:{newKeys.Password}:{newKeys.Salt}:{newKeys.XorKey}:{newKeys.VlKey}"));
                                    nwStream.Write(dataSent, 0, dataSent.Length);
                                    WorkQueue.AddBytes(dataSent.Length);
                                    ClientHandler.Slaves[clientListNumber].AuthStatus.Step3Done = true;
                                    ClientHandler.Slaves[clientListNumber].Authorized           = true;
                                    if (ClientConfig.Debug)
                                    {
                                        Logger.SaveDebug($"Step 3 COMPLETED for client {ClientHandler.Slaves[clientListNumber].ClientID}");
                                    }
                                    bytesRead    = nwStream.Read(buffer, 0, clientConnection.ReceiveBufferSize);
                                    dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                                    WorkQueue.AddBytes(buffer.Length);
                                    if (dataReceived.Contains("UPDATED"))
                                    {
                                        Authed  = true;
                                        Authing = false;
                                    }
                                    else
                                    {
                                        // Bad sequence sent, close connection
                                        AuthStep = 0;         // Deny
                                        Authing  = false;
                                        Authed   = false;
                                        clientConnection.Close();
                                        ClientHandler.Slaves[clientListNumber].Authorized   = false;
                                        ClientHandler.Slaves[clientListNumber].OnlineStatus = OnlineInfo.Unknown;
                                        if (ClientConfig.Debug)
                                        {
                                            Logger.SaveDebug($"Step 3 FAILED | Connection closed and list updated | ERROR UPDATING KEYS!");
                                        }
                                    }
                                }
                                else
                                {
                                    // Bad sequence sent, close connection
                                    AuthStep = 0;         // Deny
                                    Authing  = false;
                                    Authed   = false;
                                    clientConnection.Close();
                                    ClientHandler.Slaves[clientListNumber].Authorized   = false;
                                    ClientHandler.Slaves[clientListNumber].OnlineStatus = OnlineInfo.VMDenied;
                                    if (ClientConfig.Debug)
                                    {
                                        Logger.SaveDebug($"Step 3 FAILED | Connection closed and list updated");
                                    }
                                }
                                break;

                            default:
                                // Bad sequence sent, close connection
                                AuthStep = 0;         // Deny
                                Authing  = false;
                                Authed   = false;
                                clientConnection.Close();
                                ClientHandler.Slaves[clientListNumber].Authorized   = false;
                                ClientHandler.Slaves[clientListNumber].OnlineStatus = OnlineInfo.Error;
                                if (ClientConfig.Debug)
                                {
                                    Logger.SaveDebug($"Default auth switch hit, ERROR occured!");
                                }
                                break;
                            }

                            //}
                        } // Authing loop

                        Debug.WriteLine($"Auth Status processed: {Authed} | Auth sequence processing is complete");
                    }
                    else if (Authed & !Authing) // Process this after client has been authorized
                    {
                        // read response
                        //bytesRead = nwStream.Read(buffer, 0, clientConnection.ReceiveBufferSize);
                        //dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                        // Send response
                        //dataSent = null;
                        //dataSent = Encoding.ASCII.GetBytes(crypto.DefaultEncrypt("VALID"));
                        //nwStream.Write(dataSent, 0, dataSent.Length);
                        for (var x = 0; x < WorkQueue.JobQueue.Count; x++)
                        {
                            if (WorkQueue.JobQueue[x] != null)                                                                                       // Validate we haven't grabbed a junk list item
                            {
                                if (WorkQueue.JobQueue[x].ClientID == ClientHandler.Slaves[clientListNumber].ClientID & !WorkQueue.JobQueue[x].Sent) // Client has work in queue that isn't sent yet
                                {                                                                                                                    // Pending work, let's send it
                                    switch (WorkQueue.JobQueue[x].WorkType)
                                    {
                                    case WorkType.Kill:
                                    default:
                                        if (ClientConfig.Debug)
                                        {
                                            Logger.SaveDebug($"JobQueue item {x} could not be handled for client {WorkQueue.JobQueue[x].ClientID}({ClientHandler.Slaves[clientListNumber].ClientID})");
                                        }
                                        Debug.WriteLine($"JobQueue item {x} could not be handled for client {WorkQueue.JobQueue[x].ClientID}({ClientHandler.Slaves[clientListNumber].ClientID})");
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        // Unknown not authed or not failed to auth either
                        KeepAlive = false;
                    }
                }// end of keepalive loop

                ClientHandler.Slaves[clientListNumber].OnlineStatus = OnlineInfo.Offline;
                Debug.WriteLine("KEEP ALIVE OFF AND SLAVE THREAD ENDING!");
                Logger.SaveDebug("KEEP ALIVE OFF AND SLAVE THREAD ENDING!");
            }
            catch (Exception ex)
            {
                ClientHandler.Slaves[clientListNumber].OnlineStatus = OnlineInfo.Offline;
                Debug.WriteLine("ERROR! >> " + ex);
            }
        }