/// <summary>
        /// 当出现多人请求字典数据时,此方法可能会出现延迟现象(自行根据实际处理)
        /// </summary>
        /// <returns></returns>
        private static List <Sys_Dictionary> GetAllDictionary()
        {
            ICacheService cacheService = AutofacContainerModule.GetService <ICacheService>();

            //每次比较缓存是否更新过,如果更新则重新获取数据
            if (_dictionaries != null && _dicVersionn == cacheService.Get(Key))
            {
                return(_dictionaries);
            }

            lock (_dicObj)
            {
                if (_dicVersionn != "" && _dictionaries != null && _dicVersionn == cacheService.Get(Key))
                {
                    return(_dictionaries);
                }
                _dictionaries = DBServerProvider.DbContext
                                .Set <Sys_Dictionary>()
                                .Where(x => x.Enable == 1)
                                .Include(c => c.Sys_DictionaryList).ToList();

                string cacheVersion = cacheService.Get(Key);
                if (string.IsNullOrEmpty(cacheVersion))
                {
                    cacheVersion = DateTime.Now.ToString("yyyyMMddHHMMssfff");
                    cacheService.Add(Key, cacheVersion);
                }
                else
                {
                    _dicVersionn = cacheVersion;
                }
            }
            return(_dictionaries);
        }
        public void Init()
        {
            var serviceCollection = GetService();

            serviceCollection.AddMemoryCache();
            serviceCollection.AddOptions();

            var optionMock = new Mock <IOptions <AppSetting> >();

            optionMock.Setup(x => x.Value).Returns(new AppSetting {
                DbType = Define.DBTYPE_MYSQL
            });
            serviceCollection.AddScoped(x => optionMock.Object);

            // 测试my sql
            serviceCollection.AddDbContext <OpenAuthDBContext>(options =>
                                                               options.UseMySql("server=127.0.0.1;user id=root;database=openauthdb;password=000000"));

//            serviceCollection.AddDbContext<OpenAuthDBContext>(options =>
//                options.UseSqlServer("Data Source=.;Initial Catalog=OpenAuthDB;User=sa;Password=000000;Integrated Security=True"));

            var container = AutofacExt.InitForTest(serviceCollection);

            _autofacServiceProvider = new AutofacServiceProvider(container);
            AutofacContainerModule.ConfigServiceProvider(_autofacServiceProvider);
        }
Exemple #3
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostEnvironment env)
        {
            app.UseAuthentication();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseStaticFiles();

            //配置ServiceProvider
            AutofacContainerModule.ConfigServiceProvider(app.ApplicationServices);

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Exemple #4
0
        public string GetService1()
        {
            // 一个接口多个实现 为不同的实现指定名称
            var container = AutofacContainerModule.GetContainer();
            var myService = container.ResolveNamed <IMyService>("service2");
            var result    = myService.ShowMsg("一个接口多个实现 为不同的实现指定名称 会触发拦截器");

            return(result);
        }
        /// <summary>
        /// 拦截控制器方法
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var isDefined = false;
            // 获取请求进来的控制器与方法
            var controllerActionDescriptor = filterContext.ActionDescriptor as ControllerActionDescriptor;

            if (controllerActionDescriptor != null)
            {
                isDefined = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
                            .Any(a => a.GetType().Equals(typeof(AllowAnonymousAttribute)));
            }

            if (isDefined || UserContext.Current.IsSuperAdmin)
            {
                return;
            }

            // 获取设置的操作码(如果没设置操作码,默认不验证权限)
            var actionCode = (PermissionAttribute)controllerActionDescriptor.MethodInfo
                             .GetCustomAttributes(inherit: true)
                             .FirstOrDefault(t => t.GetType().Equals(typeof(PermissionAttribute)));

            if (actionCode != null)
            {
                //tableNmae
                if (string.IsNullOrEmpty(actionCode.TableName))
                {
                    actionCode.TableName = controllerActionDescriptor.ControllerName;
                }

                var ResponseConten = new WebResponseContent();
                // 验证是否通过
                var permissions = AutofacContainerModule.GetService <Sys_RoleService>().GetUserPermissions();
                if (permissions == null || permissions.Count() == 0)
                {
                    filterContext.Result = new OkObjectResult(ResponseConten.Error(ResponseType.NoPermissions));
                    return;
                }
                var actionAuth = permissions.Where(x => x.TableName == actionCode.TableName.ToLower()).FirstOrDefault()?.UserAuthArr;
                if (actionAuth == null ||
                    actionAuth.Count() == 0 ||
                    !actionAuth.Contains(actionCode.Code.SafeString()))
                {
                    filterContext.Result = new OkObjectResult(ResponseConten.Error(ResponseType.NoPermissions));
                }
            }

            base.OnActionExecuting(filterContext);
        }
Exemple #6
0
        public void Init()
        {
            var serviceCollection = GetService();

            serviceCollection.AddMemoryCache();
            serviceCollection.AddOptions();
            //读取OpenAuth.WebApi的配置文件用于单元测试
            var            path     = AppContext.BaseDirectory;
            int            pos      = path.IndexOf("OpenAuth.App");
            var            basepath = Path.Combine(path.Substring(0, pos), "OpenAuth.WebApi");
            IConfiguration config   = new ConfigurationBuilder()
                                      .SetBasePath(basepath)
                                      .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                                      .AddJsonFile("appsettings.Development.json", optional: true)
                                      .AddEnvironmentVariables()
                                      .Build();

            serviceCollection.Configure <AppSetting>(config.GetSection("AppSetting"));
            //添加log4net
            serviceCollection.AddLogging(builder =>
            {
                builder.ClearProviders();                               //去掉默认的日志
                builder.AddConfiguration(config.GetSection("Logging")); //读取配置文件中的Logging配置
                builder.AddLog4Net();
            });
            //注入OpenAuth.WebApi配置文件
            serviceCollection.AddScoped(x => config);

            //模拟HTTP请求
            var httpContextAccessorMock = new Mock <IHttpContextAccessor>();

            httpContextAccessorMock.Setup(x => x.HttpContext.Request.Query[Define.TOKEN_NAME]).Returns("tokentest");
            httpContextAccessorMock.Setup(x => x.HttpContext.Request.Query[Define.TENANT_ID]).Returns("OpenAuthDBContext");
            serviceCollection.AddScoped(x => httpContextAccessorMock.Object);

            serviceCollection.AddDbContext <OpenAuthDBContext>();

            var container = AutofacExt.InitForTest(serviceCollection);

            _autofacServiceProvider = new AutofacServiceProvider(container);
            AutofacContainerModule.ConfigServiceProvider(_autofacServiceProvider);

            var dbtypes = config.GetSection("AppSetting:DbTypes").GetChildren()
                          .ToDictionary(x => x.Key, x => x.Value);

            Console.WriteLine($"单元测试数据库信息:{dbtypes[httpContextAccessorMock.Object.GetTenantId()]}/{config.GetSection("ConnectionStrings")["OpenAuthDBContext"]}");
        }
Exemple #7
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddLog4Net();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            //可以访问根目录下面的静态文件
            var staticfile = new StaticFileOptions {
                FileProvider = new PhysicalFileProvider(AppContext.BaseDirectory)
            };

            app.UseStaticFiles(staticfile);


            //todo:测试可以允许任意跨域,正式环境要加权限
            app.UseCors(builder => builder.AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader());

            app.UseRouting();
            app.UseAuthentication();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            //配置ServiceProvider
            AutofacContainerModule.ConfigServiceProvider(app.ApplicationServices);

            app.UseSwagger();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
            // specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "V1 Docs");
                c.DocExpansion(DocExpansion.None);
                c.OAuthClientId("OpenAuth.WebApi"); //oauth客户端名称
                c.OAuthAppName("开源版webapi认证");      // 描述
            });
        }
Exemple #8
0
        public void Init()
        {
            var serviceCollection = GetService();

            serviceCollection.AddMemoryCache();
            serviceCollection.AddOptions();
            //讀取OpenAuth.WebApi的配置檔案用於單元測試
            var            path     = AppContext.BaseDirectory;
            int            pos      = path.IndexOf("OpenAuth.App");
            var            basepath = Path.Combine(path.Substring(0, pos), "OpenAuth.WebApi");
            IConfiguration config   = new ConfigurationBuilder()
                                      .SetBasePath(basepath)
                                      .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                                      .AddJsonFile("appsettings.Development.json", optional: true)
                                      .AddEnvironmentVariables()
                                      .Build();

            Console.WriteLine($"單元測試資料庫資訊:{config.GetSection("AppSetting")["DbType"]}/{config.GetSection("ConnectionStrings")["OpenAuthDBContext"]}");

            //新增log4net
            serviceCollection.AddLogging(builder =>
            {
                builder.ClearProviders();                               //去掉預設的日誌
                builder.AddConfiguration(config.GetSection("Logging")); //讀取配置檔案中的Logging配置
                builder.AddLog4Net();
            });
            //注入OpenAuth.WebApi配置檔案
            serviceCollection.AddScoped(x => config);

            //模擬HTTP請求
            var httpContextAccessorMock = new Mock <IHttpContextAccessor>();

            httpContextAccessorMock.Setup(x => x.HttpContext.Request.Query[Define.TOKEN_NAME]).Returns("tokentest");
            httpContextAccessorMock.Setup(x => x.HttpContext.Request.Query[Define.TENANT_ID]).Returns("OpenAuthDBContext");
            serviceCollection.AddScoped(x => httpContextAccessorMock.Object);

            serviceCollection.AddDbContext <OpenAuthDBContext>();

            var container = AutofacExt.InitForTest(serviceCollection);

            _autofacServiceProvider = new AutofacServiceProvider(container);
            AutofacContainerModule.ConfigServiceProvider(_autofacServiceProvider);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public WebResponseContent Login(string userName, string password)
        {
            WebResponseContent responseContent = new WebResponseContent();

            if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(password))
            {
                return(responseContent.Error("登录错误"));
            }
            // var encryptPwd = AESEncrypt.Encrypt(password, AESEncrypt.pwdKey);

            var user = repository.Sys_User.Where(q => q.Enable == (byte)DataStatus.Enable)
                       .Where(q => q.UserName == userName && q.UserPwd == password).First();

            if (user == null)
            {
                return(responseContent.Error("账户或密码错误"));
            }
            var adminToken = new AdminUser
            {
                User_Id  = user.UID,
                Email    = user.Email,
                Role_Id  = user.Role_Id,
                UserName = user.UserName,
            };
            //获取token配置
            var tokenManagement = AutofacContainerModule.GetService <IOptions <TokenManagement> >().Value;

            var token = TokenHelper.CreateAdminToken(tokenManagement, adminToken);

            //HttpContext.Current.Response.Headers.Add("Authorization", new StringValues(token));

            return(responseContent.OK("登录成功", new M_AdminUserRP
            {
                id = user.UID,
                UserName = user.UserName,
                RoleId = user.Role_Id,
                HeadImageUrl = user.HeadImageUrl,
                Moblie = user.Mobile,
                Email = user.Email,
                Token = token,
            }));
        }
Exemple #10
0
 /// <summary>
 /// 获取 <paramref name="name"/> 对应的本地化字符串。
 /// </summary>
 /// <param name="name">本地化资源的名称。</param>
 /// <returns>返回本地化字符串。</returns>
 public static string L(string name)
 {
     if (string.IsNullOrWhiteSpace(name))
     {
         return(name);
     }
     try
     {
         var Language = WM.Infrastructure.Utilities.HttpContext.Current.Request.Headers["Language"].ToString();
         LocalizationHelper.InitializeLanguage(Language);
         var value = LocalizationHelper.GetString(name);
         return(value);
     }
     catch (Exception ex)
     {
         var logger = AutofacContainerModule.GetService <ILogger <BaseSerivce <TRepository> > >();
         logger?.LogError(ex, $"多语言名称[{name}]未找到!");
         //写日志
     }
     return(name);
 }
Exemple #11
0
        public static List <RoleNodes> GetAllRoleId()
        {
            ICacheService cacheService = AutofacContainerModule.GetService <ICacheService>();

            //每次比较缓存是否更新过,如果更新则重新获取数据
            if (_roles != null && _RoleVersionn == cacheService.Get(Key))
            {
                return(_roles);
            }
            lock (_RoleObj)
            {
                if (_RoleVersionn != "" && _roles != null && _RoleVersionn == cacheService.Get(Key))
                {
                    return(_roles);
                }
                _roles = DBServerProvider.DbContext
                         .Set <Sys_Role>()
                         .Where(x => x.Enable == 1)
                         .Select(s => new RoleNodes()
                {
                    Id = s.Role_Id, ParentId = s.ParentId, RoleName = s.RoleName
                })
                         .ToList();

                string cacheVersion = cacheService.Get(Key);
                if (string.IsNullOrEmpty(cacheVersion))
                {
                    cacheVersion = DateTime.Now.ToString("yyyyMMddHHMMssfff");
                    cacheService.Add(Key, cacheVersion);
                }
                else
                {
                    _RoleVersionn = cacheVersion;
                }
            }
            return(_roles);
        }
Exemple #12
0
 private static T GetService <T>() where T : class
 {
     return(AutofacContainerModule.GetService <T>());
 }
Exemple #13
0
 public static void Refresh()
 {
     AutofacContainerModule.GetService <ICacheService>().Remove(Key);
 }
Exemple #14
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="path"></param>
 /// <param name="rootPath">获取wwwroot路径</param>
 /// <returns></returns>
 public static string MapPath(this string path, bool rootPath)
 {
     return(AutofacContainerModule.GetService <IPathProvider>().MapPath(path, rootPath));
 }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddLog4Net();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMiniProfiler();

            //可以访问根目录下面的静态文件
            var staticfile = new StaticFileOptions
            {
                FileProvider      = new PhysicalFileProvider(AppContext.BaseDirectory),
                OnPrepareResponse = (ctx) =>
                {
                    //可以在这里为静态文件添加其他http头信息,默认添加跨域信息
                    ctx.Context.Response.Headers["Access-Control-Allow-Origin"] = "*";
                }
            };

            app.UseStaticFiles(staticfile);


            //todo:测试可以允许任意跨域,正式环境要加权限
            app.UseCors(builder => builder.AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader());

            app.UseRouting();
            app.UseAuthentication();

            // 启用日志追踪记录和异常友好提示
            app.UseLogMiddleware();

            app.UseEndpoints(endpoints => { endpoints.MapControllers(); });

            //配置ServiceProvider
            AutofacContainerModule.ConfigServiceProvider(app.ApplicationServices);


            app.UseSwagger();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
            // specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.IndexStream = () =>
                                GetType().GetTypeInfo().Assembly.GetManifestResourceStream("OpenAuth.WebApi.index.html");

                foreach (var controller in GetControllers())
                {
                    var groupname = GetSwaggerGroupName(controller);

                    c.SwaggerEndpoint($"/swagger/{groupname}/swagger.json", groupname);
                }

                c.DocExpansion(DocExpansion.List);  //默认展开列表
                c.OAuthClientId("OpenAuth.WebApi"); //oauth客户端名称
                c.OAuthAppName("开源版webapi认证");      // 描述
            });
        }