protected override bool HasExecutePermission(ActionExecutingContext filterContext, string Area, string Controller, string Action)
        {
            var userinfo = AuthenticationExtension.Current();

            if (userinfo.IsAdmin)
            {
                return(true);
            }
            else
            {
                List <HavePermisionDto> usePermits = null;
                //ISystemPermissionDapperRepository systemPermission = new SystemPermissionDapperRepository();
                string cacheKey = USER_PERMITS_CACHE_KEY + userinfo.UserId.ToString();
                usePermits = this._cache.Get <List <HavePermisionDto> >(cacheKey);
                if (usePermits == null)
                {
                    usePermits = _systemPermissionDapper.GetHavePermisionByUserId(userinfo.UserId.ToString()).Result.ToList();
                }
                _cache.Set(cacheKey, usePermits, TimeSpan.FromMinutes(10)); //缓存10分钟,10分钟后重新加载
                if (!usePermits.Any(a => Area.Equals(a.Area, StringComparison.OrdinalIgnoreCase) && Controller.Equals(a.Controller, StringComparison.OrdinalIgnoreCase) && Action.Equals(a.Action, StringComparison.OrdinalIgnoreCase)))
                {
                    return(false);
                }
            }
            return(true);
        }
예제 #2
0
        public async Task <JsonResult> Submit(UserLoginInput model)
        {
            model.Password = _3DESEncrypt.Encrypt(model.Password);
            var info = await _systemUserLogic.CheckUserByCodeAndPwdAsync(model);

            if (info.Data != null)
            {
                var prin = new PrincipalUser()
                {
                    UserId   = Guid.Parse(info.Data.UserId),
                    Code     = info.Data.Code,
                    Name     = info.Data.Name,
                    IsAdmin  = info.Data.IsAdmin,
                    RoleName = info.Data.RoleName,
                    ImgUrl   = info.Data.ImgUrl
                };
                if (prin.Code == "admin")
                {
                    prin.RoleName = "超级管理员";
                }
                //写入Cookie信息
                AuthenticationExtension.SetAuthCookie(prin);

                //写入日志
                var logHandler = new LoginLogHandler(info.Data.UserId, info.Data.Code, info.Data.Name, (int)EnumLoginType.账号密码登录);
                logHandler.WriteLog();
            }
            return(Json(info));
        }
        protected override bool HasExecutePermission(ActionExecutingContext filterContext, List <string> permissionCodes)
        {
            var userinfo = AuthenticationExtension.Current();

            if (userinfo.IsAdmin)
            {
                return(true);
            }
            else
            {
                List <string> usePermits = null;
                string        userId     = userinfo.UserId.ToString();
                string        cacheKey   = USER_PERMITSAj_CACHE_KEY + userId;
                usePermits = this._cache.Get <List <string> >(cacheKey);
                if (usePermits == null)
                {
                    usePermits = _systemPermissionDapper.GetHavePermisionStrByUserId(userId).Result.ToList();
                    _cache.Set(cacheKey, usePermits, TimeSpan.FromMinutes(15));//缓存15分钟,15分钟后重新加载
                }
                foreach (var permit in permissionCodes)
                {
                    if (!usePermits.Any(a => a == permit))
                    {
                        return(false);
                    }
                }
                return(true);
            }
        }
예제 #4
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            //app.UseHttpsRedirection();

            app.UseRouting();

            AuthenticationExtension.Configure(app);

            CorsExtension.Configure(app);

            app.UseStaticFiles();

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

            SwaggerExtension.Configure(app);

            SignalRExtension.Configure(app);
        }
        /// <summary>
        ///     Action开始执行触发
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            _operationLogHandler = new OperationLogHandler(filterContext.HttpContext.Request);
            CurrentUser          = AuthenticationExtension.Current();
            if (CurrentUser != null)
            {
                _operationLogHandler.log.CreateUserCode = CurrentUser.Code;
                _operationLogHandler.log.CreateUserName = CurrentUser.Name;
            }

            //获取Action特性
            var descriptionAttribute = filterContext.ActionDescriptor.EndpointMetadata.Where(a => a is DescriptionAttribute).ToList();;

            if (descriptionAttribute.Any())
            {
                var info = descriptionAttribute[0] as DescriptionAttribute;
                if (info != null)
                {
                    var description = info.Description;
                    _operationLogHandler.log.ControllerName =
                        ((Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)filterContext.ActionDescriptor).ControllerName;
                    _operationLogHandler.log.ActionName = ((Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)filterContext.ActionDescriptor).ActionName;
                    _operationLogHandler.log.Describe   = description;
                }
            }

            base.OnActionExecuting(filterContext);
        }
예제 #6
0
        public async Task <UserDto> CreateUserAsync(UserDto user)
        {
            user.ValidateToInsert();

            var password = user.Password;

            user.Password = null;

            if (await repository.ExistsByAsync(u => u.Username == user.Username))
            {
                throw new ValueAlreadyRegisteredException(user.Username);
            }

            var entityUser = user.ToEntity <User>(Mapper);

            entityUser.Roles.Add(new Role {
                RoleName = "User"
            });

            var hmac = AuthenticationExtension.Encrypt(password);

            entityUser.PasswordSalt = hmac.PasswordSalt;
            entityUser.PasswordHash = hmac.PasswordHash;

            entityUser = await repository.AddAsync(entityUser);

            return(entityUser.ToDto <UserDto>(Mapper));
        }
예제 #7
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.InjectBusinessLogicDependency(Configuration);

            AuthenticationExtension.Add(services, Configuration);
            CorsExtension.Add(services);

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
예제 #8
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     DependencyInjectionExtension.ConfigureService(services);
     CorsExtension.ConfigureService(services);
     AuthenticationExtension.ConfigureService(services);
     MediatRExtension.ConfigureService(services);
     SwaggerExtension.ConfigureService(services);
     ControllersExtension.ConfigureService(services);
     SignalRExtension.ConfigureService(services);
 }
        /// <summary>
        ///     构造函数
        /// </summary>
        /// <param name="exception"></param>
        public ExceptionLogHandler(Exception exception) : base("ExceptionLogToDatabase")
        {
            PrincipalUser principalUser = new PrincipalUser();
            var           current       = HttpContexts.Current;

            if (current != null)
            {
                principalUser = AuthenticationExtension.Current();
            }
            if (principalUser == null)
            {
                principalUser = new PrincipalUser()
                {
                    Name   = "匿名用户",
                    UserId = Guid.Empty
                };
            }
            log = new ExceptionLog()
            {
                ExceptionLogId = CombUtil.NewComb().ToString(),
                CreateUserCode = principalUser.Code,
                CreateUserId   = principalUser.UserId.ToString(),
                CreateUserName = principalUser.Name,
                ServerHost     = String.Format("{0}【{1}】", IpBrowserUtil.GetServerHost(), IpBrowserUtil.GetServerHostIp()),
                ClientHost     = String.Format("{0}", IpBrowserUtil.GetClientIp()),
                Runtime        = "Web",
                CreateTime     = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                Message        = exception.Message,
                StackTrace     = exception.StackTrace,
                ExceptionType  = exception.GetType().FullName,
                ClientAddress  = IpBrowserUtil.GetAddressByApi()
            };
            //获取服务器信息
            var request = HttpContexts.Current.Request;

            log.RequestUrl     = string.Format("{0} ", request.Path);
            log.HttpMethod     = request.Method;
            log.UserAgent      = request.Headers["user-agent"];
            log.InnerException = exception.InnerException != null?GetExceptionFullMessage(exception.InnerException) : "";

            if (request?.HasFormContentType ?? request.HasFormContentType)
            {
                log.RequestData = request?.Form?.ToJson();
            }
            else
            {
                if (request.Body.CanSeek)
                {
                    log.RequestData = HttpUtility.UrlDecode(new StreamReader(request?.Body).ReadToEnd());
                }
            }
        }
예제 #10
0
        public async Task <IActionResult> Login(UserLoginInput model)
        {
            model.Password = _3DESEncrypt.Encrypt(model.Password);
            var info = await _systemUserLogic.CheckUserByCodeAndPwdAsync(model);

            if (info.Data != null)
            {
                var prin = new PrincipalUser()
                {
                    UserId  = info.Data.Id,
                    Code    = info.Data.Code,
                    Name    = info.Data.Name,
                    IsAdmin = info.Data.IsAdmin,
                    //TODO先注释
                    //RoleName = info.Data.RoleName,
                    ImgUrl = info.Data.ImgUrl
                };
                if (prin.Code == "admin")
                {
                    prin.RoleName = "超级管理员";
                }
                //写入Cookie信息
                AuthenticationExtension.SetAuthCookie(prin);

                //写入日志
                var logHandler = new LoginLogHandler(info.Data.Id.ToString(), info.Data.Code, info.Data.Name, (int)EnumLoginType.账号密码登录);
                logHandler.WriteLog();
            }
            if (info.ResultSign == ResultSign.Successful)
            {
                if (Url.IsLocalUrl(model.ReturnUrl))
                {
                    return(Redirect(model.ReturnUrl));
                }
                else if (string.IsNullOrEmpty(model.ReturnUrl))
                {
                    return(Redirect("~/"));
                }
                else
                {
                    // user might have clicked on a malicious link - should be logged
                    throw new Exception("invalid return URL");
                }
            }
            else
            {
                ModelState.AddModelError(string.Empty, info.Message);
            }

            return(View());
        }
예제 #11
0
        /// <summary>
        /// Activates the WorkBench and the middleware of its services previously initiated.
        /// </summary>
        /// <param name="builder">The builder of the core application</param>
        /// <returns>The builder of the core application</returns>
        public static IServiceCollection AddWorkBench(this IServiceCollection service, IConfiguration Configuration, bool hasIdentityServer = false)
        {
            WorkBench.Configuration = Configuration;
            //Add Secrets options
            WorkBench.Configuration = Configuration.UseSecrets();

            service.AddHttpContextAccessor();

            //Inject Swagger (Open API specification) and API Versioning
            WebApiVersion.AddApiVersion(service);
            Swagger.AddSwagger(service);

            //Inject JWT pattern and security
            AuthenticationExtension.AddAuth(service, hasIdentityServer);

            TelemetryExtensions.AddTelemetry(service);

            return(service);
        }
예제 #12
0
        public SqlLogHandler(string operateSql,
                             DateTime endDateTime,
                             double elapsedTime,
                             string parameter
                             )
            : base("SqlLogToDatabase")
        {
            PrincipalUser principalUser = new PrincipalUser
            {
                Name   = "匿名用户",
                UserId = Guid.Empty
            };
            var current = HttpContexts.Current;

            if (current != null)
            {
                principalUser = AuthenticationExtension.Current();
            }
            if (principalUser == null)
            {
                principalUser = new PrincipalUser()
                {
                    Name   = "匿名用户",
                    UserId = Guid.Empty
                };
            }
            log = new SqlLog
            {
                SqlLogId       = CombUtil.NewComb(),
                CreateTime     = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                CreateUserId   = principalUser.UserId.ToString(),
                CreateUserCode = principalUser.Code,
                CreateUserName = principalUser.Name,
                OperateSql     = operateSql,
                ElapsedTime    = elapsedTime,
                EndDateTime    = endDateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                Parameter      = parameter
            };
        }
예제 #13
0
        /// <summary>
        ///  人脸识别登录
        /// </summary>
        /// <returns></returns>
        public async Task <JsonResult> LoginFaceSubmit(string facebase)
        {
            OperateStatus <UserLoginOutput> operateStatus = new OperateStatus <UserLoginOutput>();
            var results = new FaceUtil().SearchFace(facebase);

            if (results.error_msg == "SUCCESS")
            {
                var infobase = await _systemUserLogic.GetById(results.result.user_id.Replace('M', '-'));

                var info = await _systemUserLogic.CheckUserByCodeAndPwdAsync(new UserLoginInput { Code = infobase.Code, Password = infobase.Password });

                if (info != null)
                {
                    var prin = new PrincipalUser()
                    {
                        UserId   = Guid.Parse(info.Data.UserId),
                        Code     = info.Data.Code,
                        Name     = info.Data.Name,
                        IsAdmin  = info.Data.IsAdmin,
                        RoleName = info.Data.RoleName,
                        ImgUrl   = info.Data.ImgUrl
                    };
                    //写入Cookie信息
                    AuthenticationExtension.SetAuthCookie(prin);
                    //写入日志
                    var logHandler = new LoginLogHandler(info.Data.UserId, info.Data.Code, info.Data.Name, (int)EnumLoginType.账号密码登录);
                    logHandler.WriteLog();
                }
            }
            else
            {
                operateStatus.ResultSign = Core.Entities.ResultSign.Error;
                operateStatus.Message    = "识别失败!";
                goto End;
            }
End:
            return(Json(operateStatus));
        }
예제 #14
0
 /// <summary>
 /// 登录退出界面
 /// </summary>
 /// <returns></returns>
 public ActionResult Logout()
 {
     AuthenticationExtension.SignOut();
     return(RedirectToAction("Login", "Account"));
 }
예제 #15
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //获取当前登录人员信息
            PrincipalUser currentUser = AuthenticationExtension.Current();

            #region 是否具有忽略验证特性
            //是否具有忽略特性:若有忽略特性则不进行其他的验证
            if (filterContext.ActionDescriptor.FilterDescriptors.Where(a => a.Filter is IgnoreAttribute).Select(a => a.Filter as IgnoreAttribute).ToList().Count() > 0)
            {
                return;
            }
            #endregion


            #region 用户是否登录
            if (currentUser == null)
            {
                filterContext.Result = new ContentResult()
                {
                    Content     = @"<script type='text/javascript'>
                                        alert('登录超时!系统将退出重新登录!');
                                        top.window.location='/sysManage/Account/Login';
                                    </script>",
                    ContentType = "text/html;charset=utf-8;"
                };
                ErrorRedirect(filterContext, "/sysManage/Account/Login");
                return;
            }
            #endregion

            #region 权限验证


            bool isAjaxCall = filterContext.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest";
            if (this.SkipAuthorize(filterContext.ActionDescriptor))
            {
                return;
            }
            List <string> permissionCodes = filterContext.ActionDescriptor.FilterDescriptors.Where(a => a.Filter is PermissionAttribute).Select(a => a.Filter as PermissionAttribute).Select(a => a.Code).ToList();

            if (!isAjaxCall)
            {
                if (currentUser != null)
                {
                    if (this.HasExecutePermission(filterContext, permissionCodes))
                    {
                        return;
                    }
                    //说明处于登录状态,则开始验证当前登录用户是否拥有访问权限
                    if (!this.HasExecutePermission(filterContext, filterContext.RouteData.Values["Area"].ToString(), filterContext.RouteData.Values["Controller"].ToString(),
                                                   filterContext.RouteData.Values["Action"].ToString()))
                    {
                        ErrorRedirect(filterContext, "/sysManage/Home/Unauthorizeds");
                        return;
                    }
                }
            }

            else
            {
                if (permissionCodes.Count == 0)
                {
                    return;
                }
                if (this.HasExecutePermission(filterContext, permissionCodes))
                {
                    return;
                }

                OperateStatus operate = new OperateStatus {
                    Message = "抱歉,您无当前操作权限", ResultSign = ResultSign.Error
                };
                ContentResult contentResult = new ContentResult()
                {
                    Content = JsonConvert.SerializeObject(operate)
                };
                filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                filterContext.Result = contentResult;
                return;
            }
            #endregion
            base.OnActionExecuting(filterContext);
        }