Esempio n. 1
0
        public Result ChangePwdGuestUser(User user, SpuContext spucontext)
        {
            try
            {
                var setup = spucontext.table_setup.FirstOrDefault();
                PrincipalContext context   = new PrincipalContext(ContextType.Domain, setup.Host, "ou=guest," + setup.Base, setup.Username, setup.Password);
                UserPrincipal    principal = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, user.UserName);
                if (principal == null)
                {
                    return(new Result()
                    {
                        result = false, Message = "Account has not found"
                    });
                }
                principal.SetPassword(DataEncryptor.Decrypt(user.Password));
                principal.Save();

                return(new Result()
                {
                    result = true
                });
            }
            catch (Exception ex)
            {
                return(new Result()
                {
                    result = false, Message = ex.Message
                });
            }
        }
Esempio n. 2
0
        private void changePassBtn_Click(object sender, RoutedEventArgs e)
        {
            warning.Text       = string.Empty;
            warning.Visibility = Visibility.Collapsed;

            if (!OldPassword.PasswordText.Equals(string.Empty) &&
                !NewPassword.PasswordText.Equals(string.Empty) &&
                !ConfirmPassword.PasswordText.Equals(string.Empty))
            {
                string plainPwd = DataEncryptor.Decrypt(viewModel.CurrentAppUser.CurrentPassword);
                if (!NewPassword.PasswordText.Equals(ConfirmPassword.PasswordText))
                {
                    ShowMessage("New password doesn't match the confirmation. Please re-enter password.");
                }
                else if (!OldPassword.PasswordText.Equals(plainPwd))
                {
                    ShowMessage("Old password doesn't match the current password. Please re-enter password.");
                }
                else if (NewPassword.PasswordText.Equals(plainPwd))
                {
                    ShowMessage("Old password is the same with new password. Please re-enter new and unique password.");
                }
                else
                {
                    viewModel.CommandParameter = NewPassword.PasswordText;
                    this.changePassBtn.SetBinding(Button.CommandProperty, new Binding("ChangeUserPasswordCommand"));
                }
            }
            else
            {
                ShowMessage("Please fill up the empty fields.");
            }
        }
Esempio n. 3
0
        //data
        private void RunDataReceiver(ClientWebSocket socket, DataTunnelInfo dInfo, Func <Guid, byte[], Task> dataReceiver)
        {
            Task.Run(async() =>
            {
                await ReceiveAsync(socket, MessageHandler, CloseHandler);
                if (socket.State == WebSocketState.Open)
                {
                    await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
                }

                log.LogInformation($"Дисконект DT");
            });

            async Task MessageHandler(byte[] encryptedData)
            {
                var data = await dEncoder.Decrypt(dInfo.Key, encryptedData);

                await using var ms = new MemoryStream(data);
                using var br       = new BinaryReader(ms);
                var guidb       = br.ReadBytes(16);
                var payloadSize = br.ReadInt32();
                var payload     = br.ReadBytes(payloadSize);

                await dataReceiver(new Guid(guidb), payload);
            }

            async Task CloseHandler()
            {
                await RemoveConnection(dInfo.TunnelId);
            }
        }
Esempio n. 4
0
        public static (int birthYear, int weight, bool isMan) GetPersonalData(string username)
        {
            lock (username)
            {
                if (File.Exists(usersFolderPath + @"/Authentifications.json"))
                {
                    string fileContent = DataEncryptor.Decrypt(File.ReadAllText(usersFolderPath + @"/Authentifications.json"), DataEncryptor.FileKey);

                    if (!String.IsNullOrEmpty(fileContent))
                    {
                        JObject json = JObject.Parse(fileContent);
                        JArray  authentifications = json.GetValue("authentifications").ToObject <JArray>();

                        foreach (JToken authToken in authentifications)
                        {
                            JObject authentification = authToken.ToObject <JObject>();

                            string usernameAuth = authentification.GetValue("username").ToString();

                            if (username == usernameAuth)
                            {
                                int  birthYear = int.Parse(authentification.GetValue("birthyear").ToString());
                                int  weight    = int.Parse(authentification.GetValue("weight").ToString());
                                bool isMan     = (authentification.GetValue("gender").ToString() == "man") ? true : false;

                                return(birthYear, weight, isMan);
                            }
                        }
                    }
                }
                return(0, 0, true);
            }
        }
        public IActionResult Update(int?id)
        {
            if (!_loginServices.isInAdminRoles(this.GetRoles()))
            {
                return(RedirectToAction("Login", "Accounts"));
            }
            var model = this._context.Merchants
                        .Include(i => i.User)
                        .Where(w => w.MerchantID == id).FirstOrDefault();

            if (model == null)
            {
                return(RedirectToAction("Index"));
            }

            if (model.User != null)
            {
                model.UserName = model.User.UserName;
                model.Password = DataEncryptor.Decrypt(model.User.Password);
            }

            ViewBag.ListType      = this._context.MerchantCategories.Where(w => w.Status == StatusType.Active).OrderBy(o => o.Index);
            ViewBag.ListProvinces = this._context.Provinces.OrderBy(b => b.ProvinceName);
            return(View("MerchantInfo", model));
        }
        private async Task AskForPassword(int count = 0)
        {
            if (string.IsNullOrEmpty(Password))
            {
                var res = await _jsRuntime.InvokeAsync <string>("prompt",
                                                                "Enter passphrase to decrypt secure web storage.");

                if (!string.IsNullOrEmpty(res))
                {
                    var lsRes = await GetRaw($"{KeyPrefix}passwordtest");

                    if (string.IsNullOrEmpty(lsRes))
                    {
                        Password = res;
                        await Set($"passwordtest", "passwordtest");

                        var decryptTest = await Get <string>("passwordtest");

                        await _jsRuntime.InvokeVoidAsync("alert",
                                                         $"saved key test and decoded it correctly: {(decryptTest == "passwordtest")}");
                    }
                    else if (DataEncryptor.Decrypt(lsRes, res) != "\"passwordtest\"")
                    {
                        await _jsRuntime.InvokeVoidAsync("alert", $"Invalid password.");
                        await AskForPassword(count + 1);
                    }
                    else
                    {
                        Password = res;
                    }
                }
            }
        }
Esempio n. 7
0
        public static ÄstrandTest GetAstrandTestData(string filename)
        {
            lock (filename)
            {
                if (File.Exists(testsFolderPath + @"/" + filename + ".json"))
                {
                    string fileContent = DataEncryptor.Decrypt(File.ReadAllText(testsFolderPath + @"/" + filename + ".json"), DataEncryptor.FileKey);

                    if (!String.IsNullOrEmpty(fileContent))
                    {
                        try
                        {
                            ÄstrandTest astrandTest = new ÄstrandTest();

                            JObject historydataJson = JObject.Parse(fileContent);

                            JObject personalData = historydataJson.GetValue("personaldata").ToObject <JObject>();
                            astrandTest.Username  = personalData.GetValue("name").ToString();
                            astrandTest.BirthYear = int.Parse(personalData.GetValue("birthyear").ToString());
                            astrandTest.Weight    = int.Parse(personalData.GetValue("weight").ToString());
                            astrandTest.IsMan     = (personalData.GetValue("gender").ToString() == "man") ? true : false;

                            JObject testResultData = historydataJson.GetValue("testresult").ToObject <JObject>();
                            astrandTest.HasSteadyState = testResultData.GetValue("hassteadystate").ToObject <bool>();
                            astrandTest.VO2            = double.Parse(testResultData.GetValue("vo2").ToString());

                            JArray heartratesJson   = historydataJson.GetValue("heartrates").ToObject <JArray>();
                            JArray distancesJson    = historydataJson.GetValue("distances").ToObject <JArray>();
                            JArray speedsJson       = historydataJson.GetValue("speeds").ToObject <JArray>();
                            JArray cycleRhythmsJson = historydataJson.GetValue("cyclerhythms").ToObject <JArray>();

                            foreach (JObject heartrateJson in heartratesJson)
                            {
                                astrandTest.HeartrateValues.Add((int.Parse(heartrateJson.GetValue("heartrate").ToString()), DateTime.Parse(heartrateJson.GetValue("time").ToString())));
                            }

                            foreach (JObject distanceJson in distancesJson)
                            {
                                astrandTest.DistanceValues.Add((int.Parse(distanceJson.GetValue("distance").ToString()), DateTime.Parse(distanceJson.GetValue("time").ToString())));
                            }

                            foreach (JObject speedJson in speedsJson)
                            {
                                astrandTest.SpeedValues.Add((int.Parse(speedJson.GetValue("speed").ToString()), DateTime.Parse(speedJson.GetValue("time").ToString())));
                            }

                            foreach (JObject cycleRhythmJson in cycleRhythmsJson)
                            {
                                astrandTest.CycleRhythmValues.Add((int.Parse(cycleRhythmJson.GetValue("cyclerhythm").ToString()), DateTime.Parse(cycleRhythmJson.GetValue("time").ToString())));
                            }

                            return(astrandTest);
                        }
                        catch (Exception e) { }
                    }
                }
                return(null);
            }
        }
    public void recv(IAsyncResult res)
    {
        IPEndPoint ep = new IPEndPoint(IPAddress.Any, _port);

        byte[] received = _client.EndReceive(res, ref ep);

        _receiving = true;
        Message.Update(DataEncryptor.Decrypt(Encoding.UTF8.GetString(received), _decryptKey));

        _client.BeginReceive(new AsyncCallback(recv), null);
    }
Esempio n. 9
0
        public void EncryptionTest()
        {
            //Declare
            string data = "testString123";

            //Action
            string protectedData   = DataEncryptor.Encrypt(data);
            string unprotectedData = DataEncryptor.Decrypt(protectedData);

            //Assert
            Assert.AreEqual(data, unprotectedData);
            Assert.AreNotEqual(data, protectedData);
        }
Esempio n. 10
0
    /// <summary>
    /// Decrypts the wallet asynchronously.
    /// </summary>
    /// <param name="hashes"> Different hash levels used for multi level encryption of the wallet seed. </param>
    /// <param name="encryptedSeed"> The encrypted seed of the wallet. </param>
    /// <param name="password"> The user's password to the wallet. </param>
    /// <param name="onWalletDecrypted"> Action called once the wallet has been decrypted, passing the <see langword="byte"/>[] seed of the wallet. </param>
    private void AsyncDecryptWallet(
        string[] hashes,
        string encryptedSeed,
        byte[] password,
        Action <byte[]> onWalletDecrypted)
    {
        byte[] derivedPassword = playerPrefPassword.Restore(password);
        byte[] decryptedSeed   = null;

        using (var dataEncryptor = new DataEncryptor(new AdvancedSecureRandom(new Blake2bDigest(512), derivedPassword)))
        {
            byte[] hash1 = dataEncryptor.Decrypt(hashes[0].GetBase64Bytes());
            byte[] hash2 = dataEncryptor.Decrypt(hashes[1].GetBase64Bytes());

            decryptedSeed = dataEncryptor.Decrypt(dataEncryptor.Decrypt(encryptedSeed, hash2), hash1).HexToByteArray();

            password.ClearBytes();
            hash1.ClearBytes();
            hash2.ClearBytes();
        }

        onWalletDecrypted?.Invoke(decryptedSeed);
    }
        public JiraSettings Get()
        {
            JiraSettings result = null;

            if (_applicationStorageFolder.FileExists(JiraSettingsFileName))
            {
                byte[]        encryptedBytes = _applicationStorageFolder.GetBytes(JiraSettingsFileName);
                EncryptedData encryptedData  = _binarySerializer.Deserialize <EncryptedData, EncryptedDataProtobufContract>(encryptedBytes);

                byte[] decryptedData = _dataEncryptor.Decrypt(encryptedData);
                result = _binarySerializer.Deserialize <JiraSettings, JiraSettingsProtobufContract>(decryptedData);
            }

            return(result);
        }
        public override async Task <T> Get <T>(string key)
        {
            await AskForPassword();

            var lsRes = await GetRaw($"{KeyPrefix}{key}");

            if (lsRes is null)
            {
                return(default(T));
            }

            var decrypted = DataEncryptor.Decrypt(lsRes, Password);

            return(JsonSerializer.Deserialize <T>(decrypted));
        }
Esempio n. 13
0
        public IActionResult ResetPwdO(ResetPwdDTO model)
        {
            if (!_loginServices.isInAdminRoles(this.GetRoles()))
            {
                return(RedirectToAction("Login", "Accounts"));
            }

            if (ModelState.IsValid)
            {
                try
                {
                    var user = this._context.Users.Where(w => w.ID == model.ID).FirstOrDefault();
                    if (model.oldpassword == model.password)
                    {
                        ModelState.AddModelError("oldpassword", "รหัสผ่านใหม่เหมือนกับรหัสผ่านเดิม");
                        ModelState.AddModelError("password", "รหัสผ่านใหม่เหมือนกับรหัสผ่านเดิม");
                    }
                    if (model.oldpassword != DataEncryptor.Decrypt(user.Password))
                    {
                        ModelState.AddModelError("oldpassword", "รหัสผ่านเดิมไม่ถูกต้อง");
                    }
                    if (ModelState.IsValid)
                    {
                        if (!string.IsNullOrEmpty(model.password))
                        {
                            user.Password  = DataEncryptor.Encrypt(model.password);
                            user.Update_On = DateUtil.Now();
                            user.Update_By = this.HttpContext.User.Identity.Name;
                        }

                        this._context.Users.Attach(user);
                        this._context.Entry(user).Property(u => u.Password).IsModified  = true;
                        this._context.Entry(user).Property(u => u.Update_On).IsModified = true;
                        this._context.Entry(user).Property(u => u.Update_By).IsModified = true;
                        this._context.SaveChanges();

                        return(RedirectToAction("Update", new { ID = model.ID }));
                    }
                }
                catch
                {
                }
            }
            return(View(model));
        }
Esempio n. 14
0
        public static bool CheckAuthorization(string username, string password, bool isSpecialist, string cryptoKey)
        {
            if (File.Exists(filesFolderPath + @"/Authentifications.json"))
            {
                string fileContent = DataEncryptor.Decrypt(File.ReadAllText(filesFolderPath + @"/Authentifications.json"), cryptoKey);

                if (!String.IsNullOrEmpty(fileContent))
                {
                    JObject json = JObject.Parse(fileContent);
                    JArray  authentifications = json.GetValue("authentifications").ToObject <JArray>();

                    foreach (JToken authToken in authentifications)
                    {
                        JObject authentification = authToken.ToObject <JObject>();

                        string usernameAuth = authentification.GetValue("username").ToString();
                        string passwordAuth = authentification.GetValue("password").ToString();

                        if (username == usernameAuth && password == passwordAuth)
                        {
                            JToken birthYear = "";
                            authentification.TryGetValue("birthyear", out birthYear);

                            if (!isSpecialist)
                            {
                                if (birthYear == null)
                                {
                                    return(false);
                                }
                            }
                            else
                            {
                                if (birthYear != null)
                                {
                                    return(false);
                                }
                            }

                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
Esempio n. 15
0
        public static bool AddNewSpecialistAuthorization(string username, string password, string cryptoKey)
        {
            if (!Authorizer.CheckAuthorization(username, password, true, cryptoKey))
            {
                if (File.Exists(filesFolderPath + @"/Authentifications.json"))
                {
                    string fileContent = DataEncryptor.Decrypt(File.ReadAllText(filesFolderPath + @"/Authentifications.json"), cryptoKey);

                    JObject json = null;
                    JArray  authentifications = null;

                    if (!String.IsNullOrEmpty(fileContent))
                    {
                        json = JObject.Parse(fileContent);
                        authentifications = json.GetValue("authentifications").ToObject <JArray>();
                        json.Remove("authentifications");
                    }
                    else
                    {
                        authentifications = new JArray();
                        json = new JObject();
                    }

                    JObject authentification = new JObject();
                    authentification.Add("username", username);
                    authentification.Add("password", password);

                    authentifications.Add(authentification);
                    json.Add("authentifications", authentifications);

                    File.WriteAllText(filesFolderPath + @"/Authentifications.json", DataEncryptor.Encrypt(json.ToString(), cryptoKey));

                    return(true);
                }
                else
                {
                    File.WriteAllText(filesFolderPath + @"/Authentifications.json", "");
                    AddNewSpecialistAuthorization(username, password, cryptoKey);
                    return(true);
                }
            }
            return(false);
        }
        public void GivenAnInvalidPrivateKey_WhenDecryptingAString_ThenItFails()
        {
            // Given
            var privateKey = "<RSAKeyValue><Modulus>21wEnTU+mcD2w0Lfo1Gv4rtcSWsQJQTNa6gio05AOkV/Er9w3Y13Ddo5wGtjJ19402S71HUeN0vbKILLJdRSES5MHSdJPSVrOqdrll/vLXxDxWs/U0UT1c8u6k/Ogx9hTtZxYwoeYqdhDblof3E75d9n2F0Zvf6iTb4cI7j6fMs=</Modulus><Exponent>AQAB</Exponent><P>/aULPE6jd5IkwtWXmReyMUhmI/nfwfkQSyl7tsg2PKdpcxk4mpPZUdEQhHQLvE84w2DhTyYkPHCtq/mMKE3MHw==</P><Q>3WV46X9Arg2l9cxb67KVlNVXyCqc/w+LWt/tbhLJvV2xCF/0rWKPsBJ9MC6cquaqNPxWWEav8RAVbmmGrJt51Q==</Q><DP>8TuZFgBMpBoQcGUoS2goB4st6aVq1FcG0hVgHhUI0GMAfYFNPmbDV3cY2IBt8Oj/uYJYhyhlaj5YTqmGTYbATQ==</DP><DQ>FIoVbZQgrAUYIHWVEYi/187zFd7eMct/Yi7kGBImJStMATrluDAspGkStCWe4zwDDmdam1XzfKnBUzz3AYxrAQ==</DQ><InverseQ>QPU3Tmt8nznSgYZ+5jUo9E0SfjiTu435ihANiHqqjasaUNvOHKumqzuBZ8NRtkUhS6dsOEb8A2ODvy7KswUxyA==</InverseQ><D>cgoRoAUpSVfHMdYXW9nA3dfX75dIamZnwPtFHq80ttagbIe4ToYYCcyUz5NElhiNQSESgS5uCgNWqWXt5PnPu4XmCXx6utco1UVH8HGLahzbAnSy6Cj3iUIQ7Gj+9gQ7PkC434HTtHazmxVgIR5l56ZjoQ8yGNCPZnsdYEmhJWk=</D></RSAKeyValue>";
            var publicKey  = "<RSAKeyValue><Modulus>31wEnTU+mcD2w0Lfo1Gv4rtcSWsQJQTNa6gio05AOkV/Er9w3Y13Ddo5wGtjJ19402S71HUeN0vbKILLJdRSES5MHSdJPSVrOqdrll/vLXxDxWs/U0UT1c8u6k/Ogx9hTtZxYwoeYqdhDblof3E75d9n2F0Zvf6iTb4cI7j6fMs=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";


            var message = "12345678123456748";

            var realDataDecryptor = new DataEncryptor(publicKey, privateKey);

            // When

            var encryptedMessage = realDataDecryptor.Encrypt(message);

            var exception = Assert.Throws <CryptographicException>(() => realDataDecryptor.Decrypt(encryptedMessage));

            // Then

            exception.Should().BeOfType <CryptographicException>();
        }
Esempio n. 17
0
        public static bool AddNewClientAuthorization(string username, string password, int birthYear, int weight, bool isMan, string cryptoKey)
        {
            if (!Authorizer.CheckAuthorization(username, password, false, cryptoKey))
            {
                if (File.Exists(filesFolderPath + @"/Authentifications.json"))
                {
                    string fileContent = DataEncryptor.Decrypt(File.ReadAllText(filesFolderPath + @"/Authentifications.json"), cryptoKey);

                    JObject json = null;
                    JArray  authentifications = null;

                    if (!String.IsNullOrEmpty(fileContent))
                    {
                        json = JObject.Parse(fileContent);
                        authentifications = json.GetValue("authentifications").ToObject <JArray>();
                        json.Remove("authentifications");
                    }
                    else
                    {
                        authentifications = new JArray();
                        json = new JObject();
                    }

                    JObject authentification = new JObject();
                    authentification.Add("username", username);
                    authentification.Add("password", password);
                    authentification.Add("birthyear", birthYear);
                    authentification.Add("weight", weight);
                    authentification.Add("gender", (isMan) ? "man" : "woman");

                    authentifications.Add(authentification);
                    json.Add("authentifications", authentifications);

                    File.WriteAllText(filesFolderPath + @"/Authentifications.json", DataEncryptor.Encrypt(json.ToString(), cryptoKey));

                    return(true);
                }
            }
            return(false);
        }
Esempio n. 18
0
        private async Task HandleDataMessage(byte[] encryptedData, DataConnectionInfo connectionInfo)
        {
            var data = await dEncoder.Decrypt(connectionInfo.aes, encryptedData);

            var ms = new MemoryStream(data);

            using var br = new BinaryReader(ms);

            var socketId    = new Guid(br.ReadBytes(16));
            var payloadSize = br.ReadInt32();
            var payload     = br.ReadBytes(payloadSize);


            if (socketId == Guid.Empty)
            {
                await EchoProcessing(connectionInfo, payload);
            }
            else
            {
                await SocketProcessing(socketId, payload);
            }
        }
Esempio n. 19
0
        public object login(string username, string password)
        {
            var user = _context.Users.Where(w => w.UserName == username).FirstOrDefault();

            if (user == null)
            {
                return(CreatedAtAction(nameof(login), new { result = ResultCode.WrongAccountorPassword, message = ResultMessage.WrongAccountorPassword }));
            }

            var dpassword = DataEncryptor.Decrypt(user.Password);

            if (password == dpassword)
            {
                var token = CreateToken(user);
                var staff = _context.Staffs.Where(w => w.UserID == user.ID);

                if (staff.FirstOrDefault() == null)
                {
                    return(CreatedAtAction(nameof(login), new { result = ResultCode.DataHasNotFound, message = ResultMessage.DataHasNotFound }));
                }

                if (staff.FirstOrDefault().Status == StatusType.InActive)
                {
                    return(CreatedAtAction(nameof(login), new { result = ResultCode.InactiveAccount, message = ResultMessage.InactiveAccount }));
                }

                var s = staff.Select(s => new
                {
                    username             = s.User.UserName,
                    id                   = s.UserID,
                    staffid              = s.ID,
                    firstname            = s.FirstName,
                    lastname             = s.LastName,
                    profileImg           = "",
                    isAdmin              = s.isAdmin,
                    isMasterAdmin        = s.isMasterAdmin,
                    isQuestionAppr       = s.isQuestionAppr,
                    isMasterQuestionAppr = s.isMasterQuestionAppr,
                    isTestAppr           = s.isTestAppr,
                    isMasterTestAppr     = s.isMasterTestAppr,
                }).FirstOrDefault();

                if (s == null)
                {
                    return(CreatedAtAction(nameof(login), new { result = ResultCode.DataHasNotFound, message = ResultMessage.DataHasNotFound }));
                }

                var log = new LoginStaffHistory();
                log.StaffID   = s.staffid;
                log.UserID    = s.id;
                log.AuthType  = AuthType.Login;
                log.Create_On = DateUtil.Now();
                log.Create_By = s.username;
                log.Update_On = DateUtil.Now();
                log.Update_By = s.username;
                _context.LoginStaffHistorys.Add(log);


                _context.SaveChanges();
                return(CreatedAtAction(nameof(login), new { result = ResultCode.Success, message = ResultMessage.Success, token = token, user = s }));
            }
            return(CreatedAtAction(nameof(login), new { result = ResultCode.WrongAccountorPassword, message = ResultMessage.WrongAccountorPassword }));
        }
Esempio n. 20
0
        public async Task <IActionResult> Register(CustomerDTO model, bool repair = false)
        {
            if (ModelState.IsValid)
            {
                if (!repair)
                {
                    if (string.IsNullOrEmpty(model.username))
                    {
                        model.username = model.email;
                    }
                    if (!model.isDhiMember)
                    {
                        model.citizenId = null;
                    }
                    if (this.isExistIDCard(model))
                    {
                        var rg = new RijndaelCrypt();

                        model.ShowIdcardDupPopup = true;
                        var ducus = this._context.Customers.Include(i => i.User).Where(c => c.IDCard == model.citizenId & (model.ID > 0 ? c.ID != model.ID : true));
                        model.dupEmail = new List <string>();
                        model.dupFBID  = new List <string>();
                        foreach (var cus in ducus)
                        {
                            if (string.IsNullOrEmpty(cus.FacebookID))
                            {
                                model.dupEmail.Add(cus.User.UserName);
                            }
                            else
                            {
                                model.dupFBID.Add(cus.User.UserName);
                            }

                            model.dupIdcard = model.citizenId;
                        }
                        ModelState.AddModelError("citizenId", "รหัสบัตรประชาชนซ้ำในระบบ");
                    }
                    if (this.isExistEmail(model))
                    {
                        ModelState.AddModelError("email", "อีเมลซ้ำในระบบ");
                    }
                    if (this.isExistUserName(model))
                    {
                        ModelState.AddModelError("email", "รหัสผู้ใช้งานซ้ำในระบบ");
                    }
                    //if (this.isExistMobileNo(model))
                    //   ModelState.AddModelError("moblieNo", "เบอร์โทรศัพท์ซ้ำในระบบ");
                    //if (this.isExistName(model))
                    //{
                    //   ModelState.AddModelError("firstName", "ชื่อนามสกุลซ้ำในระบบ");
                    //   ModelState.AddModelError("lastName", "ชื่อนามสกุลซ้ำในระบบ");
                    //}
                    if (!string.IsNullOrEmpty(model.friendCode) && !this.isExistFriendCode(model))
                    {
                        ModelState.AddModelError("friendCode", "ไม่พบข้อมูล friend Code");
                    }
                }

                if (ModelState.IsValid)
                {
                    if (model.valid)
                    {
                        model.password = DataEncryptor.Decrypt(model.pEncyprt);
                        var customer = new Customer();
                        customer.Create_On     = DateUtil.Now();
                        customer.ChannelUpdate = CustomerChanal.TIP;
                        customer = CustomerBinding.Binding(customer, model);

                        GetCustomerClass(customer);
                        customer.Create_On = DateUtil.Now();
                        customer.Create_By = customer.User.UserName;
                        customer.Update_On = DateUtil.Now();
                        customer.Update_By = customer.User.UserName;
                        customer.Success   = false;
                        var regs = this.GetPointCondition(customer, TransacionTypeID.Register);
                        foreach (var item in regs)
                        {
                            if (item.Point.Value > 0)
                            {
                                var point = this.GetCustomerPoint(item, customer, item.Point.Value, (int)TransacionTypeID.Register, CustomerChanal.TIP, "tipsociety-register");
                                customer.CustomerPoints.Add(point);
                            }
                        }
                        var      friendpoint = 0;
                        Customer friend      = null;
                        if (!string.IsNullOrEmpty(customer.FriendCode))
                        {
                            var invites = this.GetPointCondition(customer, TransacionTypeID.InviteFriend);
                            foreach (var item in invites)
                            {
                                var p = this.GetPoint(item, customer);
                                if (p > 0)
                                {
                                    var point = this.GetCustomerPoint(item, customer, p, (int)TransacionTypeID.InviteFriend, CustomerChanal.TIP, "tipsociety-register");
                                    friend = this._context.Customers.Where(w => w.RefCode == customer.FriendCode).FirstOrDefault();
                                    if (friend != null)
                                    {
                                        friendpoint      = p;
                                        point.CustomerID = friend.ID;
                                        this._context.CustomerPoints.Add(point);
                                    }
                                }
                            }
                        }
                        this._context.Customers.Add(customer);
                        this._context.SaveChanges();
                        this._context.Entry(customer).GetDatabaseValues();
                        customer.RefCode = CustomerBinding.GetRefCode(customer);
                        this._context.Users.Attach(customer.User);
                        this._context.Entry(customer.User).Property(u => u.Email).IsModified       = true;
                        this._context.Entry(customer.User).Property(u => u.PhoneNumber).IsModified = true;
                        this._context.Update(customer);
                        this._context.SaveChanges();

                        AddConsent(model);

                        if (_conf.SendEmail == true && friend != null && friendpoint > 0)
                        {
                            await MailInviteFriend(friend.Email, friend, customer, friendpoint);
                        }
                        try
                        {
                            if (!repair)
                            {
                                using (var client = new HttpClient())
                                {
                                    client.BaseAddress = new Uri(_mobile.Url + "/rewardpoint/customerprofile/register");
                                    client.DefaultRequestHeaders.Accept.Clear();
                                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                                    var rg = new RijndaelCrypt();
                                    model.username = rg.Encrypt(model.username);
                                    model.password = rg.Encrypt(model.password);
                                    model.status   = customer.Status.toStatusNameEn();

                                    StringContent content = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json");

                                    HttpResponseMessage response = await client.PostAsync(client.BaseAddress, content);

                                    if (response.IsSuccessStatusCode && response.StatusCode == HttpStatusCode.OK)
                                    {
                                        customer.Success = true;
                                        this._context.SaveChanges();
                                    }
                                    else
                                    {
                                        _logger.LogWarning(JsonConvert.SerializeObject(model));
                                        _logger.LogWarning(await response.Content.ReadAsStringAsync());
                                    }
                                }
                            }
                        }
                        catch
                        {
                        }
                        if (_conf.SendEmail == true)
                        {
                            await MailActivateAcc(customer.Email, customer.ID);
                        }

                        //if (_conf.SendSMS == true)
                        //   SendSMS(customer.ID);

                        return(await Login(new Login()
                        {
                            UserName = model.email, Password = model.password
                        }, true));
                    }
                    else
                    {
                        model.pEncyprt = DataEncryptor.Encrypt(model.password);
                    }
                    model.valid = true;
                }
            }
            return(View(model));
        }
Esempio n. 21
0
        public async Task <IActionResult> Terminate(string code)
        {
            var acccode = this._context.AccountCodes.Where(w => w.Code == code && w.Status == StatusType.Active).FirstOrDefault();

            if (acccode != null)
            {
                var customer = _context.Customers.Where(w => w.ID == acccode.CustomerID).FirstOrDefault();
                if (customer != null)
                {
                    var redeems     = this._context.Redeems.Where(w => w.CustomerID == customer.ID);
                    var mobile      = this._context.MobilePoints.Where(w => w.CustomerID == customer.ID);
                    var classchages = this._context.CustomerClassChanges.Where(w => w.CustomerID == customer.ID);
                    var adjusts     = this._context.PointAdjusts.Where(w => w.CustomerID == customer.ID);
                    var points      = this._context.CustomerPoints.Where(w => w.CustomerID == customer.ID);

                    var tempcus = JsonConvert.SerializeObject(customer, new JsonSerializerSettings()
                    {
                        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                    });
                    var tcus = new TerminateCustomer();
                    tcus            = JsonConvert.DeserializeObject <TerminateCustomer>(tempcus);
                    tcus.ID         = 0;
                    tcus.CustomerID = customer.ID;
                    this._context.TerminateCustomers.Add(tcus);

                    foreach (var item in redeems)
                    {
                        var temp = JsonConvert.SerializeObject(item, new JsonSerializerSettings()
                        {
                            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                        });
                        var t = new TerminateRedeem();
                        t    = JsonConvert.DeserializeObject <TerminateRedeem>(temp);
                        t.ID = 0;
                        this._context.TerminateRedeems.Add(t);
                    }
                    foreach (var item in points)
                    {
                        var temp = JsonConvert.SerializeObject(item, new JsonSerializerSettings()
                        {
                            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                        });
                        var t = new TerminateCustomerPoint();
                        t    = JsonConvert.DeserializeObject <TerminateCustomerPoint>(temp);
                        t.ID = 0;
                        this._context.TerminateCustomerPoints.Add(t);
                    }
                    foreach (var item in mobile)
                    {
                        var temp = JsonConvert.SerializeObject(item, new JsonSerializerSettings()
                        {
                            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                        });
                        var t = new TerminateMobilePoint();
                        t    = JsonConvert.DeserializeObject <TerminateMobilePoint>(temp);
                        t.ID = 0;
                        this._context.TerminateMobilePoints.Add(t);
                    }
                    foreach (var item in classchages)
                    {
                        var temp = JsonConvert.SerializeObject(item, new JsonSerializerSettings()
                        {
                            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                        });
                        var t = new TerminateCustomerClassChange();
                        t    = JsonConvert.DeserializeObject <TerminateCustomerClassChange>(temp);
                        t.ID = 0;
                        this._context.TerminateCustomerClassChanges.Add(t);
                    }
                    foreach (var item in adjusts)
                    {
                        var temp = JsonConvert.SerializeObject(item, new JsonSerializerSettings()
                        {
                            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                        });
                        var t = new TerminatePointAdjust();
                        t    = JsonConvert.DeserializeObject <TerminatePointAdjust>(temp);
                        t.ID = 0;
                        this._context.TerminatePointAdjusts.Add(t);
                    }

                    var user = this._context.Users.Where(w => w.ID == customer.UserID).FirstOrDefault();
                    if (user != null)
                    {
                        var rg   = new RijndaelCrypt();
                        var u    = rg.Encrypt(user.UserName);
                        var p    = rg.Encrypt(DataEncryptor.Decrypt(user.Password));
                        var flag = rg.Encrypt(customer.FacebookFlag);

                        var tempuser = JsonConvert.SerializeObject(user, new JsonSerializerSettings()
                        {
                            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                        });
                        var tuser = new TerminateUser();
                        tuser            = JsonConvert.DeserializeObject <TerminateUser>(tempuser);
                        tuser.ID         = 0;
                        tuser.CustomerID = customer.ID;
                        this._context.TerminateUsers.Add(tuser);

                        this._context.CustomerPoints.RemoveRange(points);
                        this._context.MobilePoints.RemoveRange(mobile);
                        this._context.CustomerClassChanges.RemoveRange(classchages);
                        this._context.PointAdjusts.RemoveRange(adjusts);
                        this._context.Redeems.RemoveRange(redeems);
                        this._context.Customers.Remove(customer);
                        this._context.Users.Remove(user);

                        acccode.Status = StatusType.InActive;
                        this._context.SaveChanges();
                        /*delete customer imobile*/
                        using (var client = new HttpClient())
                        {
                            client.BaseAddress = new Uri(_mobile.Url + "/rewardpoint/customerprofile/delete");
                            client.DefaultRequestHeaders.Accept.Clear();
                            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                            var model = new { u = u, p = p, flag = flag };

                            StringContent       content  = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json");
                            HttpResponseMessage response = await client.PostAsync(client.BaseAddress, content);

                            if (response.IsSuccessStatusCode && response.StatusCode == HttpStatusCode.OK)
                            {
                                customer.Success = true;
                                this._context.SaveChanges();
                            }
                        }
                    }
                }
            }
            this._loginServices.Logout();
            return(View());
        }
Esempio n. 22
0
        public async Task <IActionResult> Login(Login model, bool registed = false)
        {
            model.UserName = model.UserName.Trim();
            model.Password = model.Password.Trim();

            ModelState.Remove("");
            if (ModelState.IsValid)
            {
                //  Login statement here
                var user = this._context.Users.Include(u => u.UserRole).Where(u => u.UserName == model.UserName).FirstOrDefault();
                if (user == null)
                {
                    /*create customer imobile*/
                    if (user == null)
                    {
                        await this.Repair(model.UserName, model.Password, null, bcrypt : BCrypt.Net.BCrypt.HashPassword(model.Password));

                        user = this._context.Users.Include(u2 => u2.UserRole).Where(u2 => u2.UserName == model.UserName).FirstOrDefault();
                    }
                }

                if (user != null)
                {
                    if (registed)
                    {
                        if (user != null && user.Status == UserStatusType.Active)
                        {
                            this._loginServices.Login(user, model.RememberMe);
                            var customer = this._context.Customers.Where(w => w.UserID == user.ID).FirstOrDefault();
                            if (customer != null)
                            {
                                customer.FirstLogedIn = true;
                                this._context.SaveChanges();
                            }
                            return(RedirectToAction("RegisterCompleted", new { Email = model.UserName }));
                        }
                    }
                    else
                    {
                        if (user.Status != UserStatusType.InActive)
                        {
                            if (user.UserRole != null && user.UserRole.RoleName == RoleName.Member)
                            {
                                var customer = this._context.Customers.Where(w => w.UserID == user.ID).FirstOrDefault();
                                if (customer == null)
                                {
                                    ViewData["ErrorMessage"] = "ไม่พบข้อมูลผู้ใช้";
                                    return(View(model));
                                }
                                if (customer.FirstLogedIn == false && customer.Channel == CustomerChanal.TipInsure)
                                {
                                    var rg = new RijndaelCrypt();
                                    return(RedirectToAction("ResetPwd", "Accounts", new { u = rg.Encrypt(customer.User.UserName) }));
                                }
                                if (!string.IsNullOrEmpty(user.Password))
                                {
                                    string desPassword = DataEncryptor.Decrypt(user.Password);
                                    if (model.Password == desPassword)
                                    {
                                        this._loginServices.Login(user, model.RememberMe);
                                        GetCustomerClass(customer);
                                        customer.FirstLogedIn = true;
                                        var conditions = this.GetPointCondition(customer, TransacionTypeID.Login);
                                        foreach (var con in conditions)
                                        {
                                        }
                                        this._context.SaveChanges();
                                        return(RedirectToAction("Info", "Customer"));
                                    }
                                }

                                if (!string.IsNullOrEmpty(customer.BCryptPwd))
                                {
                                    string paintTextPassword = model.Password;
                                    string passworeInDB      = customer.BCryptPwd;
                                    if (!string.IsNullOrEmpty(paintTextPassword) && !string.IsNullOrEmpty(passworeInDB))
                                    {
                                        if (BCrypt.Net.BCrypt.Verify(paintTextPassword, passworeInDB))
                                        {
                                            user.Password  = DataEncryptor.Encrypt(model.Password);
                                            customer.Syned = true;
                                            this._context.Users.Update(user);
                                            this._loginServices.Login(user, model.RememberMe);
                                            GetCustomerClass(customer);
                                            customer.FirstLogedIn = true;
                                            this._context.SaveChanges();
                                            return(RedirectToAction("Info", "Customer"));
                                        }
                                    }
                                }
                            }
                            else if (user.UserRole.RoleName == RoleName.Merchant)
                            {
                                string desPassword = DataEncryptor.Decrypt(user.Password);
                                if (model.Password == desPassword)
                                {
                                    this._loginServices.Login(user, model.RememberMe);
                                    return(RedirectToAction("Index", "MerchantU"));
                                }
                            }
                            else
                            {
                                string desPassword = DataEncryptor.Decrypt(user.Password);
                                if (model.Password == desPassword)
                                {
                                    this._loginServices.Login(user, model.RememberMe);
                                    return(RedirectToAction("Index", "Admin"));
                                }
                            }
                        }
                        else
                        {
                            ViewData["ErrorMessage"] = "ถูกระงับการเป็นสมาชิก";
                            return(View(model));
                        }
                    }
                }
            }
            ViewData["ErrorMessage"] = "รหัสผู้ใช้ หรือ รหัสผ่านไม่ถูกต้อง";
            return(View(model));
        }
Esempio n. 23
0
        public async Task <IActionResult> SSO(SSODTO model)
        {
            if (string.IsNullOrEmpty(model.u))
            {
                model.u = model.UserName;
            }
            if (string.IsNullOrEmpty(model.p))
            {
                model.p = model.Password;
            }
            if (string.IsNullOrEmpty(model.p))
            {
                model.p = model.u;
            }
            if (!string.IsNullOrEmpty(model.u) && !string.IsNullOrEmpty(model.p))
            {
                var rg = new RijndaelCrypt();
                var u  = rg.Decrypt(model.u);
                var p  = rg.Decrypt(model.p);
                var f  = "";
                if (!string.IsNullOrEmpty(model.f))
                {
                    f = rg.Decrypt(model.f);
                }
                if (!string.IsNullOrEmpty(model.facebookFlag))
                {
                    f = model.facebookFlag;
                }
                var user = this._context.Users.Include(w => w.UserRole).Where(w => w.UserName == u).FirstOrDefault();
                /*create customer imobile*/

                _logger.LogWarning(DateUtil.Now() + "");
                _logger.LogWarning("SSO");
                _logger.LogWarning(JsonConvert.SerializeObject(model));
                model.u = u;

                if (user == null)
                {
                    await this.Repair(u, p, f, "loginForStatus");

                    user = this._context.Users.Include(u2 => u2.UserRole).Where(u2 => u2.UserName == u).FirstOrDefault();
                }

                if (user != null)
                {
                    if (user.Status != UserStatusType.InActive)
                    {
                        var customer = this._context.Customers.Where(w => w.UserID == user.ID).FirstOrDefault();
                        if (customer == null)
                        {
                            ViewData["ErrorMessage"] = "ไม่พบข้อมูลผู้ใช้";
                            _logger.LogWarning(ViewData["ErrorMessage"].ToString());
                            return(RedirectToAction("Login", "Accounts", new { message = ViewData["ErrorMessage"] }));
                        }
                        f = customer.FacebookFlag;
                        var valid = false;
                        if (!string.IsNullOrEmpty(f) && f.ToLower() == "y")
                        {
                            valid = true;
                        }
                        else
                        {
                            if (customer.BCryptPwd == p)
                            {
                                valid = true;
                            }

                            if (!valid)
                            {
                                if (!string.IsNullOrEmpty(user.Password))
                                {
                                    string paintTextPassword = DataEncryptor.Decrypt(user.Password);
                                    string passworeInDB      = p;
                                    if (!valid)
                                    {
                                        if (!string.IsNullOrEmpty(paintTextPassword) && !string.IsNullOrEmpty(passworeInDB))
                                        {
                                            try
                                            {
                                                if (BCrypt.Net.BCrypt.Verify(paintTextPassword, passworeInDB))
                                                {
                                                    valid = true;
                                                }
                                            }
                                            catch
                                            {
                                            }
                                        }
                                    }
                                }
                            }

                            if (!valid)
                            {
                                if (!string.IsNullOrEmpty(user.Password))
                                {
                                    string desPassword = DataEncryptor.Decrypt(user.Password);
                                    if (p == desPassword)
                                    {
                                        valid = true;
                                    }
                                }
                            }
                        }


                        if (valid)
                        {
                            this._loginServices.Login(user, true);
                            GetCustomerClass(customer);
                            customer.FirstLogedIn = true;
                            this._context.SaveChanges();

                            return(RedirectToAction("Privilege", "Home", new { /*poppromo = 1 */ }));
                        }
                    }
                    else
                    {
                        ViewData["ErrorMessage"] = "ถูกระงับการเป็นสมาชิก";
                        _logger.LogWarning(ViewData["ErrorMessage"].ToString());
                        return(RedirectToAction("Login", "Accounts", new { message = ViewData["ErrorMessage"] }));
                    }
                }
            }
            ViewData["ErrorMessage"] = "รหัสผู้ใช้ หรือ รหัสผ่านไม่ถูกต้อง";
            _logger.LogWarning(ViewData["ErrorMessage"].ToString());
            return(RedirectToAction("Login", "Accounts", new { message = ViewData["ErrorMessage"] }));
        }
Esempio n. 24
0
        public IActionResult ResetPassword(ChangePassword2DTO model)
        {
            visual_fim_user fim_user = null;

            try
            {
                fim_user = this._context.table_visual_fim_user.Where(w => w.basic_uid == DataEncryptor.Decrypt(model.Code)).FirstOrDefault();
                if (fim_user == null)
                {
                    return(RedirectToAction("Logout", "Auth"));
                }
            }
            catch (Exception ex)
            {
                return(RedirectToAction("Logout", "Auth"));
            }

            if (ModelState.IsValid)
            {
                var msg  = ReturnMessage.ChangePasswordFail;
                var code = ReturnCode.Error;
                ViewBag.Message    = msg;
                ViewBag.ReturnCode = code;
                try
                {
                    fim_user.basic_userPassword = Cryptography.encrypt(model.Password);
                    fim_user.cu_pwdchangeddate  = DateUtil.Now();
                    fim_user.cu_pwdchangedby    = fim_user.basic_uid;
                    fim_user.cu_pwdchangedloc   = getClientIP();
                    fim_user.system_actived     = true;
                    _context.SaveChanges();
                    var result_ldap = _providerldap.ChangePwd(fim_user, model.Password, _context);
                    if (result_ldap.result == true)
                    {
                        writelog(LogType.log_reset_password, LogStatus.successfully, IDMSource.LDAP, fim_user.basic_uid);
                    }
                    else
                    {
                        writelog(LogType.log_reset_password, LogStatus.failed, IDMSource.LDAP, fim_user.basic_uid, log_exception: result_ldap.Message);
                    }

                    var result_ad = _provider.ChangePwd(fim_user, model.Password, _context);
                    if (result_ad.result == true)
                    {
                        writelog(LogType.log_reset_password, LogStatus.successfully, IDMSource.AD, fim_user.basic_uid);
                    }
                    else
                    {
                        writelog(LogType.log_reset_password, LogStatus.failed, IDMSource.AD, fim_user.basic_uid, log_exception: result_ad.Message);
                    }

                    writelog(LogType.log_reset_password, LogStatus.successfully, IDMSource.VisualFim, fim_user.basic_uid);

                    msg                = ReturnMessage.ChangePasswordSuccess;
                    code               = ReturnCode.Success;
                    ViewBag.Message    = msg;
                    ViewBag.ReturnCode = code;
                    return(RedirectToAction("ResetPasswordCompleted", new { code = code, msg = msg }));
                }
                catch (Exception ex)
                {
                    writelog(LogType.log_reset_password, LogStatus.failed, IDMSource.VisualFim, fim_user.basic_uid, log_exception: ex.Message);
                }
            }
            return(View(model));
        }
 public void OnDataReceived(byte[] data)
 {
     byte[] decryptedData = DataEncryptor.Decrypt(data, "Test");
     this.receiver?.OnMessageReceived(Message.ParseMessage(decryptedData));
 }
Esempio n. 26
0
        public object loginstudent(string username, string password)
        {
            var user = _context.Users.Where(w => w.UserName == username).FirstOrDefault();

            if (user == null)
            {
                return(CreatedAtAction(nameof(login), new { result = ResultCode.WrongAccountorPassword, message = ResultMessage.WrongAccountorPassword }));
            }

            var dpassword = DataEncryptor.Decrypt(user.Password);

            if (password == dpassword)
            {
                var token   = CreateToken(user);
                var student = _context.Students.Where(w => w.UserID == user.ID & w.Status == StatusType.Active).Select(s => new
                {
                    username    = s.User.UserName,
                    id          = s.UserID,
                    studentid   = s.ID,
                    studentcode = s.StudentCode,
                    course      = s.Course,
                    prefix      = s.Prefix.toPrefixName(),
                    firstname   = s.FirstName,
                    lastname    = s.LastName,
                    idcard      = s.IDCard,
                    profileImg  = "",
                }).FirstOrDefault();

                if (student == null)
                {
                    return(CreatedAtAction(nameof(loginstudent), new { result = ResultCode.DataHasNotFound, message = ResultMessage.DataHasNotFound }));
                }


                var log = new LoginStudentHistory();
                log.StudentID = student.studentid;
                log.UserID    = student.id;
                log.AuthType  = AuthType.Login;
                log.Create_On = DateUtil.Now();
                log.Create_By = student.username;
                log.Update_On = DateUtil.Now();
                log.Update_By = student.username;
                _context.LoginStudentHistorys.Add(log);

                var tokens = _context.LoginTokens.Where(w => w.StudentID == student.studentid);
                if (tokens.Count() > 0)
                {
                    _context.LoginTokens.RemoveRange(tokens);
                }

                var tok = new LoginToken();
                tok.StudentID  = student.studentid;
                tok.UserID     = student.id;
                tok.Token      = token;
                tok.Create_On  = DateUtil.Now();
                tok.Create_By  = student.username;
                tok.Update_On  = DateUtil.Now();
                tok.Update_By  = student.username;
                tok.ExpiryDate = DateUtil.Now().AddHours(8);
                _context.LoginTokens.Add(tok);
                _context.SaveChanges();

                return(CreatedAtAction(nameof(loginstudent), new { result = ResultCode.Success, message = ResultMessage.Success, token = token, user = student }));
            }
            return(CreatedAtAction(nameof(loginstudent), new { result = ResultCode.WrongAccountorPassword, message = ResultMessage.WrongAccountorPassword }));
        }