public IHttpActionResult StopLiveStream()
        {
            try
            {
                CurrentSessionHandler session = new CurrentSessionHandler(HttpContext.Current.Session);

                if (String.IsNullOrWhiteSpace(session.Username))
                {
                    return(Ok(false));
                }

                Boolean result = AudioHandler.FlagForceStopStream(session.Username);
                if (result)
                {
                    _logger.LogInfo($"Flagged stream for user '{session.Username}' to be stopped.");
                }

                return(Ok(result));
            }
            catch (Exception ex)
            {
                String errMsg = "Exception in AudioController.StopLiveStream";
                _logger.LogError(ex, errMsg);

                return(InternalServerError(ex));
            }
        }
        public Task <Unit> Handle(HandleIncomingMessageCommand request, CancellationToken cancellationToken)
        {
            if (new List <string> {
                "hey", "/start"
            }.Contains(request.Update.Message?.Text, StringComparer.CurrentCultureIgnoreCase))
            {
                AppEntryFlow.InitRequestHandler(request.Update);
                return(Task.FromResult(Unit.Value));
            }

            if (CurrentSessionHandler.NextQuestion.Equals(default(KeyValuePair <Question, Action <string> >)))
            {
                return(Task.FromResult(Unit.Value));
            }

            if (CurrentSessionHandler.NextQuestion.Key == null)
            {
                return(Task.FromResult(Unit.Value));
            }

            if (CurrentSessionHandler.NextQuestion.Key.IsEndSignal || CurrentSessionHandler.NextQuestion.Value == null)
            {
                CurrentSessionHandler.EndSession(request.Update);
                return(Task.FromResult(Unit.Value));
            }

            HandleResponse(request.Update);
            return(Task.FromResult(Unit.Value));
        }
        private static void SetUnauthorized(ActionExecutingContext actionContext)
        {
            CurrentSessionHandler session = new CurrentSessionHandler(HttpContext.Current.Session);

            session.Reset();

            RouteValueDictionary loginRoute = new RouteValueDictionary
            {
                { "controller", "Account" },
                { "action", "Login" }
            };

            actionContext.Result = new RedirectToRouteResult(loginRoute);
        }
Example #4
0
        private static void SetInternalServerError(HttpActionContext actionContext)
        {
            try
            {
                CurrentSessionHandler session = new CurrentSessionHandler(HttpContext.Current.Session);
                session.Reset();
            }
            catch (Exception)
            {
                // Try to reset session, but could have been cause of this method call, so have to carry on.
            }

            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.InternalServerError);
        }
Example #5
0
        private static void SetUnauthorizedRedirect(HttpActionContext actionContext, String reasonPhrase)
        {
            CurrentSessionHandler session = new CurrentSessionHandler(HttpContext.Current.Session);

            session.Reset();

            HttpResponseMessage response = actionContext.Request.CreateResponse(HttpStatusCode.Redirect);

            response.ReasonPhrase = reasonPhrase;

            Uri redirectUri = new Uri(UrlHelper.GetLoginRedirectUrl());

            response.Headers.Location = redirectUri;
            actionContext.Response    = response;
        }
        public IHttpActionResult Logout()
        {
            try
            {
                CurrentSessionHandler session = new CurrentSessionHandler(HttpContext.Current.Session);
                session.Reset();

                return(Ok());
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error attempting to log out user.");
                return(InternalServerError());
            }
        }
        private LoginResponse GetLoginResponse()
        {
            CurrentSessionHandler session = new CurrentSessionHandler(HttpContext.Current.Session);
            User user = AccountRepo.GetKcUser(session.Username);

            LoginResponse result = new LoginResponse();

            result.FirstName         = user.FirstName;
            result.LastName          = user.LastName;
            result.Username          = user.UserName;
            result.Email             = user.Email;
            result.IsMilitaryDisplay = false;             // TODO Get from db
            result.Permissions       = session.LMRoles;

            return(result);
        }
        public IHttpActionResult DisconnectCall(String ani)
        {
            try
            {
                if (String.IsNullOrWhiteSpace(ani))
                {
                    return(BadRequest());
                }

                CircuitsInterop.Shutdown(ani);

                CurrentSessionHandler session = new CurrentSessionHandler(HttpContext.Current.Session);
                _logger.LogInfo($"User '{session.Username}' disconnected call on circuit '{ani}'");

                return(Ok());
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error trying to disconnect call");
                return(InternalServerError(ex));
            }
        }
Example #9
0
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            // Check if the class or method has AllowAnonymousAttribute defined.
            Boolean allowAnonymous = actionContext.ActionDescriptor.GetCustomAttributes <AllowAnonymousAttribute>().Count > 0 ||
                                     actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes <AllowAnonymousAttribute>().Count > 0;

            if (!allowAnonymous)
            {
                try
                {
                    CurrentSessionHandler session = new CurrentSessionHandler(HttpContext.Current.Session);

                    if (session.IsAuthenticated)
                    {
                        if (session.IsTokenExpired)
                        {
                            SetUnauthorizedRedirect(actionContext, Constants.UNAUTHORIZED_EXPIRED_TOKEN);
                        }
                        else if (!session.HasRoles(RequiredRoles))
                        {
                            SetUnauthorizedRedirect(actionContext, Constants.UNAUTHORIZED_REQUIRED_ROLES);
                        }
                    }
                    else
                    {
                        SetUnauthorizedRedirect(actionContext, Constants.UNAUTHORIZED_UNAUTHENTICATED);
                    }
                }
                catch (Exception ex)
                {
                    SetInternalServerError(actionContext);
                    actionContext.Response.Headers.Add("Error", ex.Message);
                    if (ex.InnerException != null)
                    {
                        actionContext.Response.Headers.Add("ErrorInner", ex.InnerException.Message);
                    }
                }
            }
        }
        public override void OnActionExecuting(ActionExecutingContext actionContext)
        {
            // Check if the class or method has AllowAnonymousAttribute defined.
            Boolean allowAnonymous = actionContext.ActionDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), false).Length > 0 ||
                                     actionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), false).Length > 0;

            if (!allowAnonymous)
            {
                try
                {
                    Boolean userAuthorized = false;

                    CurrentSessionHandler session = new CurrentSessionHandler(HttpContext.Current.Session);

                    if (session.IsAuthenticated && !session.IsTokenExpired)
                    {
                        userAuthorized = session.HasRoles(RequiredRoles);
                    }

                    if (!userAuthorized)
                    {
                        SetUnauthorized(actionContext);
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    if (ex.InnerException != null)
                    {
                        Debug.WriteLine(ex.InnerException.Message);
                    }

                    SetUnauthorized(actionContext);
                }
            }

            base.OnActionExecuting(actionContext);
        }
        public IHttpActionResult Facilities()
        {
            try
            {
                _logger.LogInfo("Getting list of current user's facilities...");

                CurrentSessionHandler session = new CurrentSessionHandler(HttpContext.Current.Session);

                DomainFacilityArguments args = new DomainFacilityArguments();
                args.DomainId = session.DomainId;

                // <SiteId, Name>
                Dictionary <String, Object> domainFacilities = DomainFacilityRepo.GetDomainFacilities(args);

                _logger.LogInfo($"Domain facilities retrieved {domainFacilities?.Count ?? 0}");

                return(Ok(domainFacilities));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Failed to load current user's domain facilities.");
                return(InternalServerError(ex));
            }
        }
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            Boolean allowAnonymous = actionContext.ActionDescriptor.GetCustomAttributes <System.Web.Http.AllowAnonymousAttribute>().Count > 0 ||
                                     actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes <System.Web.Http.AllowAnonymousAttribute>().Count > 0;

            if (!allowAnonymous)
            {
                CurrentSessionHandler session = new CurrentSessionHandler(HttpContext.Current.Session);

                try
                {
                    LoginArgs loginArgs;
                    String    authToken = null;
                    // Get request body object
                    using (StreamReader sr = new StreamReader(actionContext.Request.Content.ReadAsStreamAsync().Result))
                    {
                        sr.BaseStream.Position = 0;
                        String srStr = sr.ReadToEnd();
                        _logger.LogInfo(srStr);
                        loginArgs = JsonConvert.DeserializeObject <LoginArgs>(srStr);

                        if (!String.IsNullOrWhiteSpace(loginArgs?.Token))
                        {
                            _logger.LogInfo("Logging in Kinetic Console user with token...");
                            authToken = loginArgs.Token;
                        }
                    }

                    // ReSharper disable once ConstantConditionalAccessQualifier
                    if ((String.IsNullOrWhiteSpace(loginArgs?.Username) || String.IsNullOrWhiteSpace(loginArgs.Password)) && String.IsNullOrWhiteSpace(loginArgs?.Token))
                    {
                        SetUnauthorized(actionContext, session);
                    }
                    else
                    {
                        if (authToken == null)
                        {
                            LoginArguments loginArguments = new LoginArguments();
                            loginArguments.Username = loginArgs.Username;
                            loginArguments.Password = loginArgs.Password;

                            authToken = AccountRepo.RetrieveAuthToken(loginArguments);
                        }

                        LoginData loginData = AccountRepo.GetLoginData(authToken);

                        _logger.LogInfo($"LoginData retrieved: {JsonConvert.SerializeObject(loginData)}");

                        String[] userRoles = AccountRepo.GetKcUserPermissions(loginData.UserId).ToArray();

                        _logger.LogInfo($"User Roles retrieved: {JsonConvert.SerializeObject(userRoles)}");

                        Boolean userAuthorized = false;
                        if (!String.IsNullOrWhiteSpace(authToken))
                        {
                            session.LMRoles = userRoles;
                            userAuthorized  = session.HasRoles(RequiredRoles);
                            if (!userAuthorized)
                            {
                                _logger.LogWarning($"User does not have required roles.\r\n\tRequired Roles: {JsonConvert.SerializeObject(RequiredRoles)}");
                            }
                        }
                        else
                        {
                            _logger.LogWarning("User has invalid auth token");
                        }

                        if (userAuthorized)
                        {
                            // Give IIS a few seconds to create the session ID if it hasn't already been created
                            CookieHeaderValue sessionId = null;
                            Int32             tryCt     = 0;
                            while (tryCt < 10)
                            {
                                sessionId = actionContext.Request.Headers.GetCookies("ASP.NET_SessionId").FirstOrDefault();
                                if (sessionId != null)
                                {
                                    break;
                                }

                                Thread.Sleep(500);
                                tryCt++;
                            }

                            if (sessionId == null)
                            {
                                _logger.LogWarning("Unable to find ASP.NET SessionId");
                                SetUnauthorized(actionContext, session);
                            }
                            else
                            {
                                User user = AccountRepo.GetKcUser(loginData.UserId);

                                LMUser lmUser = new LMUser();
                                lmUser.AuthToken       = authToken;
                                lmUser.TokenExpiresUtc = DateTime.UtcNow.AddSeconds(loginData.ExpirationSeconds);
                                lmUser.IsAuthenticated = true;
                                lmUser.UserName        = loginData.UserId;
                                lmUser.Roles           = userRoles;
                                lmUser.SessionId       = sessionId["ASP.NET_SessionId"].Value;
                                lmUser.DomainId        = user.DomainId;

                                lmUser.DomainName = Caching.GetDomainName(user.DomainId);

                                session.AuthToken       = authToken;
                                session.TokenExpiresUtc = DateTime.UtcNow.AddSeconds(loginData.ExpirationSeconds);
                                session.IsAuthenticated = true;
                                session.Username        = loginData.UserId;
                                session.DomainId        = user.DomainId;

                                // Remove DomainUser if exists so Signal-R connection ID for this user is reset.
                                DomainUsersHandler.RemoveDomainUser(lmUser.UserName);

                                // Add new DomainUser
                                DomainUsersHandler.AddDomainUser(user.DomainId, lmUser);

                                _logger.LogInfo($"User '{lmUser.UserName}' successfully logged in");
                                _logger.LogInfo($"User Info: {JsonConvert.SerializeObject(lmUser)}");

                                base.OnAuthorization(actionContext);
                            }
                        }
                        else
                        {
                            SetUnauthorized(actionContext, session);
                            _logger.LogWarning($"User does not have required permissions. Required roles: {JsonConvert.SerializeObject(RequiredRoles)}");
                        }
                    }
                }
                catch (Exception ex)
                {
                    SetUnauthorized(actionContext, session);
                    actionContext.Response.Headers.Add("Error", ex.Message);
                    _logger.LogError(ex, "Error authenticating user");

                    if (ex.InnerException != null)
                    {
                        actionContext.Response.Headers.Add("ErrorInner", ex.InnerException.Message);
                        _logger.LogError(ex.InnerException, "Error authenticating user (Inner Exception)");
                    }
                }
            }
        }
        private void SetUnauthorized(HttpActionContext actionContext, CurrentSessionHandler session)
        {
            session.Reset();

            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
        }
        public HttpResponseMessage GetLiveStream(Int32 callId, Int32 lineId, Int32 unitId, String ani)
        {
            HttpResponseMessage response = Request.CreateResponse();

            try
            {
                Boolean startStreaming = false;
                String  argsStr        = $"args: lineId: {lineId}, unitId: {unitId}, ani: {ani}, callId: {callId}";
                UInt32  responseCode   = 0;

                // Only send monitor start request if the stream does not already exist.
                if (AudioHandler.IsExistingStream(callId))
                {
                    _logger.LogInfo($"No monitor start request sent. Stream already exists.\r\n\t{argsStr}");
                    startStreaming = true;
                }
                else
                {
                    MailmanResponse mailmanResponse = CircuitsInterop.MonitorRequestStart(callId, lineId, unitId, ani);
                    responseCode = CircuitsInterop.GetResponseCode(mailmanResponse);

                    //CircuitsInterop.MonitorRequestStart(callId, lineId, unitId, ani, false);
                    //responseCode = ResponseCodes.LM_OK;

                    _logger.LogInfo($"Monitor start request sent.\r\n\t{argsStr}\r\n\tResponseCode: {responseCode}");

                    switch (responseCode)
                    {
                    case ResponseCodes.LM_OK:
                        startStreaming = true;
                        AudioHandler.CreateNewStream(callId);

                        break;

                    case ResponseCodes.LM_INVALID_INFO:
                    case ResponseCodes.LM_MONITOR_REQ_INVALID:
                        response.StatusCode = HttpStatusCode.BadRequest;

                        break;

                    case ResponseCodes.LM_NO_MONITORING_SESSION:
                    case ResponseCodes.LM_INTERNAL_ERROR:
                    case ResponseCodes.LM_COMM_FAILURE:
                    case ResponseCodes.LM_NOT_REGISTERED:
                        response.StatusCode = HttpStatusCode.InternalServerError;

                        break;

                    default:
                        response.StatusCode = HttpStatusCode.InternalServerError;

                        break;
                    }
                }

                if (startStreaming)
                {
                    CurrentSessionHandler session = new CurrentSessionHandler(HttpContext.Current.Session);

                    response.Content = new PushStreamContent(
                        async(outputStream, httpContent, context) =>
                    {
                        await AudioHandler.WriteToAsync(outputStream, httpContent, context, callId, lineId, unitId, ani, session.Username);
                    },
                        new MediaTypeHeaderValue("audio/wav")
                        );

                    _logger.LogInfo($"User '{session.Username}' started streaming call ID: {callId}");

                    response.StatusCode = HttpStatusCode.OK;
                }
                else
                {
                    _logger.LogWarning($"Request Monitor Start returned response code: {responseCode}\r\n\t{argsStr}");
                }

                return(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Exception in GetLiveStream");
                response.StatusCode = HttpStatusCode.InternalServerError;
                response.Content    = new StringContent("Error retrieving live stream audio data");
                return(response);
            }
        }