示例#1
0
        public void Create()
        {
            // 全局初始化设置WorkerId,默认最大2^16-1。(初始化过程全局只需一次,且必须最先设置)
            var options = new IdGeneratorOptions()
            {
                Method   = 1,
                WorkerId = 1
            };

            YitIdHelper.SetIdGenerator(options);
            var code = YitIdHelper.NextId().ToString();

            var app         = _autofacServiceProvider.GetService <FlowInstanceApp>();
            var instanceReq = new AddFlowInstanceReq
            {
                SchemeId   = "0dac17c2-fec7-4bcd-a391-4ff74de8506a",
                FrmType    = 1,
                DbName     = "FrmLeaveReq",
                FrmData    = "{\"id\":\"\",\"userName\":\"周翔宇\",\"requestType\":\"病假\",\"startDate\":\"2021-03-08T16:00:00.000Z\",\"startTime\":\"2021-03-16T15:11:28.000Z\",\"endDate\":\"2021-03-24T16:00:00.000Z\",\"endTime\":\"2021-03-16T15:11:31.000Z\",\"requestComment\":\"1111\",\"attachment\":\"\",\"files\":[],\"extendInfo\":\"\"}",
                CustomName = DateTime.Now.ToString(),
                Code       = code
            };

            app.CreateInstance(instanceReq);
        }
示例#2
0
文件: Startup.cs 项目: jwc-gh/Wichian
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            //  NGINX 反向代理获取真实IP
            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });

            // 添加状态码拦截中间件
            app.UseUnifyResultStatusCodes();

            app.UseHttpsRedirection(); // 强制https
            app.UseStaticFiles();

            // Serilog请求日志中间件---必须在 UseStaticFiles 和 UseRouting 之间
            app.UseSerilogRequestLogging();

            app.UseRouting();

            app.UseCorsAccessor();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseInject(string.Empty);

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapHub <ChatHub>("/hubs/chathub");

                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });

            // 设置雪花Id的workerId,确保每个实例workerId都应不同
            var workerId = ushort.Parse(App.Configuration["SnowId:WorkerId"] ?? "1");

            YitIdHelper.SetIdGenerator(new IdGeneratorOptions {
                WorkerId = workerId
            });

            // 开启自启动定时任务
            App.GetService <ISysTimerService>().StartTimerJob();
        }
示例#3
0
        static LongEntity()
        {
            //设置参数,程序初始化时执行一次
            var options = new IdGeneratorOptions()
            {
                Method   = 1,
                WorkerId = 1
            };

            YitIdHelper.SetIdGenerator(options);
        }
示例#4
0
        private YitterSnowFlake()
        {
            if (_currentWorkerId > MaxWorkerId || _currentWorkerId < 0)
            {
                throw new Exception(string.Format("worker Id can't be greater than {0} or less than 0", MaxWorkerId));
            }

            YitIdHelper.SetIdGenerator(new IdGeneratorOptions((ushort)_currentWorkerId)
            {
                WorkerIdBitLength = YitterWorkerIdBitLength
                ,
                SeqBitLength = YitterSeqBitLength
            });;
        }
示例#5
0
        public void Generate()
        {
            // 全局初始化设置WorkerId,默认最大2^16-1。(初始化过程全局只需一次,且必须最先设置)
            var options = new IdGeneratorOptions()
            {
                Method   = 1,
                WorkerId = 1
            };

            YitIdHelper.SetIdGenerator(options);
            long newId = YitIdHelper.NextId();

            Console.WriteLine("=====================================");
            Console.WriteLine("生成的 Id:" + newId);
        }
示例#6
0
    protected override void SavingChangesEvent(DbContextEventData eventData, InterceptionResult <int> result)
    {
        var dbContext = eventData.Context;

        var entities = dbContext.ChangeTracker.Entries().Where(u => u.State == EntityState.Added || u.State == EntityState.Modified || u.State == EntityState.Deleted);

        foreach (var entity in entities)
        {
            switch (entity.State)
            {
            case EntityState.Added:
                entity.Property(nameof(BaseEntity.Id)).CurrentValue = YitIdHelper.NextId();
                break;
            }
        }
    }
示例#7
0
        protected override void SavingChangesEvent(DbContextEventData eventData, InterceptionResult <int> result)
        {
            // 获取所有已更改的实体
            var entities = eventData.Context.ChangeTracker.Entries()
                           .Where(u => u.State == EntityState.Modified || u.State == EntityState.Deleted || u.State == EntityState.Added)
                           .ToList();

            // 判断是否是演示环境
            var demoEnvFlag = App.GetService <ISysConfigService>().GetDemoEnvFlag().GetAwaiter().GetResult();

            if (demoEnvFlag)
            {
                var sysUser = entities.Find(u => u.Entity.GetType() == typeof(SysUser));
                if (sysUser == null || string.IsNullOrEmpty((sysUser.Entity as SysUser).LastLoginTime.ToString())) // 排除登录
                {
                    throw Oops.Oh(ErrorCode.D1200);
                }
            }

            // 当前操作用户信息
            var userId   = App.User.FindFirst(ClaimConst.CLAINM_USERID)?.Value;
            var userName = App.User.FindFirst(ClaimConst.CLAINM_ACCOUNT)?.Value;

            foreach (var entity in entities)
            {
                if (entity.Entity.GetType().IsSubclassOf(typeof(DEntityBase <long, MultiTenantDbContextLocator>)))
                {
                    var obj = entity.Entity as DEntityBase <long, MultiTenantDbContextLocator>;
                    if (entity.State == EntityState.Added)
                    {
                        obj.Id          = YitIdHelper.NextId();
                        obj.CreatedTime = DateTimeOffset.Now;
                        if (!string.IsNullOrEmpty(userId))
                        {
                            obj.CreatedUserId   = long.Parse(userId);
                            obj.CreatedUserName = userName;
                        }
                    }
                    else if (entity.State == EntityState.Modified)
                    {
                        obj.UpdatedTime     = DateTimeOffset.Now;
                        obj.UpdatedUserId   = long.Parse(userId);
                        obj.UpdatedUserName = userName;
                    }
                }
            }
        }
示例#8
0
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddConfigurableOptions <WechatOptions>();
        var wechat = App.GetConfig <WechatOptions>("Wechat", true);

        services.AddHttpApi <IWechatApi>(o =>
        {
            o.HttpHost = new Uri(wechat.AuthUrl);
        });

        //TODO id long dto transcation to string
        YitIdHelper.SetIdGenerator(new IdGeneratorOptions(1));

        services.AddCorsAccessor();
        services.AddTaskScheduler();

        services.AddControllers()
        .AddInjectWithUnifyResult();

        services.AddMvcFilter <SessionFilter>();
    }
示例#9
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World! C#");

            var options = new IdGeneratorOptions()
            {
                Method   = method,
                WorkerId = 1,

                WorkerIdBitLength     = 6,
                SeqBitLength          = 6,
                DataCenterIdBitLength = 10,
                TopOverCostCount      = 2000,

                //TimestampType = 1,

                // MinSeqNumber = 1,
                // MaxSeqNumber = 200,

                // BaseTime = DateTime.Now.AddYears(-10),
            };

            IdGen = new DefaultIdGenerator(options);
            GenTest genTest = new GenTest(IdGen, genIdCount, options.WorkerId);

            // 首先测试一下 IdHelper 方法,获取单个Id
            YitIdHelper.SetIdGenerator(options);
            long newId = YitIdHelper.NextId();

            Console.WriteLine("=====================================");
            Console.WriteLine("这是用方法 " + method + " 生成的 Id:" + newId);

            while (true)
            {
                RunSingle();
                //CallDll();
                //Go(options);
                Thread.Sleep(1000); // 每隔1秒执行一次Go
            }
        }
示例#10
0
        /// <summary>
        /// 审计数据
        /// </summary>
        /// <param name="e"></param>
        /// <param name="timeOffset"></param>
        /// <param name="user"></param>
        public static void AuditValue(AuditValueEventArgs e, TimeSpan timeOffset, IUser user)
        {
            if (e.Property.GetCustomAttribute <ServerTimeAttribute>(false) != null &&
                (e.Column.CsType == typeof(DateTime) || e.Column.CsType == typeof(DateTime?)) &&
                (e.Value == null || (DateTime)e.Value == default || (DateTime?)e.Value == default))
            {
                e.Value = DateTime.Now.Subtract(timeOffset);
            }

            if (e.Column.CsType == typeof(long) &&
                e.Property.GetCustomAttribute <SnowflakeAttribute>(false) != null &&
                (e.Value == null || (long)e.Value == default || (long?)e.Value == default))
            {
                e.Value = YitIdHelper.NextId();
            }

            if (user == null || user.Id <= 0)
            {
                return;
            }

            if (e.AuditValueType == FreeSql.Aop.AuditValueType.Insert)
            {
                switch (e.Property.Name)
                {
                case "CreatedUserId":
                    if (e.Value == null || (long)e.Value == default || (long?)e.Value == default)
                    {
                        e.Value = user.Id;
                    }
                    break;

                case "CreatedUserName":
                    if (e.Value == null || ((string)e.Value).IsNull())
                    {
                        e.Value = user.Name;
                    }
                    break;

                case "TenantId":
                    if (e.Value == null || (long)e.Value == default || (long?)e.Value == default)
                    {
                        e.Value = user.TenantId;
                    }
                    break;
                }
            }
            else if (e.AuditValueType == FreeSql.Aop.AuditValueType.Update)
            {
                switch (e.Property.Name)
                {
                case "ModifiedUserId":
                    e.Value = user.Id;
                    break;

                case "ModifiedUserName":
                    e.Value = user.Name;
                    break;
                }
            }
        }
示例#11
0
 public long GetId()
 {
     return(YitIdHelper.NextId());
 }
示例#12
0
        public void ConfigureServices(IServiceCollection services)
        {
            //雪花漂移算法
            YitIdHelper.SetIdGenerator(new IdGeneratorOptions(1)
            {
                WorkerIdBitLength = 6
            });

            services.AddScoped <IPermissionHandler, PermissionHandler>();

            // ClaimType不被更改
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            //用户信息
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            if (_appConfig.IdentityServer.Enable)
            {
                //is4
                services.TryAddSingleton <IUser, UserIdentiyServer>();
            }
            else
            {
                //jwt
                services.TryAddSingleton <IUser, User>();
            }

            //添加数据库
            services.AddDbAsync(_env).Wait();

            //添加IdleBus单例
            var dbConfig          = new ConfigHelper().Get <DbConfig>("dbconfig", _env.EnvironmentName);
            int idleTime          = dbConfig.IdleTime > 0 ? dbConfig.IdleTime : 10;
            IdleBus <IFreeSql> ib = new IdleBus <IFreeSql>(TimeSpan.FromMinutes(idleTime));

            services.AddSingleton(ib);
            //数据库配置
            services.AddSingleton(dbConfig);

            //应用配置
            services.AddSingleton(_appConfig);

            //上传配置
            var uploadConfig = _configHelper.Load("uploadconfig", _env.EnvironmentName, true);

            services.Configure <UploadConfig>(uploadConfig);

            #region AutoMapper 自动映射

            var serviceAssembly = Assembly.Load("Admin.Core.Service");
            services.AddAutoMapper(serviceAssembly);

            #endregion AutoMapper 自动映射

            #region Cors 跨域

            if (_appConfig.CorUrls?.Length > 0)
            {
                services.AddCors(options =>
                {
                    options.AddPolicy(DefaultCorsPolicyName, policy =>
                    {
                        policy
                        .WithOrigins(_appConfig.CorUrls)
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials();
                    });

                    /*
                     * //浏览器会发起2次请求,使用OPTIONS发起预检请求,第二次才是api异步请求
                     * options.AddPolicy("All", policy =>
                     * {
                     *  policy
                     *  .AllowAnyOrigin()
                     *  .SetPreflightMaxAge(new TimeSpan(0, 10, 0))
                     *  .AllowAnyHeader()
                     *  .AllowAnyMethod()
                     *  .AllowCredentials();
                     * });
                     */
                });
            }

            #endregion Cors 跨域

            #region 身份认证授权

            var jwtConfig = _configHelper.Get <JwtConfig>("jwtconfig", _env.EnvironmentName);
            services.TryAddSingleton(jwtConfig);

            if (_appConfig.IdentityServer.Enable)
            {
                //is4
                services.AddAuthentication(options =>
                {
                    options.DefaultScheme          = IdentityServerAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = nameof(ResponseAuthenticationHandler); //401
                    options.DefaultForbidScheme    = nameof(ResponseAuthenticationHandler); //403
                })
                .AddJwtBearer(options =>
                {
                    options.Authority            = _appConfig.IdentityServer.Url;
                    options.RequireHttpsMetadata = false;
                    options.Audience             = "admin.server.api";
                })
                .AddScheme <AuthenticationSchemeOptions, ResponseAuthenticationHandler>(nameof(ResponseAuthenticationHandler), o => { });
            }
            else
            {
                //jwt
                services.AddAuthentication(options =>
                {
                    options.DefaultScheme          = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = nameof(ResponseAuthenticationHandler); //401
                    options.DefaultForbidScheme    = nameof(ResponseAuthenticationHandler); //403
                })
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer           = true,
                        ValidateAudience         = true,
                        ValidateLifetime         = true,
                        ValidateIssuerSigningKey = true,
                        ValidIssuer      = jwtConfig.Issuer,
                        ValidAudience    = jwtConfig.Audience,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.SecurityKey)),
                        ClockSkew        = TimeSpan.Zero
                    };
                })
                .AddScheme <AuthenticationSchemeOptions, ResponseAuthenticationHandler>(nameof(ResponseAuthenticationHandler), o => { });
            }

            #endregion 身份认证授权

            #region Swagger Api文档

            if (_env.IsDevelopment() || _appConfig.Swagger)
            {
                services.AddSwaggerGen(options =>
                {
                    typeof(ApiVersion).GetEnumNames().ToList().ForEach(version =>
                    {
                        options.SwaggerDoc(version, new OpenApiInfo
                        {
                            Version = version,
                            Title   = "Admin.Core"
                        });
                        //c.OrderActionsBy(o => o.RelativePath);
                    });

                    var xmlPath = Path.Combine(basePath, "Admin.Core.xml");
                    options.IncludeXmlComments(xmlPath, true);

                    var xmlCommonPath = Path.Combine(basePath, "Admin.Core.Common.xml");
                    options.IncludeXmlComments(xmlCommonPath, true);

                    var xmlModelPath = Path.Combine(basePath, "Admin.Core.Model.xml");
                    options.IncludeXmlComments(xmlModelPath);

                    var xmlServicesPath = Path.Combine(basePath, "Admin.Core.Service.xml");
                    options.IncludeXmlComments(xmlServicesPath);

                    #region 添加设置Token的按钮

                    if (_appConfig.IdentityServer.Enable)
                    {
                        //添加Jwt验证设置
                        options.AddSecurityRequirement(new OpenApiSecurityRequirement()
                        {
                            {
                                new OpenApiSecurityScheme
                                {
                                    Reference = new OpenApiReference
                                    {
                                        Id   = "oauth2",
                                        Type = ReferenceType.SecurityScheme
                                    }
                                },
                                new List <string>()
                            }
                        });

                        //统一认证
                        options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                        {
                            Type        = SecuritySchemeType.OAuth2,
                            Description = "oauth2登录授权",
                            Flows       = new OpenApiOAuthFlows
                            {
                                Implicit = new OpenApiOAuthFlow
                                {
                                    AuthorizationUrl = new Uri($"{_appConfig.IdentityServer.Url}/connect/authorize"),
                                    Scopes           = new Dictionary <string, string>
                                    {
                                        { "admin.server.api", "admin后端api" }
                                    }
                                }
                            }
                        });
                    }
                    else
                    {
                        //添加Jwt验证设置
                        options.AddSecurityRequirement(new OpenApiSecurityRequirement()
                        {
                            {
                                new OpenApiSecurityScheme
                                {
                                    Reference = new OpenApiReference
                                    {
                                        Id   = "Bearer",
                                        Type = ReferenceType.SecurityScheme
                                    }
                                },
                                new List <string>()
                            }
                        });

                        options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                        {
                            Description = "Value: Bearer {token}",
                            Name        = "Authorization",
                            In          = ParameterLocation.Header,
                            Type        = SecuritySchemeType.ApiKey
                        });
                    }

                    #endregion 添加设置Token的按钮
                });
            }

            #endregion Swagger Api文档

            #region 操作日志

            if (_appConfig.Log.Operation)
            {
                //services.AddSingleton<ILogHandler, LogHandler>();
                services.AddScoped <ILogHandler, LogHandler>();
            }

            #endregion 操作日志

            #region 控制器

            services.AddControllers(options =>
            {
                options.Filters.Add <AdminExceptionFilter>();
                if (_appConfig.Log.Operation)
                {
                    options.Filters.Add <LogActionFilter>();
                }
                //禁止去除ActionAsync后缀
                options.SuppressAsyncSuffixInActionNames = false;
            })
            //.AddFluentValidation(config =>
            //{
            //    var assembly = Assembly.LoadFrom(Path.Combine(basePath, "Admin.Core.dll"));
            //    config.RegisterValidatorsFromAssembly(assembly);
            //})
            .AddNewtonsoftJson(options =>
            {
                //忽略循环引用
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                //使用驼峰 首字母小写
                options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                //设置时间格式
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            });

            #endregion 控制器

            #region 缓存

            var cacheConfig = _configHelper.Get <CacheConfig>("cacheconfig", _env.EnvironmentName);
            if (cacheConfig.Type == CacheType.Redis)
            {
                var csredis = new CSRedis.CSRedisClient(cacheConfig.Redis.ConnectionString);
                RedisHelper.Initialization(csredis);
                services.AddSingleton <ICache, RedisCache>();
            }
            else
            {
                services.AddMemoryCache();
                services.AddSingleton <ICache, MemoryCache>();
            }

            #endregion 缓存

            #region IP限流

            if (_appConfig.RateLimit)
            {
                services.AddIpRateLimit(_configuration, cacheConfig);
            }

            #endregion IP限流

            //阻止NLog接收状态消息
            services.Configure <ConsoleLifetimeOptions>(opts => opts.SuppressStatusMessages = true);
        }
        public async Task <IResponseOutput> Login(LoginInput input)
        {
            if (!ModelState.IsValid)
            {
                return(ResponseOutput.NotOk(ModelState.Values.First().Errors[0].ErrorMessage));
            }

            var sw = new Stopwatch();

            sw.Start();

            var context = await _interaction.GetAuthorizationContextAsync(input.ReturnUrl);

            var user = await _userRepository.Select.Where(a => a.UserName == input.UserName)
                       .ToOneAsync(a => new { a.Id, a.Password, a.NickName, a.TenantId });

            if (user == null)
            {
                return(ResponseOutput.NotOk("", 1));
            }

            var password = MD5Encrypt.Encrypt32(input.Password);

            if (user.Password != password)
            {
                return(ResponseOutput.NotOk("", 2));
            }

            AuthenticationProperties props = null;

            if (input.RememberLogin)
            {
                props = new AuthenticationProperties
                {
                    IsPersistent = true,
                    ExpiresUtc   = DateTimeOffset.UtcNow.Add(TimeSpan.FromDays(1))
                };
            }
            ;

            var identityServerUser = new IdentityServerUser(user.Id.ToString())
            {
                DisplayName = input.UserName
            };

            await HttpContext.SignInAsync(identityServerUser, props);

            sw.Stop();

            //写登录日志
            var loginLogEntity = new LoginLogEntity()
            {
                Id                  = YitIdHelper.NextId(),
                TenantId            = user.TenantId,
                CreatedUserId       = user.Id,
                NickName            = user.NickName,
                CreatedUserName     = input.UserName,
                ElapsedMilliseconds = sw.ElapsedMilliseconds,
                Status              = true
            };

            await AddLoginLog(loginLogEntity);

            return(ResponseOutput.Ok());
        }
示例#14
0
 /// <summary>
 /// 采用雪花算法计算Id
 /// </summary>
 public override void GenerateDefaultKeyVal()
 {
     Id = YitIdHelper.NextId();
 }
        public async Task <IResponseOutput> Login(LoginInput input)
        {
            if (!ModelState.IsValid)
            {
                return(ResponseOutput.NotOk(ModelState.Values.First().Errors[0].ErrorMessage));
            }

            if (input.Captcha == null)
            {
                return(ResponseOutput.NotOk("请完成安全验证!"));
            }

            //滑动验证
            input.Captcha.DeleteCache = true;
            using var client          = new HttpClient();
            var res = await client.GetAsync($"{_appSettings.Captcha.CheckUrl}?{ToParams(input.Captcha)}");

            var content = await res.Content.ReadAsStringAsync();

            var captchaResult = JsonConvert.DeserializeObject <ResultModel <string> >(content);

            if (!captchaResult.Success)
            {
                return(ResponseOutput.NotOk("安全验证不通过,请重新登录!"));
            }


            var sw = new Stopwatch();

            sw.Start();

            var context = await _interaction.GetAuthorizationContextAsync(input.ReturnUrl);

            var user = await _userRepository.Select.Where(a => a.UserName == input.UserName)
                       .ToOneAsync(a => new { a.Id, a.Password, a.NickName, a.TenantId });

            if (user == null)
            {
                return(ResponseOutput.NotOk("", 1));
            }

            var password = MD5Encrypt.Encrypt32(input.Password);

            if (user.Password != password)
            {
                return(ResponseOutput.NotOk("", 2));
            }

            AuthenticationProperties props = null;

            if (input.RememberLogin)
            {
                props = new AuthenticationProperties
                {
                    IsPersistent = true,
                    ExpiresUtc   = DateTimeOffset.UtcNow.Add(TimeSpan.FromDays(1))
                };
            }
            ;

            var identityServerUser = new IdentityServerUser(user.Id.ToString())
            {
                DisplayName = input.UserName
            };

            await HttpContext.SignInAsync(identityServerUser, props);

            sw.Stop();

            //写登录日志
            var loginLogEntity = new LoginLogEntity()
            {
                Id                  = YitIdHelper.NextId(),
                TenantId            = user.TenantId,
                CreatedUserId       = user.Id,
                NickName            = user.NickName,
                CreatedUserName     = input.UserName,
                ElapsedMilliseconds = sw.ElapsedMilliseconds,
                Status              = true
            };

            await AddLoginLog(loginLogEntity);

            return(ResponseOutput.Ok());
        }
示例#16
0
        protected override void SavingChangesEvent(DbContextEventData eventData, InterceptionResult <int> result)
        {
            // 获取当前事件对应上下文
            var dbContext = eventData.Context;
            // 获取所有更改,删除,新增的实体,但排除审计实体(避免死循环)
            var entities = dbContext.ChangeTracker.Entries()
                           .Where(u => u.Entity.GetType() != typeof(SysLogAudit) && u.Entity.GetType() != typeof(SysLogOp) &&
                                  u.Entity.GetType() != typeof(SysLogVis) && u.Entity.GetType() != typeof(SysLogEx) &&
                                  (u.State == EntityState.Modified || u.State == EntityState.Deleted || u.State == EntityState.Added)).ToList();

            if (entities == null || entities.Count < 1)
            {
                return;
            }

            // 判断是否是演示环境
            var demoEnvFlag = App.GetService <ISysConfigService>().GetDemoEnvFlag().GetAwaiter().GetResult();

            if (demoEnvFlag)
            {
                var sysUser = entities.Find(u => u.Entity.GetType() == typeof(SysUser));
                if (sysUser == null || string.IsNullOrEmpty((sysUser.Entity as SysUser).LastLoginTime.ToString())) // 排除登录
                {
                    throw Oops.Oh(ErrorCode.D1200);
                }
            }

            // 当前操作者信息
            var userId   = App.User.FindFirst(ClaimConst.CLAINM_USERID)?.Value;
            var userName = App.User.FindFirst(ClaimConst.CLAINM_ACCOUNT)?.Value;

            foreach (var entity in entities)
            {
                if (entity.Entity.GetType().IsSubclassOf(typeof(DEntityTenant)))
                {
                    var obj = entity.Entity as DEntityTenant;
                    switch (entity.State)
                    {
                    // 自动设置租户Id
                    case EntityState.Added:
                        var tenantId = entity.Property(nameof(Entity.TenantId)).CurrentValue;
                        if (tenantId == null || (long)tenantId == 0)
                        {
                            entity.Property(nameof(Entity.TenantId)).CurrentValue = long.Parse(GetTenantId().ToString());
                        }

                        obj.Id          = obj.Id == 0 ? YitIdHelper.NextId() : obj.Id;
                        obj.CreatedTime = DateTimeOffset.Now;
                        if (!string.IsNullOrEmpty(userId))
                        {
                            obj.CreatedUserId   = long.Parse(userId);
                            obj.CreatedUserName = userName;
                        }
                        break;

                    // 排除租户Id
                    case EntityState.Modified:
                        entity.Property(nameof(Entity.TenantId)).IsModified = false;
                        obj.UpdatedTime = DateTimeOffset.Now;
                        if (!string.IsNullOrEmpty(userId))
                        {
                            obj.UpdatedUserId   = long.Parse(userId);
                            obj.UpdatedUserName = userName;
                        }
                        break;
                    }
                }
                else if (entity.Entity.GetType().IsSubclassOf(typeof(DEntityBase)))
                {
                    var obj = entity.Entity as DEntityBase;
                    if (entity.State == EntityState.Added)
                    {
                        obj.Id          = obj.Id == 0 ? YitIdHelper.NextId() : obj.Id;
                        obj.CreatedTime = DateTimeOffset.Now;
                        if (!string.IsNullOrEmpty(userId))
                        {
                            obj.CreatedUserId   = long.Parse(userId);
                            obj.CreatedUserName = userName;
                        }
                    }
                    else if (entity.State == EntityState.Modified)
                    {
                        obj.UpdatedTime = DateTimeOffset.Now;
                        if (!string.IsNullOrEmpty(userId))
                        {
                            obj.UpdatedUserId   = long.Parse(userId);
                            obj.UpdatedUserName = userName;
                        }
                    }
                }
            }
        }
示例#17
0
        public void ConfigureServices(IServiceCollection services)
        {
            //界面即时编译,Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation
            //services.AddRazorPages().AddRazorRuntimeCompilation();

            //雪花漂移算法
            YitIdHelper.SetIdGenerator(new IdGeneratorOptions(1)
            {
                WorkerIdBitLength = 6
            });

            services.AddSingleton(_appSettings);
            services.AddSingleton(new IPHelper());
            services.AddDb(_appSettings);

            #region Cors 跨域

            if (_appSettings.CorUrls?.Length > 0)
            {
                services.AddCors(options =>
                {
                    options.AddPolicy("Limit", policy =>
                    {
                        policy
                        .WithOrigins(_appSettings.CorUrls)
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials();
                    });
                });
            }

            #endregion Cors 跨域

            var builder = services.AddIdentityServer(options =>
            {
                options.UserInteraction = new UserInteractionOptions
                {
                    LoginUrl  = "/user/login",
                    LogoutUrl = "/user/logout"
                };
            })
                          .AddInMemoryIdentityResources(Config.IdentityResources)
                          .AddInMemoryApiScopes(Config.ApiScopes)
                          .AddInMemoryApiResources(Config.ApiResources)
                          .AddInMemoryClients(Config.Clients(_appSettings))
                          .AddProfileService <AdminProfileService>()
                          .AddResourceOwnerValidator <AdminResourceOwnerPasswordValidator>();

            if (_env.IsDevelopment())
            {
                builder.AddDeveloperSigningCredential();
            }
            else
            {
                builder.AddSigningCredential(new X509Certificate2(
                                                 Path.Combine(AppContext.BaseDirectory, _appSettings.Certificate.Path),
                                                 _appSettings.Certificate.Password)
                                             );
            }

            services.ConfigureApplicationCookie(options =>
            {
                options.LoginPath = "/user/login";
            });

            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromSeconds(120);
            });

            services.AddControllersWithViews(options =>
            {
                //禁止去除ActionAsync后缀
                options.SuppressAsyncSuffixInActionNames = false;
            })
            .AddNewtonsoftJson(options =>
            {
                //忽略循环引用
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                //使用驼峰 首字母小写
                options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                //设置时间格式
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            });

            if (_env.IsDevelopment() || _appSettings.Swagger)
            {
                services.AddSwaggerGen(options =>
                {
                    options.SwaggerDoc("v1", new OpenApiInfo
                    {
                        Version = "v1",
                        Title   = "Admin.IdentityServer"
                    });

                    //添加Jwt验证设置
                    options.AddSecurityRequirement(new OpenApiSecurityRequirement()
                    {
                        {
                            new OpenApiSecurityScheme
                            {
                                Reference = new OpenApiReference
                                {
                                    Id   = "Bearer",
                                    Type = ReferenceType.SecurityScheme
                                }
                            },
                            new List <string>()
                        }
                    });

                    //添加设置Token的按钮
                    options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                    {
                        Description = "Value: Bearer {token}",
                        Name        = "Authorization",
                        In          = ParameterLocation.Header,
                        Type        = SecuritySchemeType.ApiKey
                    });

                    string xmlPath = Path.Combine(basePath, $"{typeof(Startup).Assembly.GetName().Name}.xml");
                    options.IncludeXmlComments(xmlPath);
                });
            }

            if (_appSettings.Health)
            {
                services.AddHealthChecks();
            }
        }