Пример #1
0
    /// <summary>
    /// Encrypts the wallet data asynchronously.
    /// </summary>
    /// <param name="seed"> The <see langword="byte"/>[] seed to encrypt. </param>
    /// <param name="password"> The base password to use for encryption, retrieved from the user input. </param>
    /// <param name="onWalletEncrypted"> Action called once the wallet has been encrypted. </param>
    private void AsyncEncryptWallet(
        byte[] seed,
        byte[] password,
        Action <string[], string, string> onWalletEncrypted)
    {
        string[] encryptedHashes    = null;
        string   saltedPasswordHash = null;
        string   encryptedSeed      = null;

        byte[] derivedPassword = playerPrefPassword.Derive(password);

        using (var dataEncryptor = new DataEncryptor(new AdvancedSecureRandom(new Blake2bDigest(512), derivedPassword)))
        {
            byte[] hash1 = RandomBytes.Secure.Blake2.GetBytes(512);
            byte[] hash2 = RandomBytes.Secure.Blake2.GetBytes(1024);

            saltedPasswordHash = new PBKDF2PasswordHashing(new Blake2b_512_Engine()).GetSaltedPasswordHash(password).GetBase64String();
            encryptedSeed      = dataEncryptor.Encrypt(dataEncryptor.Encrypt(seed.GetHexString(), hash1), hash2);

            encryptedHashes = new string[]
            {
                dataEncryptor.Encrypt(hash1).GetBase64String(),
                dataEncryptor.Encrypt(hash2).GetBase64String()
            };

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

        dynamicDataCache.SetData("pass", new ProtectedString(password, this));
        dynamicDataCache.SetData("mnemonic", null);

        MainThreadExecutor.QueueAction(() => onWalletEncrypted?.Invoke(encryptedHashes, saltedPasswordHash, encryptedSeed));
    }
Пример #2
0
    void Update()
    {
        if (!Input.gyro.enabled)
        {
            return;
        }

        Click = _checkLimits(Input.GetMouseButton(0));

        string toSend =
            "hand=" + (dominantHand == DominantHandType.Right ? "Right" : "Left") + "/"
            + "click=" + Click + "/"
            + "r.x=" + gameObject.transform.rotation.x + "/"
            + "r.y=" + gameObject.transform.rotation.y + "/"
            + "r.z=" + gameObject.transform.rotation.z + "/"
            + "r.w=" + gameObject.transform.rotation.w;

        toSend.Replace(",", ".");
        toSend = DataEncryptor.Encrypt(toSend, EncriptKey);

        if (!ShowConfig)
        {
            _udp.send(toSend);
        }
    }
Пример #3
0
        public object resetpassword([FromBody] JsonElement json)
        {
            var model = JsonConvert.DeserializeObject <PasswordDTO>(json.GetRawText());

            if (model == null)
            {
                return(CreatedAtAction(nameof(resetpassword), new { result = ResultCode.InputHasNotFound, message = ResultMessage.InputHasNotFound }));
            }

            var student = _context.Students.Where(w => w.ID == model.id).FirstOrDefault();

            if (student != null)
            {
                var user = _context.Users.Where(w => w.ID == model.uid).FirstOrDefault();
                if (user != null)
                {
                    user.Password        = DataEncryptor.Encrypt(model.password);
                    user.ConfirmPassword = DataEncryptor.Encrypt(model.password);
                    user.Update_By       = model.update_by;
                    user.Update_On       = DateUtil.Now();
                }
                student.Update_By = model.update_by;
                student.Update_On = DateUtil.Now();
                _context.SaveChanges();
                return(CreatedAtAction(nameof(resetpassword), new { result = ResultCode.Success, message = ResultMessage.Success }));
            }
            return(CreatedAtAction(nameof(resetpassword), new { result = ResultCode.InvalidInput, message = ResultMessage.InvalidInput }));
        }
Пример #4
0
        public object update([FromBody] JsonElement json)
        {
            var model = JsonConvert.DeserializeObject <UserDTO>(json.GetRawText());

            if (model == null)
            {
                return(CreatedAtAction(nameof(update), new { result = ResultCode.InputHasNotFound, message = ResultMessage.InputHasNotFound }));
            }

            var dupid = _context.Students.Where(w => w.IDCard == model.idcard & w.ID != model.id).FirstOrDefault();

            if (dupid != null)
            {
                return(CreatedAtAction(nameof(insert), new { result = ResultCode.DuplicateData, message = "เลขประจำตัวประชาชนซ้ำ" }));
            }

            var dupscode = _context.Students.Where(w => w.StudentCode == model.studentcode & w.ID != model.id).FirstOrDefault();

            if (dupscode != null)
            {
                return(CreatedAtAction(nameof(insert), new { result = ResultCode.DuplicateData, message = "รหัสนักศึกษาซ้ำ" }));
            }

            var student = _context.Students.Where(w => w.ID == model.id).FirstOrDefault();

            if (student != null)
            {
                if (student.IDCard != model.idcard)
                {
                    var user = _context.Users.Where(w => w.ID == student.UserID).FirstOrDefault();
                    if (user != null)
                    {
                        user.UserName        = model.idcard;
                        user.Password        = DataEncryptor.Encrypt(model.idcard);
                        user.ConfirmPassword = DataEncryptor.Encrypt(model.idcard);
                        user.Update_On       = DateUtil.Now();
                        user.Update_By       = model.update_by;
                    }
                }
                student.Update_On   = DateUtil.Now();
                student.Update_By   = model.update_by;
                student.Status      = model.status.toStatus();
                student.Prefix      = model.prefix.toPrefix();
                student.Address     = model.address;
                student.FirstName   = model.firstname;
                student.LastName    = model.lastname;
                student.FirstNameEn = model.firstnameen;
                student.LastNameEn  = model.lastnameen;
                student.IDCard      = model.idcard;
                student.StudentCode = model.studentcode;
                student.Phone       = model.phone;
                student.Email       = model.email;
                student.FacultyID   = model.faculty;
                student.Course      = model.course.toCourse();
                _context.SaveChanges();
                return(CreatedAtAction(nameof(update), new { result = ResultCode.Success, message = ResultMessage.Success }));
            }
            return(CreatedAtAction(nameof(update), new { result = ResultCode.InvalidInput, message = ResultMessage.InvalidInput }));
        }
        public void Set(JiraSettings jiraSettings)
        {
            byte[]        serializedJiraSettings = _binarySerializer.Serialize <JiraSettings, JiraSettingsProtobufContract>(jiraSettings);
            EncryptedData encryptedJiraSettings  = _dataEncryptor.Encrypt(serializedJiraSettings);

            byte[] serializedEncryptedJiraSettings = _binarySerializer.Serialize <EncryptedData, EncryptedDataProtobufContract>(encryptedJiraSettings);

            _applicationStorageFolder.StoreBytes(JiraSettingsFileName, serializedEncryptedJiraSettings);
        }
        /// <summary>
        /// Ensures the base seed for all secure key generation is created.
        /// </summary>
        private void EnsureSeedCreation()
        {
            string seedName = GetSeedName();

            if (PlayerPrefs.HasKey(seedName))
            {
                return;
            }

            PlayerPrefs.SetString(seedName, dataEncryptor.Encrypt(RandomBytes.Secure.Blake2.GetBytes(128).Keccak_512().GetHexString()));
        }
Пример #7
0
        private async Task <bool> SendData(DataConnectionInfo connectionInfo, Guid socketId, byte[] data, int size)
        {
            await using var ms = new MemoryStream();
            await using var bw = new BinaryWriter(ms);
            bw.Write(socketId.ToByteArray());
            bw.Write(size);
            bw.Write(data, 0, size);
            bw.Flush();

            var encodedData = await dEncoder.Encrypt(connectionInfo.aes, connectionInfo.bufferSize, ms.ToArray());

            return(await SendData(connectionInfo, encodedData));
        }
        public override async Task Set <T>(string key, T value)
        {
            await AskForPassword();

            if (value.Equals(default(T)))
            {
                await base.Set($"{KeyPrefix}{key}", value);
            }
            else
            {
                await SetRaw($"{KeyPrefix}{key}", DataEncryptor.Encrypt(JsonSerializer.Serialize(value), Password));
            }
        }
Пример #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);
        }
Пример #10
0
        public async Task SendData(Guid tunnelId, Guid socketId, byte[] buffer, int size)
        {
            if (dataTunnelInfos.TryGetValue(tunnelId, out var tunnelInfo))
            {
                await using var ms = new MemoryStream();
                await using var bw = new BinaryWriter(ms);
                bw.Write(socketId.ToByteArray());
                bw.Write(size);
                bw.Write(buffer, 0, size);
                bw.Flush();

                var encodedData = await dEncoder.Encrypt(tunnelInfo.Key, tunnelInfo.BlockSize, ms.ToArray());

                await SendData(tunnelInfo, encodedData);
            }
        }
Пример #11
0
        public IActionResult Modify(User model)
        {
            if (!_loginServices.isInAdminRoles(this.GetRoles()))
            {
                return(RedirectToAction("Login", "Accounts"));
            }

            if (this.isExistUserName(model))
            {
                ModelState.AddModelError("UserName", "รหัสผู้ใช้ซ้ำในระบบ");
            }

            if (ModelState.IsValid)
            {
                model.Update_On = DateUtil.Now();
                model.Update_By = this.HttpContext.User.Identity.Name;
                if (model.ID <= 0)
                {
                    model.Password  = DataEncryptor.Encrypt(model.Password);
                    model.Create_On = DateUtil.Now();
                    model.Create_By = this.HttpContext.User.Identity.Name;

                    this._context.Users.Add(model);
                    this._context.SaveChanges();
                }
                else
                {
                    this._context.Users.Attach(model);
                    this._context.Entry(model).Property(u => u.Email).IsModified       = true;
                    this._context.Entry(model).Property(u => u.PhoneNumber).IsModified = true;
                    this._context.Entry(model).Property(u => u.FirstName).IsModified   = true;
                    this._context.Entry(model).Property(u => u.LastName).IsModified    = true;
                    this._context.Entry(model).Property(u => u.Status).IsModified      = true;
                    this._context.Entry(model).Property(u => u.UserName).IsModified    = true;
                    this._context.Entry(model).Property(u => u.UserRoleID).IsModified  = true;
                    this._context.Entry(model).Property(u => u.Update_By).IsModified   = true;
                    this._context.Entry(model).Property(u => u.Update_On).IsModified   = true;

                    this._context.SaveChanges();
                }
                return(RedirectToAction("Index"));
            }
            ViewBag.Roles     = this._context.UserRoles.OrderBy(r => r.UserRoleID);
            ViewBag.UserRoles = this._context.UserRoles.Where(w => w.Status == StatusType.Active).OrderBy(r => r.UserRoleID);
            return(View("UserInfo", model));
        }
Пример #12
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));
        }
        private void _SeedCustomers()
        {
            if (dbContext.Customers.Any())
            {
                return;
            }

            string newCardNumber  = "4929399657543118";
            string lastFourDigits = newCardNumber.Substring(newCardNumber.Length - 5);
            string cardNumHash    = DataEncryptor.Encrypt(newCardNumber);

            CreditCard card = new CreditCard
            {
                LastFourDigits = lastFourDigits,
                CardNumHash    = cardNumHash,
                ExpDate        = "0822",
                FirstName      = "John",
                LastName       = "Doe",
            };

            Address address = new Address
            {
                Street  = "12th Jason ave",
                City    = "Orange park",
                State   = "FL",
                Phone   = "23094587",
                ZIP     = "33312",
                Country = "United States"
            };

            Customer customer = new Customer
            {
                FirstName = "John",
                LastName  = "Doe",
                DateAdded = DateTime.Now,
            };

            customer.Addresses.Add(address);
            customer.CreditCards.Add(card);

            dbContext.Customers.Add(customer);

            saveChanges = true;
        }
Пример #14
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);
        }
Пример #15
0
 public IActionResult ActiveUser(ActivateDTO model)
 {
     if (ModelState.IsValid)
     {
         var fim_user = this._context.table_visual_fim_user.Where(w => w.cu_pplid == model.cu_pplid).FirstOrDefault();
         if (fim_user == null)
         {
             ModelState.AddModelError("cu_pplid", "ไม่พบข้อมูลรหัสบัตรประชาชนที่ระบุ");
             return(View(model));
         }
         fim_user = this._context.table_visual_fim_user.Where(w => w.cu_jobcode == model.cu_jobcode & w.cu_pplid == model.cu_pplid).FirstOrDefault();
         if (fim_user == null)
         {
             ModelState.AddModelError("cu_jobcode", "รหัสนักศึกษาไม่ถูกต้อง");
             return(View(model));
         }
         return(RedirectToAction("ResetPassword", new { u = DataEncryptor.Encrypt(fim_user.basic_uid) }));
     }
     return(View(model));
 }
        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>();
        }
Пример #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);
        }
Пример #18
0
        public object upload([FromBody] JsonElement json)
        {
            var model = JsonConvert.DeserializeObject <ImportExamRegisterDTO>(json.GetRawText());

            if (model != null && model.fileupload != null)
            {
                var file = Convert.FromBase64String(model.fileupload.value);
                using (MemoryStream ms = new MemoryStream(file))
                {
                    using (ExcelPackage package = new ExcelPackage(ms))
                    {
                        if (package.Workbook.Worksheets.Count == 0)
                        {
                            return(CreatedAtAction(nameof(upload), new { result = ResultCode.InputHasNotFound, message = ResultMessage.InputHasNotFound }));
                        }
                        else
                        {
                            var worksheet = package.Workbook.Worksheets.First();
                            int totalRows = worksheet.Dimension.End.Row;
                            for (int i = 2; i <= totalRows; i++)
                            {
                                var j           = 1;
                                var studentcode = worksheet.Cells[i, j].Text; j++;
                                var idcard      = worksheet.Cells[i, j].Text; j++;
                                var prefix      = worksheet.Cells[i, j].Text; j++;
                                var firstname   = worksheet.Cells[i, j].Text; j++;
                                var lastname    = worksheet.Cells[i, j].Text; j++;
                                var firstnameEn = worksheet.Cells[i, j].Text; j++;
                                var lastnameEn  = worksheet.Cells[i, j].Text; j++;
                                var email       = worksheet.Cells[i, j].Text; j++;
                                var phone       = worksheet.Cells[i, j].Text; j++;
                                var address     = worksheet.Cells[i, j].Text; j++;
                                var faculty     = worksheet.Cells[i, j].Text; j++;
                                var course      = worksheet.Cells[i, j].Text; j++;
                                var status      = worksheet.Cells[i, j].Text; j++;

                                var student = _context.Students.Where(w => w.StudentCode == studentcode).FirstOrDefault();
                                if (student == null)
                                {
                                    student        = new Student();
                                    student.Course = course.toCourse();
                                    student.Email  = email;
                                    var fac = _context.Facultys.Where(w => w.FacultyName == faculty).FirstOrDefault();
                                    if (fac != null)
                                    {
                                        student.FacultyID = fac.ID;
                                    }
                                    student.FirstName   = firstname;
                                    student.LastName    = lastname;
                                    student.FirstNameEn = firstnameEn;
                                    student.LastNameEn  = lastnameEn;
                                    student.Phone       = phone;
                                    student.Prefix      = prefix.toPrefix();
                                    student.StudentCode = studentcode;
                                    student.Status      = status.toStatus();
                                    student.Update_On   = DateUtil.Now();
                                    student.Create_On   = DateUtil.Now();
                                    student.Create_By   = model.update_by;
                                    student.Update_By   = model.update_by;
                                    student.Address     = address;
                                    student.IDCard      = idcard;

                                    var user = new User();
                                    user.Password  = DataEncryptor.Encrypt(studentcode);
                                    user.UserName  = studentcode;
                                    user.Update_On = DateUtil.Now();
                                    user.Create_On = DateUtil.Now();
                                    user.Create_By = model.update_by;
                                    user.Update_By = model.update_by;
                                    student.User   = user;
                                    _context.Students.Add(student);
                                }
                                else
                                {
                                    student.Course = course.toCourse();
                                    student.Email  = email;
                                    var fac = _context.Facultys.Where(w => w.FacultyName == faculty).FirstOrDefault();
                                    if (fac != null)
                                    {
                                        student.FacultyID = fac.ID;
                                    }
                                    student.FirstName   = firstname;
                                    student.LastName    = lastname;
                                    student.FirstNameEn = firstnameEn;
                                    student.LastNameEn  = lastnameEn;
                                    student.Phone       = phone;
                                    student.Prefix      = prefix.toPrefix();
                                    student.StudentCode = studentcode;
                                    student.Update_On   = DateUtil.Now();
                                    student.Update_By   = model.update_by;
                                    student.Status      = status.toStatus();
                                    student.Address     = address;
                                    student.IDCard      = idcard;
                                }
                            }
                            _context.SaveChanges();
                        }
                    }
                }
            }
            return(CreatedAtAction(nameof(upload), new { result = ResultCode.InvalidInput, message = ResultMessage.InvalidInput }));
        }
Пример #19
0
        public async Task <IActionResult> Modify(Merchant model, IFormFile file)
        {
            if (!_loginServices.isInAdminRoles(this.GetRoles()))
            {
                return(RedirectToAction("Login", "Accounts"));
            }
            var uvali = new User()
            {
                UserName = model.UserName, ID = model.UserID.HasValue ? model.UserID.Value : 0
            };

            if (this.isExistUserName(uvali))
            {
                ModelState.AddModelError("UserName", "รหัสผู้ใช้งานซ้ำในระบบ");
            }

            if (ModelState.IsValid)
            {
                var dateformat = DateUtil.ToInternalDateTime(DateUtil.Now());
                if (model.MerchantID <= 0)
                {
                    model.Create_On = DateUtil.Now();
                    model.Create_By = this.HttpContext.User.Identity.Name;
                    model.Update_On = DateUtil.Now();
                    model.Update_By = this.HttpContext.User.Identity.Name;

                    model.User           = new User();
                    model.User.Email     = model.UserName;
                    model.User.FirstName = model.MerchantName;
                    model.User.LastName  = "Admin";
                    model.User.UserName  = model.UserName;
                    model.User.Password  = DataEncryptor.Encrypt(model.Password);
                    model.User.Status    = UserStatusType.Active;
                    model.User.Create_On = DateUtil.Now();
                    model.User.Create_By = this.HttpContext.User.Identity.Name;
                    model.User.Update_On = DateUtil.Now();
                    model.User.Update_By = this.HttpContext.User.Identity.Name;
                    var userrole = _context.UserRoles.Where(w => w.RoleName == RoleName.Merchant).FirstOrDefault();
                    model.User.UserRoleID = userrole.UserRoleID;

                    this._context.Merchants.Add(model);
                    this._context.SaveChanges();

                    if (file != null)
                    {
                        var    webRoot   = Directory.GetCurrentDirectory() + "\\wwwroot\\images\\Merchant\\";
                        string extension = Path.GetExtension(file.FileName);
                        var    filename  = webRoot + model.MerchantID + dateformat + extension;
                        using (var fileStream = new FileStream(Path.Combine(webRoot, filename), FileMode.Create))
                        {
                            await file.CopyToAsync(fileStream);
                        }
                        filename  = filename.Replace(Directory.GetCurrentDirectory() + "\\wwwroot", "~");
                        filename  = filename.Replace("\\", "/");
                        model.Url = filename;
                        this._context.SaveChanges();
                    }
                    return(RedirectToAction("Index"));
                }
                else
                {
                    if (file != null)
                    {
                        if (!string.IsNullOrEmpty(model.Url))
                        {
                            var mwebRoot  = Directory.GetCurrentDirectory() + "\\wwwroot";
                            var mfilename = model.Url.Replace("~", mwebRoot);
                            mfilename = mfilename.Replace("/", "\\");
                            if (System.IO.File.Exists(mfilename))
                            {
                                System.IO.File.Delete(mfilename);
                            }
                        }
                        var    webRoot   = Directory.GetCurrentDirectory() + "\\wwwroot\\images\\Merchant\\";
                        string extension = Path.GetExtension(file.FileName);
                        var    filename  = webRoot + model.MerchantID + dateformat + extension;
                        using (var fileStream = new FileStream(Path.Combine(webRoot, filename), FileMode.Create))
                        {
                            await file.CopyToAsync(fileStream);
                        }
                        filename  = filename.Replace(Directory.GetCurrentDirectory() + "\\wwwroot", "~");
                        filename  = filename.Replace("\\", "/");
                        model.Url = filename;
                    }
                    model.Update_On = DateUtil.Now();
                    model.Update_By = this.HttpContext.User.Identity.Name;

                    if (!model.UserID.HasValue)
                    {
                        model.User           = new User();
                        model.User.Email     = model.UserName;
                        model.User.FirstName = model.MerchantName;
                        model.User.LastName  = "Admin";
                        model.User.UserName  = model.UserName;
                        model.User.Password  = DataEncryptor.Encrypt(model.Password);
                        model.User.Status    = UserStatusType.Active;
                        model.User.Create_On = DateUtil.Now();
                        model.User.Create_By = this.HttpContext.User.Identity.Name;
                        model.User.Update_On = DateUtil.Now();
                        model.User.Update_By = this.HttpContext.User.Identity.Name;
                        var userrole = _context.UserRoles.Where(w => w.RoleName == RoleName.Merchant).FirstOrDefault();
                        model.User.UserRoleID = userrole.UserRoleID;
                    }
                    else
                    {
                        var user = _context.Users.Where(w => w.ID == model.UserID).FirstOrDefault();
                        if (user != null)
                        {
                            user.UserName = model.UserName;
                            user.Password = DataEncryptor.Encrypt(model.Password);
                            this._context.Users.Attach(user);
                            this._context.Entry(user).Property(u => u.UserName).IsModified = true;
                            this._context.Entry(user).Property(u => u.Password).IsModified = true;
                        }
                    }
                    this._context.Update(model);
                    this._context.SaveChanges();
                    return(RedirectToAction("Index"));
                }
            }
            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));
        }
Пример #20
0
        public object insert([FromBody] JsonElement json)
        {
            var model = JsonConvert.DeserializeObject <UserDTO>(json.GetRawText());

            if (model == null)
            {
                return(CreatedAtAction(nameof(insert), new { result = ResultCode.InputHasNotFound, message = ResultMessage.InputHasNotFound }));
            }

            var dupid = _context.Students.Where(w => w.IDCard == model.idcard).FirstOrDefault();

            if (dupid != null)
            {
                return(CreatedAtAction(nameof(insert), new { result = ResultCode.DuplicateData, message = "เลขประจำตัวประชาชนซ้ำ" }));
            }

            if (!string.IsNullOrEmpty(model.studentcode))
            {
                var dupscode = _context.Students.Where(w => w.StudentCode == model.studentcode).FirstOrDefault();
                if (dupscode != null)
                {
                    return(CreatedAtAction(nameof(insert), new { result = ResultCode.DuplicateData, message = "รหัสนักศึกษาซ้ำ" }));
                }
            }

            var users = _context.Users.Count() + 1;

            model.username = model.idcard;

            var u = new User();

            u.UserName        = model.username;
            u.Password        = DataEncryptor.Encrypt(model.idcard);
            u.ConfirmPassword = DataEncryptor.Encrypt(model.idcard);
            u.Create_On       = DateUtil.Now();
            u.Create_By       = model.update_by;
            u.Update_On       = DateUtil.Now();
            u.Update_By       = model.update_by;

            var student = new Student();

            student.FirstName   = model.firstname;
            student.LastName    = model.lastname;
            student.FirstNameEn = model.firstnameen;
            student.LastNameEn  = model.lastnameen;
            student.Prefix      = model.prefix.toPrefix();
            student.Address     = model.address;
            student.Email       = model.email;
            student.Phone       = model.phone;
            student.Passport    = model.passport;
            student.IDCard      = model.idcard;
            student.StudentCode = model.studentcode;
            student.FacultyID   = model.faculty;
            student.Course      = model.course.toCourse();
            student.Status      = model.status.toStatus();
            student.Create_On   = DateUtil.Now();
            student.Create_By   = model.update_by;
            student.Update_On   = DateUtil.Now();
            student.Update_By   = model.update_by;
            student.User        = u;

            _context.Students.Add(student);
            _context.SaveChanges();
            return(CreatedAtAction(nameof(insert), new { result = ResultCode.Success, message = ResultMessage.Success }));
        }
Пример #21
0
        public static Customer Binding(Customer customer, CustomerDTO model)
        {
            if (customer == null)
            {
                customer               = new Customer();
                customer.Create_On     = DateUtil.Now();
                customer.ChannelUpdate = CustomerChanal.TIP;
            }

            if (!string.IsNullOrEmpty(model.email))
            {
                customer.Email = model.email;
            }

            if (model.prefixInt != null)
            {
                customer.PrefixTh = model.prefixInt;
            }

            if (!string.IsNullOrEmpty(model.firstName))
            {
                customer.NameTh = model.firstName;
            }

            if (!string.IsNullOrEmpty(model.lastName))
            {
                customer.SurNameTh = model.lastName;
            }

            if (model.prefixEnInt != null)
            {
                customer.PrefixEn = model.prefixEnInt;
            }

            if (!string.IsNullOrEmpty(model.firstNameEn))
            {
                customer.NameEn = model.firstNameEn;
            }

            if (!string.IsNullOrEmpty(model.lastNameEn))
            {
                customer.SurNameEn = model.lastNameEn;
            }

            if (!string.IsNullOrEmpty(model.moblieNo))
            {
                customer.MoblieNo = model.moblieNo;
            }

            if (!string.IsNullOrEmpty(model.telNo))
            {
                customer.TelNo = model.telNo;
            }

            if (!string.IsNullOrEmpty(model.lineId))
            {
                customer.LineID = model.lineId;
            }

            if (!string.IsNullOrEmpty(model.citizenId))
            {
                customer.IDCard = model.citizenId;
            }

            if (!string.IsNullOrEmpty(model.gender))
            {
                customer.Gender = model.gender;
            }

            if (model.prefixEnInt != null)
            {
                customer.UserID = model.userID;
            }

            if (!string.IsNullOrEmpty(model.passport))
            {
                customer.Passport = model.passport;
            }

            /*address*/

            if (customer.ChannelUpdate == CustomerChanal.TipInsure)
            {
                customer.CUR_HouseNo     = model.houseNo;
                customer.CUR_Soi         = model.lane;
                customer.CUR_Lane        = model.lane;
                customer.CUR_Road        = model.road;
                customer.CUR_Moo         = model.villageNo;
                customer.CUR_VillageNo   = model.villageNo;
                customer.CUR_VillageName = model.villageName;

                customer.CUR_HouseNoEn     = model.houseNoEn;
                customer.CUR_SoiEn         = model.laneEn;
                customer.CUR_LaneEn        = model.laneEn;
                customer.CUR_RoadEn        = model.roadEn;
                customer.CUR_MooEn         = model.villageNoEn;
                customer.CUR_VillageNoEn   = model.villageNoEn;
                customer.CUR_VillageNameEn = model.villageNameEn;
            }
            else if (customer.ChannelUpdate == CustomerChanal.Mobile)
            {
                customer.CUR_HouseNo     = model.houseNo;
                customer.CUR_Moo         = model.villageNo;
                customer.CUR_VillageNo   = model.villageNo;
                customer.CUR_VillageName = model.villageName;
                customer.CUR_Lane        = model.lane;
                customer.CUR_Soi         = model.lane;
                customer.CUR_Road        = model.road;

                customer.CUR_HouseNoEn     = model.houseNo;
                customer.CUR_MooEn         = model.villageNo;
                customer.CUR_VillageNoEn   = model.villageNoEn;
                customer.CUR_VillageNameEn = model.villageNameEn;
                customer.CUR_LaneEn        = model.laneEn;
                customer.CUR_SoiEn         = model.laneEn;
                customer.CUR_RoadEn        = model.roadEn;
            }
            else
            {
                customer.CUR_HouseNo     = model.houseNo;
                customer.CUR_Road        = model.road;
                customer.CUR_Soi         = model.soi;
                customer.CUR_Lane        = model.soi;
                customer.CUR_Moo         = model.moo;
                customer.CUR_VillageName = model.villageName;
                customer.CUR_VillageNo   = model.moo;

                customer.CUR_HouseNoEn     = model.houseNoEn;
                customer.CUR_RoadEn        = model.roadEn;
                customer.CUR_SoiEn         = model.soiEn;
                customer.CUR_LaneEn        = model.soiEn;
                customer.CUR_MooEn         = model.mooEn;
                customer.CUR_VillageNameEn = model.villageNameEn;
                customer.CUR_VillageNoEn   = model.mooEn;
            }

            if (model.provinceId != null)
            {
                customer.CUR_Province = model.provinceId;
            }

            if (model.subDistrictId != null)
            {
                customer.CUR_Tumbon = model.subDistrictId;
            }

            if (model.districtId != null)
            {
                customer.CUR_Aumper = model.districtId;
            }

            if (!string.IsNullOrEmpty(model.postalCode))
            {
                customer.CUR_ZipCode = model.postalCode;
            }

            /*address En*/
            if (model.provinceIdEn != null)
            {
                customer.CUR_ProvinceEn = model.provinceIdEn;
            }
            else if (model.provinceId != null)
            {
                customer.CUR_ProvinceEn = model.provinceId;
            }

            if (model.subDistrictIdEn != null)
            {
                customer.CUR_TumbonEn = model.subDistrictIdEn;
            }
            else if (model.subDistrictId != null)
            {
                customer.CUR_TumbonEn = model.subDistrictId;
            }

            if (model.districtIdEn != null)
            {
                customer.CUR_AumperEn = model.districtIdEn;
            }
            else if (model.districtId != null)
            {
                customer.CUR_AumperEn = model.districtId;
            }

            if (!string.IsNullOrEmpty(model.postalCodeEn))
            {
                customer.CUR_ZipCodeEn = model.postalCodeEn;
            }
            else if (!string.IsNullOrEmpty(model.postalCode))
            {
                customer.CUR_ZipCodeEn = model.postalCode;
            }

            if (!string.IsNullOrEmpty(model.facebookFlag) && model.ID <= 0)
            {
                customer.FacebookFlag = model.facebookFlag;
            }

            if (!string.IsNullOrEmpty(model.birthdate))
            {
                customer.DOB = DateUtil.ToDate(model.birthdate);
            }
            else if (model.birthdateDay > 0 && model.birthdateMonth > 0 && model.birthdateYear > 0)
            {
                customer.DOB = DateUtil.ToDate(model.birthdateDay, model.birthdateMonth, model.birthdateYear);
            }


            if (!string.IsNullOrEmpty(model.status))
            {
                customer.Status = model.status.toUserStatus();
            }

            if (!string.IsNullOrEmpty(model.refCode))
            {
                customer.RefCode = model.refCode;
            }

            if (customer.User == null)
            {
                customer.User = new User();
            }

            if (string.IsNullOrEmpty(model.username))
            {
                model.username = model.email;
            }

            if (!string.IsNullOrEmpty(model.email))
            {
                customer.User.Email = model.email;
            }

            if (!string.IsNullOrEmpty(model.moblieNo))
            {
                customer.User.PhoneNumber = model.moblieNo;
            }

            if (!string.IsNullOrEmpty(model.username))
            {
                customer.User.UserName = model.username;
            }

            customer.UserLevel       = model.userLevel;
            customer.User.UserRoleID = 2;

            if (!string.IsNullOrEmpty(model.status))
            {
                customer.User.Status = customer.Status;
            }

            if (!string.IsNullOrEmpty(model.password))
            {
                customer.User.Password = DataEncryptor.Encrypt(model.password);

                if (string.IsNullOrEmpty(customer.BCryptPwd))
                {
                    customer.BCryptPwd = BCrypt.Net.BCrypt.HashPassword(customer.User.Password);
                }

                customer.ResetedPwd = true;
            }

            if (customer.ID > 0)
            {
                customer.RefCode = GetRefCode(customer);
            }

            customer.Syned = true;

            customer.Channel = model.channelInt;
            //customer.PromotionCode = model.promotionCode;

            if (!string.IsNullOrEmpty(model.friendCode))
            {
                customer.FriendCode = model.friendCode;
            }

            if (!string.IsNullOrEmpty(model.facebookID))
            {
                customer.FacebookID = model.facebookID;
            }

            customer.DoSendReisterEmail = true;
            customer.Update_On          = DateUtil.Now();

            if (customer.CustomerPoints == null)
            {
                customer.CustomerPoints = new List <CustomerPoint>();
            }
            return(customer);
        }
Пример #22
0
        public static void SaveAstrandTestData(ÄstrandTest testData)
        {
            JObject personalData     = new JObject();
            JObject testResultData   = new JObject();
            JArray  heartratesJson   = new JArray();
            JArray  distancesJson    = new JArray();
            JArray  speedsJson       = new JArray();
            JArray  cycleRhythmsjson = new JArray();

            personalData.Add("name", testData.Username);
            personalData.Add("birthyear", testData.BirthYear);
            personalData.Add("weight", testData.Weight);
            personalData.Add("gender", (testData.IsMan) ? "man" : "woman");

            testResultData.Add("hassteadystate", testData.HasSteadyState);
            testResultData.Add("vo2", testData.VO2);

            foreach ((int heartrate, DateTime time)heartrateData in testData.HeartrateValues)
            {
                JObject heartrateJson = new JObject();
                heartrateJson.Add("heartrate", heartrateData.heartrate);
                heartrateJson.Add("time", heartrateData.time.ToString());
                heartratesJson.Add(heartrateJson);
            }

            foreach ((int distance, DateTime time)distanceData in testData.DistanceValues)
            {
                JObject distanceJson = new JObject();
                distanceJson.Add("distance", distanceData.distance);
                distanceJson.Add("time", distanceData.time.ToString());
                distancesJson.Add(distanceJson);
            }

            foreach ((int speed, DateTime time)speedData in testData.SpeedValues)
            {
                JObject speedJson = new JObject();
                speedJson.Add("speed", speedData.speed);
                speedJson.Add("time", speedData.time.ToString());
                speedsJson.Add(speedJson);
            }

            foreach ((int cycleRhythm, DateTime time)cycleRhythmData in testData.CycleRhythmValues)
            {
                JObject cycleRhythmJson = new JObject();
                cycleRhythmJson.Add("cyclerhythm", cycleRhythmData.cycleRhythm);
                cycleRhythmJson.Add("time", cycleRhythmData.time.ToString());
                cycleRhythmsjson.Add(cycleRhythmJson);
            }

            JObject testJson = new JObject();

            testJson.Add("personaldata", personalData);
            testJson.Add("testresult", testResultData);
            testJson.Add("heartrates", heartratesJson);
            testJson.Add("distances", distancesJson);
            testJson.Add("speeds", speedsJson);
            testJson.Add("cyclerhythms", cycleRhythmsjson);

            string filename = testData.Username + "_" + DateTime.Now.ToString();

            filename = filename.Replace("/", "-");
            filename = filename.Replace(":", "#");
            File.WriteAllText(testsFolderPath + @"/" + filename + ".json", DataEncryptor.Encrypt(testJson.ToString(), DataEncryptor.FileKey));
        }
Пример #23
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));
        }
Пример #24
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));
        }
Пример #25
0
        public object insert([FromBody] JsonElement json)
        {
            var model = JsonConvert.DeserializeObject <UserDTO>(json.GetRawText());

            if (model == null)
            {
                return(CreatedAtAction(nameof(insert), new { result = ResultCode.InputHasNotFound, message = ResultMessage.InputHasNotFound }));
            }

            var users    = _context.Users.Count() + 1;
            var username = "******" + users.ToString("0000");

            model.username = username;

            var u = new User();

            u.UserName        = model.username;
            u.Password        = DataEncryptor.Encrypt(model.username);
            u.ConfirmPassword = DataEncryptor.Encrypt(model.username);
            u.Create_On       = DateUtil.Now();
            u.Create_By       = model.update_by;
            u.Update_On       = DateUtil.Now();
            u.Update_By       = model.update_by;
            u.isAdmin         = true;

            var staff = new Staff();

            staff.FirstName            = model.firstname;
            staff.LastName             = model.lastname;
            staff.Prefix               = model.prefix.toPrefix();
            staff.Address              = model.address;
            staff.Email                = model.email;
            staff.Phone                = model.phone;
            staff.Phone2               = model.phone2;
            staff.Passport             = model.passport;
            staff.IDCard               = model.idcard;
            staff.OpenDate             = DateUtil.ToDate(model.opendate);
            staff.ExpiryDate           = DateUtil.ToDate(model.expirydate);
            staff.Status               = model.status.toStatus();
            staff.Create_On            = DateUtil.Now();
            staff.Create_By            = model.update_by;
            staff.Update_On            = DateUtil.Now();
            staff.Update_By            = model.update_by;
            staff.isAdmin              = model.isadmin.HasValue ? model.isadmin.Value : false;
            staff.isMasterAdmin        = model.ismasteradmin.HasValue ? model.ismasteradmin.Value : false;
            staff.isQuestionAppr       = model.isquestionappr.HasValue ? model.isquestionappr.Value : false;
            staff.isMasterQuestionAppr = model.ismasterquestionappr.HasValue ? model.ismasterquestionappr.Value : false;
            staff.isTestAppr           = model.istestappr.HasValue ? model.istestappr.Value : false;
            staff.isMasterTestAppr     = model.ismastertestappr.HasValue ? model.ismastertestappr.Value : false;
            staff.User = u;

            _context.Staffs.Add(staff);
            _context.SaveChanges();

            username   = "******" + u.ID.ToString("0000");
            u.UserName = username;
            u.Password = DataEncryptor.Encrypt(u.UserName);
            _context.SaveChanges();

            return(CreatedAtAction(nameof(insert), new { result = ResultCode.Success, message = ResultMessage.Success }));
        }
 public void Transmit(Message message)
 {
     byte[] encryptedMessage = DataEncryptor.Encrypt(message.GetBytes(), "Test");
     this.client.Transmit(encryptedMessage);
 }