Esempio n. 1
0
        public static void Initialize(ApplicationDbContext context)
        {
            context.Database.EnsureCreated();

            if (context.IdentityUser.Any())
            {
                return;
            }

            var salt = Guid.NewGuid().ToString();

            IdentityUser admin = new IdentityUser
            {
                Name         = "管理员",
                Account      = "admin",
                AccountType  = 0,
                Age          = 0,
                Birthday     = new DateTime(),
                Salt         = salt,
                Password     = Md5Utility.Sign("123456", salt),
                Gender       = true,
                IsEnabled    = true,
                Email        = "*****@*****.**",
                HomePage     = "Administrator",
                IdNumber     = "0",
                DepartmentId = 0,
                Department   = "管理员部门"
            };

            context.IdentityUser.Add(admin);
            context.SaveChanges();
        }
    public void GenCode(string folder)
    {
        if (!Directory.Exists(folder))
        {
            Directory.CreateDirectory(folder);
        }

        //typeMd5 code
        string        line = "\t\ttypeMd5[typeof({0})] = \"{1}\";\n";
        StringBuilder sb   = new StringBuilder(typeMd5CodeBegin);

        foreach (var type in registeredTypes)
        {
            var    gen  = GetGenerator(type);
            string code = gen.GenerateSerializerCode(type);
            if (code != null)
            {
                string typename = gen.SerializerFileName(type);
                sb.Append(string.Format(line, typename, Md5Utility.MD5String(code)));
                File.WriteAllText(Path.Combine(folder, typename + ".cs"), code);
            }
        }
        sb.Append(typeMd5CodeEnd);
        File.WriteAllText(Path.Combine(folder, "TypesMd5.cs"), sb.ToString());
    }
        public string GetInMask()
        {
            string mask = "";

            mask = GetAllValue();
            mask = Md5Config.InPreFix + mask + Md5Config.InPostFix;
            mask = Md5Utility.Encrypt32(mask);
            return(mask);
        }
    public static void ReadConfigAsBin(Type type, string name)
    {
        var    gen = BinarySerializerCodeGenerator.GetGenerator(type);
        string serializerFileName = gen.SerializerFileName(type);

        if (!serializerFileName.StartsWith("Static_"))
        {
            UnityEngine.Debug.LogError("Config type must be static");
            return;
        }

        Type serializer = Type.GetType(serializerFileName + ",Assembly-CSharp");

        if (serializer != null)
        {
            MethodInfo read = serializer.GetMethod("Read", BindingFlags.Public | BindingFlags.Static);
            if (read != null)
            {
                string       path = Path.Combine(FileUtils.binary_config_folder, name + ".conf");
                BinaryReader br   = new BinaryReader(File.Open(path, FileMode.Open));
                byte[]       md5  = br.ReadBytes(16);
                var          same = Md5Utility.Md5Compare(md5, Md5Utility.MD5(configGeneratorMd5(type)));
                if (!same)
                {
                    br.Close();
                    UnityEngine.Debug.LogError("Read binary config error: md5 not the same");
                    return;
                }
                read.Invoke(null, new object[] { br });
                br.Close();
            }
            else
            {
                UnityEngine.Debug.LogError("Generate serializer code first");
            }
        }
        else
        {
            UnityEngine.Debug.LogError("Generate serializer code first");
        }
    }
    public static void WriteConfigAsBin(Type type, string name, string folder)
    {
        var    gen = BinarySerializerCodeGenerator.GetGenerator(type);
        string serializerFileName = gen.SerializerFileName(type);

        if (!serializerFileName.StartsWith("Static_"))
        {
            UnityEngine.Debug.LogError("Config type must be static");
            return;
        }

        byte[] md5 = Md5Utility.MD5(ConfigReader.configGeneratorMd5(type));

        Type serializer = Type.GetType(serializerFileName + ",Assembly-CSharp");

        if (serializer != null)
        {
            MethodInfo write = serializer.GetMethod("Write", BindingFlags.Public | BindingFlags.Static);
            if (write != null)
            {
                string       path = Path.Combine(folder, name + ".conf");
                BinaryWriter bw   = new BinaryWriter(File.Open(path, FileMode.Create));
                bw.Write(md5);
                write.Invoke(null, new object[] { bw });
                bw.Close();
            }
            else
            {
                UnityEngine.Debug.LogError("Generate serializer code first");
            }
        }
        else
        {
            UnityEngine.Debug.LogError("Generate serializer code first");
        }
    }
        public async Task <IActionResult> Login(LoginViewModel viewModel, string returnUrl)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                var user = await _service.GetUserAsync(viewModel.Account, viewModel.Password, _context);

                if (user != null)
                {
                    if (user.Password.Trim() != Md5Utility.Sign(viewModel.Password, user.Salt))
                    {
                        ViewBag.ErrorInfo = "用户名或密码错误";
                        return(View());
                    }

                    _logger.LogInformation("用户:{0}于{1}登录系统", viewModel.Account, DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));

                    string role = GetRole(user);

                    //根据用户角色创建claim声明
                    List <Claim> claim = new List <Claim>
                    {
                        new Claim(ClaimTypes.Role, role)
                    };

                    var userIdentity = new ClaimsIdentity(role);
                    userIdentity.AddClaims(claim);

                    var userPrincipal = new ClaimsPrincipal(userIdentity);

                    await HttpContext.SignInAsync(userPrincipal, new AuthenticationProperties
                    {
                        ExpiresUtc   = DateTime.UtcNow.AddMinutes(20),
                        IsPersistent = false,
                        AllowRefresh = false
                    });

                    //设置当前用户信息
                    await _service.SetCurrentUser(user.IdentityUserOID, _httpContextAccessor, _context);

                    if (!string.IsNullOrEmpty(returnUrl))
                    {
                        return(RedirectToLocal(returnUrl));
                    }

                    return(RedirectToRoute(new
                    {
                        area = user.HomePage,
                        controller = "Home",
                        action = "Index"
                    }));
                }
                else
                {
                    ViewBag.ErrorInfo = "当前用户不存在";
                    return(View());
                }
            }

            //返回模型验证错误信息
            ViewBag.ErrorInfo = this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors).FirstOrDefault()?.ErrorMessage;
            return(View(viewModel));
        }
        public List <T> ConsumeMessages <T>(string queueUrl, bool deleteMessages = false, int?maxNumberOfMessages = null)
        {
            ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest
            {
                QueueUrl = queueUrl
            };

            if (maxNumberOfMessages.HasValue)
            {
                receiveMessageRequest.MaxNumberOfMessages = maxNumberOfMessages.Value;
            }

            ReceiveMessageResponse receiveMessageResponse = m_amazonSqsClient.ReceiveMessage(receiveMessageRequest);

            var messagesAndMd5 = receiveMessageResponse.Messages
                                 .Select(s => new { s.MessageId, s.Body, IsValidMD5 = Md5Utility.CompareMd5Sqs(s.Body, s.MD5OfBody), s.ReceiptHandle })
                                 .ToList();

            if (messagesAndMd5.Any(a => !a.IsValidMD5))
            {
                LoggingRepository.Log(LoggingCategory.RepricingScript, "MD5 on IMwsSubscriptionServiceApi was not valid.");
            }

            // Filter out messages with corrupted Body (Md5 didn't match).
            var messagesAndMd5Filtered = messagesAndMd5.Where(w => w.IsValidMD5)
                                         .ToDictionary(k => k.MessageId, v => v);

            if (deleteMessages && messagesAndMd5Filtered.Any())
            {
                List <DeleteMessageBatchRequestEntry> deleteMessageBatchRequestEntries = messagesAndMd5Filtered
                                                                                         .Select(s => s.Value)
                                                                                         .Select(s => new DeleteMessageBatchRequestEntry {
                    Id = s.MessageId, ReceiptHandle = s.ReceiptHandle
                })
                                                                                         .ToList();

                DeleteMessageBatchResponse deleteMessageBatchResponse = m_amazonSqsClient.DeleteMessageBatch(new DeleteMessageBatchRequest {
                    Entries = deleteMessageBatchRequestEntries, QueueUrl = queueUrl
                });

                // Don't return messages that we weren't able to delete.
                if (deleteMessageBatchResponse.Failed.Any())
                {
                    foreach (BatchResultErrorEntry batchResultErrorEntry in deleteMessageBatchResponse.Failed)
                    {
                        if (messagesAndMd5Filtered.ContainsKey(batchResultErrorEntry.Id))
                        {
                            messagesAndMd5Filtered.Remove(batchResultErrorEntry.Id);
                        }
                    }
                }
            }

            return(messagesAndMd5Filtered.Select(s => s.Value.Body.FromXml <T>()).ToList());
        }