Exemplo n.º 1
0
        public object Get()
        {
            var identity  = HttpContext.User.Identity as ClaimsIdentity;
            var userClaim = _authService.GetClaim(identity);

            try
            {
                _logger.LogInfo($"{MethodInfoHelper.GetCurrentMethodName()} started.");
                var user = _authService.AuthorizeUser(Convert.ToInt32(userClaim[4].Value));
                if (user != null)
                {
                    var jobs = _unitOfWork.Jobs.GetAll();
                    return(new { message = "Success", jobs = _unitOfWork.Jobs.GetAll() });
                }
                else
                {
                    return(new { message = "Unauthorize" });
                }
            }
            catch (AppException ex)
            {
                _logger.LogError($"{MethodInfoHelper.GetCurrentMethodName()} failed.", ex);
                throw;
            }
            finally
            {
                _logger.LogInfo($"{MethodInfoHelper.GetCurrentMethodName()} ended.");
            }
        }
        public object Get(int id)
        {
            var identity  = HttpContext.User.Identity as ClaimsIdentity;
            var userClaim = _authService.GetClaim(identity);

            try
            {
                _logger.LogInfo($"{MethodInfoHelper.GetCurrentMethodName()} started.");
                if (Convert.ToInt32(userClaim[4].Value) != 0)
                {
                    return(new { message = "Success", user = _userDetail.GetById(id) });
                }
                else
                {
                    return(new { message = "Unauthorize" });
                }
            }
            catch (AppException ex)
            {
                _logger.LogError($"{MethodInfoHelper.GetCurrentMethodName()} failed.", ex);
                throw;
            }
            finally
            {
                _logger.LogInfo($"{MethodInfoHelper.GetCurrentMethodName()} ended.");
            }
        }
Exemplo n.º 3
0
        protected virtual void HandleUnauthorizedRequest(
            AuthorizationContext filterContext,
            MethodInfo methodInfo,
            Exception ex)
        {
            filterContext.HttpContext.Response.StatusCode =
                filterContext.RequestContext.HttpContext.User?.Identity?.IsAuthenticated ?? false
                    ? (int)HttpStatusCode.Forbidden
                    : (int)HttpStatusCode.Unauthorized;

            var isJsonResult = MethodInfoHelper.IsJsonResult(methodInfo);

            if (isJsonResult)
            {
                filterContext.Result = CreateUnAuthorizedJsonResult(ex);
            }
            else
            {
                filterContext.Result = CreateUnAuthorizedNonJsonResult(filterContext, ex);
            }

            if (isJsonResult || filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true;
            }
        }
Exemplo n.º 4
0
        public object Post([FromBody] ApplicantsVm applicantVm)
        {
            var identity  = HttpContext.User.Identity as ClaimsIdentity;
            var userClaim = _authService.GetClaim(identity);

            try
            {
                _logger.LogInfo($"{MethodInfoHelper.GetCurrentMethodName()} started.");
                var user = _authService.AuthorizeUser(Convert.ToInt32(userClaim[4].Value));
                if (user != null)
                {
                    var applicant = _mapper.Map <Applicant>(applicantVm);
                    _unitOfWork.Applicants.Insert(applicant);
                    _unitOfWork.Applicants.Save();

                    return(Ok(new { message = "Success" }));
                }
                else
                {
                    return(new { message = "Unauthorize" });
                }
            }
            catch (AppException ex)
            {
                _logger.LogError($"{MethodInfoHelper.GetCurrentMethodName()} failed.", ex);
                throw;
            }
            finally
            {
                _logger.LogInfo($"{MethodInfoHelper.GetCurrentMethodName()} ended.");
            }
        }
Exemplo n.º 5
0
        public object Login([FromBody] UserVm userVm)
        {
            IActionResult response = Unauthorized();

            try
            {
                _logger.LogInfo($"{MethodInfoHelper.GetCurrentMethodName()} started.");
                UserModel login = new UserModel();
                login.EmailAddress = userVm.EmailAddress;
                login.Password     = userVm.Password;

                var user = _authService.AuthenticateUser(login);
                if (user != null)
                {
                    var tokenResponse = _authService.GenerateJSONWebToken(user);
                    return(response = Ok(new { token = tokenResponse, status = "success" }));
                }
            }
            catch (AppException ex)
            {
                _logger.LogError($"{MethodInfoHelper.GetCurrentMethodName()} failed.", ex);
                throw;
            }
            finally
            {
                _logger.LogInfo($"{MethodInfoHelper.GetCurrentMethodName()} ended.");
            }


            return(new { message = "Email address or password are not valid!!!" });
        }
        private void CreateErrorResponse(
            AuthorizationContext context,
            MethodInfo methodInfo,
            string message)
        {
            Logger.Warn(message);
            Logger.Warn("Requested URI: " + context.HttpContext.Request.Url);

            context.HttpContext.Response.StatusCode        = (int)HttpStatusCode.BadRequest;
            context.HttpContext.Response.StatusDescription = message;

            var isJsonResult = MethodInfoHelper.IsJsonResult(methodInfo);

            if (isJsonResult)
            {
                context.Result = CreateUnAuthorizedJsonResult(message);
            }
            else
            {
                context.Result = CreateUnAuthorizedNonJsonResult(context, message);
            }

            if (isJsonResult || context.HttpContext.Request.IsAjaxRequest())
            {
                context.HttpContext.Response.SuppressFormsAuthenticationRedirect = true;
            }
        }
Exemplo n.º 7
0
        public UserModel GetUser()
        {
            try
            {
                _logger.LogInfo($"{MethodInfoHelper.GetCurrentMethodName()} started.");
                IList <Claim> claim = GetClaim();
                var           user  = new UserModel
                {
                    EmailAddress = claim[0].Value,
                    Role         = claim[1].Value,
                    FirstName    = claim[2].Value,
                    LastName     = claim[3].Value,
                    Id           = Convert.ToInt32(claim[4].Value)
                };

                return(user);
            }
            catch (AppException ex)
            {
                _logger.LogError($"{MethodInfoHelper.GetCurrentMethodName()} failed.", ex);
                throw;
            }
            finally
            {
                _logger.LogInfo($"{MethodInfoHelper.GetCurrentMethodName()} ended.");
            }
        }
Exemplo n.º 8
0
 public UdpServer(uint secret = 0, int bufferSize = 1024) : base(SocketConfiguration.UdpConfiguration, secret, bufferSize)
 {
     this.bufferSize = bufferSize;
     systemDataEvents.Add(0, MethodInfoHelper.GetMethodInfo <UdpServer>(x => x.PingEventHandler(null)));
     systemDataEvents.Add(1, MethodInfoHelper.GetMethodInfo <UdpServer>(x => x.DisconnectEventHandler(null, false)));
     systemDataEvents.Add(2, MethodInfoHelper.GetMethodInfo <UdpServer>(x => x.ReliableDataResponseReceived(null, 0L)));
 }
        protected virtual void HandleUnauthorizedRequest(
            AuthorizationContext filterContext,
            MethodInfo methodInfo
            // AbpAuthorizationException ex
            )
        {
            filterContext.HttpContext.Response.StatusCode =
                filterContext.RequestContext.HttpContext.User?.Identity?.IsAuthenticated ?? false
                    ? (int)HttpStatusCode.Forbidden
                    : (int)HttpStatusCode.Unauthorized;

            var isJsonResult = MethodInfoHelper.IsJsonResult(methodInfo);

            if (isJsonResult)
            {
                //filterContext.Result = CreateUnAuthorizedJsonResult(ex);
                filterContext.Result = new AbpJsonResult();
            }
            else
            {
                // filterContext.Result = CreateUnAuthorizedNonJsonResult(filterContext, ex);
                filterContext.Result = new HttpUnauthorizedResult();
            }

            if (isJsonResult || filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true;
            }
            //_eventBus.Trigger(this, new AbpHandledExceptionData(ex));
        }
Exemplo n.º 10
0
 public SyncCallback(string procedureUri, MethodInfoHelper methodInfoHelper, object[] arguments, IOperationResultExtractor <TResult> extractor)
 {
     mMethodInfoHelper = methodInfoHelper;
     mLogger           = LogProvider.GetLogger(typeof(SyncCallback <TResult>) + "." + procedureUri);
     mArguments        = arguments;
     mExtractor        = extractor;
 }
        private void HandleUnauthorizedRequest(
            AuthorizationContext filterContext,
            MethodInfo methodInfo,
            AbpAuthorizationException ex)
        {
            filterContext.HttpContext.Response.StatusCode =
                filterContext.RequestContext.HttpContext.User?.Identity?.IsAuthenticated ?? false
                    ? (int)HttpStatusCode.Forbidden
                    : (int)HttpStatusCode.Unauthorized;

            var isJsonResult = MethodInfoHelper.IsJsonResult(methodInfo);

            if (isJsonResult)
            {
                filterContext.Result = new AbpJsonResult(
                    new AjaxResponse(
                        _errorInfoBuilder.BuildForException(ex)
                        )
                    )
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
            else
            {
                filterContext.Result = new HttpStatusCodeResult(filterContext.HttpContext.Response.StatusCode, ex.Message);
            }

            if (isJsonResult || filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true;
            }
        }
Exemplo n.º 12
0
        public void FindStaticMethodsWithAttributeTest()
        {
            var methods = MethodInfoHelper.FindStaticMethodsWithAttribute <Att>(_types);

            Assert.IsTrue(HasAllStaticMethods(methods));
            Assert.IsFalse(HasAnyInstanceMethods(methods));
            Assert.IsFalse(HasNonAttributeMethods(methods));
        }
Exemplo n.º 13
0
        public void GetStaticMethodsTest()
        {
            var methods = MethodInfoHelper.GetStaticMethods(_types);

            Assert.IsTrue(HasAllStaticMethods(methods));
            Assert.IsFalse(HasAnyInstanceMethods(methods));
            Assert.IsTrue(HasNonAttributeMethods(methods));
        }
Exemplo n.º 14
0
        private SyncCallback <T> InnerInvokeSync <T>(ICalleeProxyInterceptor interceptor, MethodInfo method, IOperationResultExtractor <T> extractor, object[] arguments, Type unwrapped)
        {
            MethodInfoHelper methodInfoHelper = new MethodInfoHelper(method);

            string procedureUri = interceptor.GetProcedureUri(method);

            SyncCallback <T> syncCallback = new SyncCallback <T>(procedureUri, methodInfoHelper, arguments, extractor);

            object[] argumentsToSend =
                methodInfoHelper.GetInputArguments(arguments);

            Invoke(interceptor, syncCallback, method, argumentsToSend);

            return(syncCallback);
        }
Exemplo n.º 15
0
 private IList <Claim> GetClaim()
 {
     try
     {
         _logger.LogInfo($"{MethodInfoHelper.GetCurrentMethodName()} started.");
         var           identity = HttpContext.User.Identity as ClaimsIdentity;
         IList <Claim> claim    = identity.Claims.ToList();
         return(claim);
     }
     catch (AppException ex)
     {
         _logger.LogError($"{MethodInfoHelper.GetCurrentMethodName()} failed.", ex);
         throw;
     }
     finally
     {
         _logger.LogInfo($"{MethodInfoHelper.GetCurrentMethodName()} ended.");
     }
 }
Exemplo n.º 16
0
        public object Post([FromBody] JobVm jobVm)
        {
            try
            {
                _logger.LogInfo($"{MethodInfoHelper.GetCurrentMethodName()} started.");
                var job = _mapper.Map <Job>(jobVm);
                if (job != null)
                {
                    _unitOfWork.Jobs.Insert(job);
                    _unitOfWork.Jobs.Save();
                }

                return(Ok(new { message = "Success" }));
            }
            catch (AppException ex)
            {
                return(new { message = "Something went wrong please try again" });
            }
        }
Exemplo n.º 17
0
        public object Post([FromBody] UserDetailVm userDetailVm)
        {
            var identity  = HttpContext.User.Identity as ClaimsIdentity;
            var userClaim = _authService.GetClaim(identity);

            try
            {
                _logger.LogInfo($"{MethodInfoHelper.GetCurrentMethodName()} started.");
                var user = _authService.AuthorizeUser(Convert.ToInt32(userClaim[4].Value));
                if (user != null)
                {
                    var file   = userDetailVm.SelectedFile.Replace("data:application/pdf;base64,", String.Empty);
                    var data   = Convert.FromBase64String(file);
                    var stream = new MemoryStream(data);
                    userDetailVm.SelectedFile = _employeeDetail.CreateFile(userDetailVm.SelectedFileName, data);

                    var employeeDetail = _mapper.Map <UserDetail>(userDetailVm);
                    if (employeeDetail != null)
                    {
                        _unitOfWork.Employees.Insert(employeeDetail);
                        _unitOfWork.Employees.Save();
                    }
                    return(Ok(new { message = "Success" }));
                }
                else
                {
                    return(new { message = "Unauthorize" });
                }
            }
            catch (AppException ex)
            {
                _logger.LogError($"{MethodInfoHelper.GetCurrentMethodName()} failed.", ex);
                throw;
            }
            finally
            {
                _logger.LogInfo($"{MethodInfoHelper.GetCurrentMethodName()} ended.");
            }
        }
Exemplo n.º 18
0
        public object Register([FromBody] UserVm userVm)
        {
            try
            {
                _logger.LogInfo($"{MethodInfoHelper.GetCurrentMethodName()} started.");
                var userConfirmation = _registerService.CreateUser(userVm);

                if (!string.IsNullOrEmpty(userConfirmation.EmailAddress))
                {
                    return(Ok(new { message = "User was succesfully recorded!" }));
                }
            }
            catch (AppException ex)
            {
                _logger.LogError($"{MethodInfoHelper.GetCurrentMethodName()} failed.", ex);
                throw;
            }
            finally
            {
                _logger.LogInfo($"{MethodInfoHelper.GetCurrentMethodName()} ended.");
            }

            return(new { message = "Something went wrong please try again" });
        }
Exemplo n.º 19
0
        protected override void OnException(ExceptionContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            //If exception handled before, do nothing.
            //If this is child action, exception should be handled by main action.
            if (context.ExceptionHandled || context.IsChildAction)
            {
                base.OnException(context);
                return;
            }

            //Log exception
            if (_wrapResultAttribute == null || _wrapResultAttribute.LogError)
            {
                LogHelper.LogException(Logger, context.Exception);
            }

            // If custom errors are disabled, we need to let the normal ASP.NET exception handler
            // execute so that the user can see useful debugging information.
            if (!context.HttpContext.IsCustomErrorEnabled)
            {
                base.OnException(context);
                return;
            }

            // If this is not an HTTP 500 (for example, if somebody throws an HTTP 404 from an action method),
            // ignore it.
            if (new HttpException(null, context.Exception).GetHttpCode() != 500)
            {
                base.OnException(context);
                return;
            }

            //Check WrapResultAttribute
            if (_wrapResultAttribute == null || !_wrapResultAttribute.WrapOnError)
            {
                base.OnException(context);
                return;
            }

            //We handled the exception!
            context.ExceptionHandled = true;

            //Return an error response to the client.
            context.HttpContext.Response.Clear();
            context.HttpContext.Response.StatusCode = GetStatusCodeForException(context);
            context.Result = MethodInfoHelper.IsJsonResult(_currentMethodInfo)
                ? GenerateJsonExceptionResult(context)
                : GenerateNonJsonExceptionResult(context);

            // Certain versions of IIS will sometimes use their own error page when
            // they detect a server error. Setting this property indicates that we
            // want it to try to render ASP.NET MVC's error page instead.
            context.HttpContext.Response.TrySkipIisCustomErrors = true;

            //Trigger an event, so we can register it.
            EventBus.Trigger(this, new AbpHandledExceptionData(context.Exception));
        }
Exemplo n.º 20
0
        protected override void OnException(ExceptionContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            //如果异常已经处理,则什么都不做
            //如果这是子操作,则应由主操作处理异常。
            if (context.ExceptionHandled || context.IsChildAction)
            {
                base.OnException(context);
                return;
            }

            //Log exception
            if (_wrapResultAttribute == null || _wrapResultAttribute.LogError)
            {
                LogHelper.LogException(Logger, context.Exception);
            }

            // 如果禁用了自定义错误,我们需要让普通的ASP.NET异常处理程序
            //执行以便用户可以看到有用的调试信息。
            if (!context.HttpContext.IsCustomErrorEnabled)
            {
                base.OnException(context);
                return;
            }

            // If this is not an HTTP 500 (for example, if somebody throws an HTTP 404 from an action method),
            // ignore it.
            if (new HttpException(null, context.Exception).GetHttpCode() != 500)
            {
                base.OnException(context);
                return;
            }

            //Check WrapResultAttribute
            if (_wrapResultAttribute == null || !_wrapResultAttribute.WrapOnError)
            {
                base.OnException(context);
                return;
            }

            //We handled the exception!
            context.ExceptionHandled = true;

            //Return an error response to the client.
            context.HttpContext.Response.Clear();
            context.HttpContext.Response.StatusCode = GetStatusCodeForException(context);

            context.Result = MethodInfoHelper.IsJsonResult(_currentMethodInfo)
                ? GenerateJsonExceptionResult(context)
                : GenerateNonJsonExceptionResult(context);

            // Certain versions of IIS will sometimes use their own error page when
            // they detect a server error. Setting this property indicates that we
            // want it to try to render ASP.NET MVC's error page instead.
            context.HttpContext.Response.TrySkipIisCustomErrors = true;

            //Trigger an event, so we can register it.
            EventBus.Trigger(this, new AbpHandledExceptionData(context.Exception));
        }