상속: ApiController
예제 #1
0
        /// <summary>
        /// Validates the ModelState, apikey and referrer url and adds errors / messages
        /// to controller.ApiResponse as needed
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="modelState"></param>
        /// <returns></returns>
        internal virtual bool ValidateRequest(BaseApiController controller, ModelStateDictionary modelState)
        {
            var boolRtn = false;

            if (!modelState.IsValid)
            {
                controller.ApiResponse.AddRangeError(modelState.GetModelStateErrors(), HttpStatusCode.BadRequest);
                boolRtn = false;
            }
            var apiAccount     = controller._db.ApiAccounts.FirstOrDefault(a => a.ApiKey.Equals(ApiKey));
            var referrerForKey = string.Empty;

            if (apiAccount != null)
            {
                referrerForKey = apiAccount.RequestURL.ToString();
            }

            if (_IsValid &&
                ((referrerForKey == "*" ||
                  string.Equals(referrerForKey, controller.ApiRequest.Url.Authority, StringComparison.CurrentCultureIgnoreCase))))
            {
                boolRtn = true;
            }
            _IsValid = boolRtn;
            return(boolRtn);
        }
        public dynamic checkToken(string Token)
        {
            LystenEntities _db      = new LystenEntities();
            var            chkToken = _db.AppAccessTokens.AsEnumerable().Where(top => top.AuthToken == Token).FirstOrDefault();

            if (chkToken == null)
            {
                return(false);
            }
            User_Master model = _db.User_Master.Where(x => x.Id == chkToken.UserId).FirstOrDefault();

            if (chkToken.ExpiresOn <= DateTime.Now)
            {
                //TimeSpan t = new TimeSpan(1, 0, 0, 0, 0);
                //chkToken.ExpiresOn = DateTime.Now.Add(t);
                //_db.SaveChanges();
                BaseApiController.updatetoken = true;
                TokenDetails objToken = api.Helpers.AsyncHelpers.RunSync <TokenDetails>(() => BaseApiController.generatToken(model.Email, model.Password, model.DeviceToken));
                if (String.IsNullOrEmpty(objToken.error))
                {
                    BaseApiController.Add_UpdateToken(model.Id, objToken);
                    BaseApiController.accessToken = objToken.access_token;
                }
                return(true);
            }
            BaseApiController.updatetoken = false;
            BaseApiController.accessToken = "";
            return(true);
        }
예제 #3
0
        private bool AuthenticateUser(string credentialValues)
        {
            var isValid = false;

            try
            {
                var credentials = Encoding.GetEncoding("iso-8859-1").GetString(Convert.FromBase64String(credentialValues));
                var values      = credentials.Split(':');


                var user = new BaseApiController <SETUP_USER>()._repo.Get().Where(c => c.USER_NAME == values[0]).FirstOrDefault();
                if (user != null)
                {
                    var principal = new ClaimsPrincipal(new GenericIdentity(user.USER_NAME, null));
                    Thread.CurrentPrincipal = principal;
                    if (HttpContext.Current != null)
                    {
                        HttpContext.Current.User = principal;
                    }
                }
            }
            catch
            {
                isValid = false;
            }
            return(isValid);
        }
예제 #4
0
        /// <summary>
        /// Validates ModelState, apikey, referrer, pageNumber, and pageSize and adds errors / messages
        /// to controller.ApiResponse as needed
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="modelState"></param>
        /// <returns></returns>
        internal override bool ValidateRequest(BaseApiController controller, ModelStateDictionary modelState)
        {
            var boolRtn = base.ValidateRequest(controller, modelState);;

            // only continue if base request (ModelState, apikey, referrer) is valid
            if (boolRtn)
            {
                // set defaults
                PageNumber = PageNumber == null ? 1 : PageNumber;
                PageSize   = PageSize == null ? 5 : PageSize;

                // make sure nothing set to zero (prevent divide by zero errors down the line)
                if (PageNumber == 0)
                {
                    controller.ApiResponse.AddError("PageNumber cannot be zero", HttpStatusCode.BadRequest);
                    boolRtn = false;
                }
                if (PageSize == 0)
                {
                    controller.ApiResponse.AddError("PageSize cannot be zero", HttpStatusCode.BadRequest);
                    boolRtn = false;
                }
            }
            _IsValid = boolRtn;
            return(boolRtn);
        }
예제 #5
0
        protected virtual void SetupControllerFrorTest(BaseApiController sut)
        {
            //Set request context
            var userMock = new Mock <IOrganizationalUserContext>();

            sut.UserContext = userMock.Object;
            var httpRequestMessage = new HttpRequestMessage();
            var httpRequestContext = new HttpRequestContext
            {
                Configuration = new HttpConfiguration()
            };

            httpRequestMessage.Properties.Add(HttpPropertyKeys.RequestContextKey, httpRequestContext);
            sut.RequestContext = httpRequestContext;
            sut.Request        = httpRequestMessage;

            //Setup authenticated user
            var identity = new Mock <IIdentity>();
            var userId   = A <int>();

            identity.Setup(x => x.Name).Returns(userId.ToString());
            var principal = new Mock <IPrincipal>();

            principal.Setup(x => x.Identity).Returns(identity.Object);
            sut.User = principal.Object;
            CurrentOrganizationId = A <int>();
            KitosUser             = new User();
            userMock.Setup(x => x.UserId).Returns(KitosUser.Id);
        }
예제 #6
0
 protected void Application_Start()
 {
     AreaRegistration.RegisterAllAreas();
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
     BaseApiController.HideUnknownException(false);
 }
예제 #7
0
        private void ListenerCallback(IAsyncResult result)
        {
            if (_listener?.IsListening ?? false)
            {
                // Call EndGetContext to complete the asynchronous operation...
                var context = _listener.EndGetContext(result);

                // Obtain a response object.
                using var response = context.Response;

                try
                {
                    // Construct a response.
                    if (context.Request.Url?.Segments.Length > 1)
                    {
                        // segments: "/" ...
                        var segment = context.Request.Url.Segments[1].TrimEnd('/').ToLower();
                        if (_listener.IsListening)
                        {
                            switch (segment)
                            {
                            case "data":
                                HandleRequestForClockWebPageTimerData(context.Request, response);
                                break;

                            case "index":
                                HandleRequestForClockWebPage(context.Request, response);
                                break;

                            case "timers":
                                HandleRequestForTimersWebPage(context.Request, response);
                                break;

                            case "api":
                                HandleApiRequest(context.Request, response);
                                break;

                            default:
                                break;
                            }
                        }
                    }
                }
                catch (WebServerException ex)
                {
                    Log.Logger.Error(ex, "Web server error");
                    response.StatusCode = (int)WebServerErrorCodes.GetHttpErrorCode(ex.Code);
                    BaseApiController.WriteResponse(response, new ApiError(ex.Code));
                }
                catch (Exception ex)
                {
                    Log.Logger.Error(ex, "Web server error");
                    response.StatusCode = (int)WebServerErrorCodes.GetHttpErrorCode(WebServerErrorCode.UnknownError);
                    BaseApiController.WriteResponse(response, new ApiError(WebServerErrorCode.UnknownError));
                }
            }
        }
예제 #8
0
        public override ContainerModel RetrieveRootContainer(BaseApiController controller)
        {
            Logger.LogDebug(LogCategory.RestServe, Name, CacheTenantId);
            var root = base.RetrieveRootContainer(controller);

            root.Description = "Hijacked description";

            return(root);
        }
예제 #9
0
        internal static List <MethodInfo> GetPublicActions <TReturnType>(BaseApiController baseApiController)
        {
            var allMethodInfos = baseApiController.GetType().GetMethods();
            var publicActions  = allMethodInfos.Where(mi => mi.ReturnType == typeof(TReturnType) &&
                                                      mi.DeclaringType == typeof(BaseApiController) &&
                                                      mi.IsPublic);

            return(publicActions.ToList());
        }
예제 #10
0
        public AppVersionViewModel Get()
        {
            log.Info("哈哈,好的。 GetAppVersionCountOld");
            AppVersionViewModel model = new AppVersionViewModel();

            model.AppVersionCount = _AppVersion.GetAppVersionCountOld();
            BaseApiController.AppendHeaderTotal(_accessor, model.AppVersionCount);
            return(model);
        }
        public void Test_BaseApiController_CheckConnection()
        {
            // Setup.
            BaseApiController controllerUnderTest = new BaseApiController();

            // Test the Controller method. Did it resond as we expect.
            if (!controllerUnderTest.CheckConnection())
            {
                Assert.Fail("Controller failed to respond correctly.");
            }
        }
        public static void Authorize(string token, BaseApiController controller)
        {
            var user = WindsorBootstrapper.Container.Resolve <ISystemUserLogic>().ValidateAuthenticationToken(token);

            if (controller == null)
            {
                return;
            }

            controller.CurrentUser = user;
        }
예제 #13
0
        public static void Authorize(string token, string language, BaseApiController controller)
        {
            ExecuteManager.Execute(() =>
            {
                var systemUser = ValidateToken(token);

                if (controller == null)
                {
                    return;
                }
                controller.CurrentUser = systemUser;
            });
        }
        public void Test_BaseApiController_GetDefault()
        {
            // Setup/
            BaseApiController controllerUnderTest = new BaseApiController();

            // Test the Controller method.
            string response = controllerUnderTest.Get();

            // Is the output as we expected.
            if (string.IsNullOrEmpty(response))
            {
                Assert.Fail("No response from Controller.");
            }
        }
예제 #15
0
        public static void SetupControllerContext(BaseApiController controller, HttpMethod method)
        {
            var request = new HttpRequestMessage(method, "http://localhost/api/Test/Validate");
            // controller.Request = new HttpRequestMessage(method, "http://localhost");
            //controller.Request.Headers.Add("Accept", "application/json");
            //var configuration = new System.Web.Http.HttpConfiguration(new System.Web.Http.HttpRouteCollection());
            var configuration = new HttpConfiguration();

            var route = configuration.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{action}");
            var routeData = new HttpRouteData(route, new HttpRouteValueDictionary(new { controller = "Test", action = "Validate" }));

            controller.ControllerContext = new HttpControllerContext(configuration, routeData, request);
            controller.Request = request;
            controller.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = configuration;
        }
        public void Test_BaseApiController_GetWithId()
        {
            // Setup.
            int idParameter = 7;
            BaseApiController controllerUnderTest = new BaseApiController();

            // Test the Controller method.
            string response = controllerUnderTest.Get(idParameter);

            // Does the output contain what we expected, roughly as text-text doesn't really matter, just that it incorperate the Id back.
            if (!response.Contains(idParameter.ToString()))
            {
                Assert.Fail("Controller failed to incorperate the parameter in the response.");
            }
        }
예제 #17
0
        public static BaseApiController SetUserId(this BaseApiController controller, string userId)
        {
            var userClaims = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, userId) }, "mock"));

            if (controller.ControllerContext.HttpContext == null)
            {
                controller.ControllerContext.HttpContext = new DefaultHttpContext {
                    User = userClaims
                };
                return(controller);
            }

            controller.ControllerContext.HttpContext.User = userClaims;
            return(controller);
        }
예제 #18
0
        internal override bool ValidateRequest(BaseApiController controller, ModelStateDictionary modelState)
        {
            var boolRtn = base.ValidateRequest(controller, modelState);

            if (boolRtn)
            {
                if (controller._db.Posts.All(p => p.ID != Post.ID))
                {
                    controller.ApiResponse.Messages.Add(ErrorMessages.PostNotFound(Post.ID));
                    controller.ApiResponse.HttpStatusCode = HttpStatusCode.OK;
                    boolRtn = false;
                }
            }

            return(boolRtn);
        }
예제 #19
0
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            // Etikette A ve U atandı.
            var actionRoles = Roles;

            var username = HttpContext.Current.User.Identity.Name;
            // httpcontxt geçerli user alıp rolunu kontrol ediyoruzu .Roles içinde varsa yetkilidir.
            var user = new BaseApiController <SETUP_USER>()._repo.Get().Where(c => c.USER_NAME == username).FirstOrDefault();

            if (user != null && Roles.Contains(user.USER_ROLE))
            {
            }
            else
            {
                actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
            }
        }
예제 #20
0
        /// <summary>
        /// Validates ModelState, username, apikey, and referrer and adds errors / messages
        /// to controller.ApiResponse as needed
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="modelState"></param>
        /// <returns></returns>
        internal override bool ValidateRequest(BaseApiController controller, ModelStateDictionary modelState)
        {
            var boolRtn = base.ValidateRequest(controller, modelState);

            // only validate the username if base request (apikey and referrer) are valid
            if (boolRtn)
            {
                // make sure username exists
                if (string.IsNullOrEmpty(Username) || !controller._db.Users.Any(u => u.UserName == Username))
                {
                    controller.ApiResponse.AddError(ErrorMessages.UsernameNotFound(Username), HttpStatusCode.OK);
                    boolRtn = false;
                }
            }

            return(boolRtn);
        }
예제 #21
0
        protected virtual void LoadUser(AuthenticationIdentity user, HttpActionContext actionContext)
        {
            if (HttpContext.Current != null)
            {
                BaseApiController baseApiController = actionContext.ControllerContext.Controller as BaseApiController;

                if (baseApiController != null)
                {
                    // Chave padrão do cache - nome do método + parâmetros.
                    string chave = RetornaChaveCache_LoadUser(user);
                    object cache = HttpContext.Current.Cache[chave];

                    if (cache == null)
                    {
                        #region Load user values

                        UsuarioWEB userLogged = new UsuarioWEB();

                        // Carrega usuário na session através do ticket de authenticação
                        userLogged.Usuario = new SYS_Usuario
                        {
                            ent_id = user.Entity
                            ,
                            usu_login = user.Login
                        };
                        SYS_UsuarioBO.GetSelectBy_ent_id_usu_login(userLogged.Usuario);

                        userLogged.Grupo = SYS_GrupoBO.GetEntity(new SYS_Grupo {
                            gru_id = user.Group
                        });

                        baseApiController.__userLogged = userLogged;

                        #endregion

                        HttpContext.Current.Cache.Insert(chave, userLogged, null, DateTime.Now.AddMinutes(GestaoEscolarUtilBO.MinutosCacheMedio)
                                                         , System.Web.Caching.Cache.NoSlidingExpiration);
                    }
                    else
                    {
                        baseApiController.__userLogged = cache as UsuarioWEB;
                    }
                }
            }
        }
        /// <summary>
        /// Registers the notification.
        /// </summary>
        /// <param name="appState">State of the application.</param>
        /// <exception cref="System.Configuration.ConfigurationErrorsException">AnalyticsNotifications Service URL setting is null or empty</exception>
        public void RegisterNotification(AppState appState)
        {
            try
            {
                //Adding to group by projectId
                Nlog.Log(LogLevel.Trace, "PC Web - Start addining connection into group");
                Groups.Add(Context.ConnectionId, appState.ProjectId.ToString(CultureInfo.InvariantCulture));
                Nlog.Log(LogLevel.Trace, "PC Web - Connection added to group");

                if (BaseApiController.IsMockMode())
                {
                    MockWorkflowState.WorkflowStateChanged += OnMockWorkflowStateChanged;
                }
                else
                {
                    Nlog.Log(LogLevel.Trace, "PC Web - Fired RegisterNotification");
                    var serviceUri = ConfigurationManager.AppSettings.Get(AnalyticsNotifications);
                    if (String.IsNullOrEmpty(serviceUri))
                    {
                        throw new ConfigurationErrorsException("AnalyticsNotifications Service URL setting is null or empty");
                    }
                    var hubConnection   = new HubConnection(serviceUri);
                    var serviceHubProxy = hubConnection.CreateHubProxy("WorkflowStateServiceHub");

                    //Handle incoming calls from service
                    //BroadcastWorkflowState for updated project
                    serviceHubProxy.On <long, List <AnalyticsWorkflowState> >("UpdateWorkflowState", BroadcastWorkflowState);

                    //Signalr service connection
                    Nlog.Log(LogLevel.Trace, "PC Web - Starting service signalr connection");
                    hubConnection.Start().ContinueWith(task => {}).Wait();
                    Nlog.Log(LogLevel.Trace, "PC Web - Service signalr connection success");

                    //Register for notifications
                    Nlog.Log(LogLevel.Trace, "PC Web - Invoking service signalr RegisterNotification");
                    serviceHubProxy.Invoke("RegisterNotification", appState.MatterId, appState.ProjectId)
                    .ContinueWith(task => {}).Wait();
                    Nlog.Log(LogLevel.Trace, "PC Web - Invoked service signalr RegisterNotification");
                }
            }
            catch (Exception ex)
            {
                Nlog.Log(LogLevel.Error, ex.GetBaseException());
            }
        }
예제 #23
0
        public Identity GetIdentity(string token, HttpActionContext actionContext)
        {
            BaseApiController controller = (BaseApiController)actionContext.ControllerContext.Controller;

            Identity identity;

            using (var repository = new Repository <Identity>(controller.Context, false))
            {
                identity = repository
                           .All()
                           .Where(e => e.Access == token)
                           .Include(e => e.User.Credential.ApiKey)
                           .Include(e => e.Client.ApiKey)
                           .SingleOrDefault();
            }

            return(identity);
        }
예제 #24
0
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            string domainName = actionContext.Request.Headers.Referrer.Authority;

            if (domainName.ToLower().Contains("localhost"))
            {
                domainName = string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["LocalDomainName"]) ? "RVMELB.qaeupgrade.cendyn.com" : ConfigurationManager.AppSettings["LocalDomainName"];
            }

            var domaininfo = DependencyResolver.Current.GetService(typeof(DomainInformationModel)) as DomainInformationModel;

            domaininfo.DomainName = domainName;
            domaininfo.IsSecure   = true;

            hotelService = DependencyResolver.Current.GetService(typeof(IHotelService)) as IHotelService;
            controller   = actionContext.ControllerContext.Controller as BaseApiController;
            controller.HotelInformation = hotelService.GetHotelByDomain("http://" + domainName);
        }
예제 #25
0
        public User GetUser(HttpActionContext actionContext)
        {
            BaseApiController controller = (BaseApiController)actionContext.ControllerContext.Controller;

            User user;

            using (var repository = new Repository <User>(controller.Context, false))
            {
                user = repository
                       .All()
                       .Where(e => e.Credential.ApiKey.Key == this.Identity.User.Credential.ApiKey.Key)
                       .Include(e => e.Groups.Select(p => p.Permissions))
                       .Include(e => e.Permissions)
                       .Single();
            }

            return(user);
        }
        private void InitializeApiController(BaseApiController baseApiController)
        {
            HttpConfiguration  httpConfig  = new HttpConfiguration();
            HttpRequestMessage httpRequest = new HttpRequestMessage();

            httpRequest.Headers.Add("account", "1");
            httpRequest.Headers.Add("token", "abcde");
            httpRequest.Headers.Add("ip", "127.0.0.1");

            var routeData = new HttpRouteData(new HttpRoute(""));

            baseApiController.ControllerContext = new HttpControllerContext(httpConfig, routeData, httpRequest)
            {
                Configuration = httpConfig
            };

            HttpContext.Current = new HttpContext(new HttpRequest(null, "http://localhost:52552", null), new HttpResponse(null));
        }
예제 #27
0
 private static void AddSupportCode(HttpActionContext actionContext, BaseApiController baseController)
 {
     try
     {
         string supportCode;
         if (TryGetSupportCode(baseController.Runtime, out supportCode))
         {
             actionContext.Response.Headers.Add("X-Error", supportCode);
         }
         else
         {
             actionContext.Response.Headers.Add("X-Error", baseController.Runtime.InstanceId.ToString());
         }
     }
     catch (Exception ex)
     {
         ex.Log();
     }
 }
        public override void OnAuthorization(HttpActionContext actionContext)


        {
            if (actionContext.Request.Headers.Authorization == null)
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);

                /*
                 * if (actionContext.Response.StatusCode == HttpStatusCode.Unauthorized && !actionContext.Response.Headers.Contains("WWW-Authenticate"))
                 * {
                 *  actionContext.Response.Headers.Add("WWW-Authenticate", "Basic");
                 * }
                 */
            }
            else
            {
                string authenticationToken       = actionContext.Request.Headers.Authorization.Parameter;
                string decodeauthenticationToken = Encoding.UTF8.GetString(Convert.FromBase64String(authenticationToken));
                //  var values = decodeauthenticationToken.Split(':');
                string[] values   = decodeauthenticationToken.Split(':');
                string   username = values[0];
                string   password = values[1];

                var user = new BaseApiController <SETUP_USER>()._repo.Get().Where(c => c.USER_NAME == username && c.USER_PASSWORD == password);
                if (user != null)
                {
                    var principal = new GenericPrincipal(new GenericIdentity(username), null);
                    Thread.CurrentPrincipal = principal;
                    if (HttpContext.Current != null)
                    {
                        HttpContext.Current.User = principal;
                    }
                }
                else
                {
                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
                }
            }
            base.OnAuthorization(actionContext);
        }
        public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            var principal = context.HttpContext.User;
            var user      = WebApiHelper.GetUser(principal, _config);

            var idParam     = context.ActionDescriptor.Parameters.OfType <ControllerParameterDescriptor>().SingleOrDefault(x => x.ParameterInfo.GetCustomAttributes(typeof(PlayerIdAttribute), false).SingleOrDefault() != null);
            var idParamName = idParam?.Name;
            var idObj       = (object)null;

            if (idParamName != null)
            {
                context.RouteData.Values?.TryGetValue(idParamName, out idObj);
            }

            var hasAccess = BaseApiController.HasFeatureAccess(_config, principal, _requirement.FeatureGroup, _requirement.FeatureName, idParamName != null ? idObj?.ToString() : user?.SteamId);

            if (!hasAccess)
            {
                context.Result = new ChallengeResult();
            }
        }
예제 #30
0
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            string authorizationToken = BaseApiController.GetAuthorizationToken(actionContext.Request.Headers);

            bool authorized = AppBusiness.Security.IsTokenActive(authorizationToken);

            if (!authorized)
            {
                BaseApiResult response = new BaseApiResult();

                response.Error   = true;
                response.Code    = 401;
                response.Message = "Authorization token invalid.";

                string json = JsonConvert.SerializeObject(response);

                actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
                {
                    Content = new StringContent(json, Encoding.UTF8, "application/json")
                };
            }
        }
예제 #31
0
 public QuickNoteService(BaseApiController controller)
     : base(controller)
 {
 }
예제 #32
0
 public AttributeProviderService(BaseApiController controller)
     : base(controller)
 {
 }
 public void TestSetupController(BaseApiController controller)
 {
     controller.Request = new HttpRequestMessage();
     controller.Request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration());
 }