public AuthenticationTester()
 {
     url               = string.Empty;
     usernames         = new List <string>();
     passwords         = new List <string>();
     successFilter     = new Filter();
     authentication    = AuthenticationMethods.BasicAuth;
     authForm          = new AuthenticationForm();
     validCombinations = new List <ValidCombination>();
     finished          = false;
     userStopped       = false;
     Work              = new Queue <CreateWebrequest>();
 }
Exemplo n.º 2
0
 /// <summary>
 /// Convert back to service model
 /// </summary>
 /// <returns></returns>
 public EndpointRegistrationModel ToServiceModel()
 {
     return(new EndpointRegistrationModel {
         Id = Id,
         Endpoint = Endpoint?.ToServiceModel(),
         EndpointUrl = EndpointUrl,
         AuthenticationMethods = AuthenticationMethods?
                                 .Select(p => p?.ToServiceModel()).ToList(),
         SecurityLevel = SecurityLevel,
         SiteId = SiteId,
         Certificate = Certificate
     });
 }
 public AuthenticationTester()
 {
     url = string.Empty;
     usernames = new List<string>();
     passwords = new List<string>();
     successFilter = new Filter();
     authentication = AuthenticationMethods.BasicAuth;
     authForm = new AuthenticationForm();
     validCombinations = new List<ValidCombination>();
     finished = false;
     userStopped = false;
     Work = new Queue<CreateWebrequest>();
 }
Exemplo n.º 4
0
        private void update(object state)
        {
            var sessionProvider = ProviderFactory.Instance.CreateSessionServiceProvider();

            if (SignalRNotifier.Instance.usersThatAreAlreadyReceievingNotifications.Contains(userLoginEmail))
            {
                try
                {
                    var session = AuthenticationMethods.GetSessionData(sessionToken);
                    if (session == null || !sessionProvider.CheckIfSessionIsValid(sessionToken) || sessionProvider.GetSessionInformation(sessionToken) == null || !sessionProvider.CheckIfSessionExists(sessionToken))
                    {
                        GlobalHost.ConnectionManager.GetHubContext <NotificationsHub>().Clients.Group(userLoginEmail).sessionExpired(new { redirectTo = GlobalProperties.LOGIN_PAGE });
                        SignalRNotifier.Instance.usersThatAreAlreadyReceievingNotifications.Remove(userLoginEmail);
                        SignalRNotifier.Instance.usersThatAreAlreadyReceievingNewDashboardData.Remove(userLoginEmail);
                        notificationTimer.Dispose();
                    }

                    /*
                     * var notificationsTransaction = new TransactionalInformation();
                     * var response = mainDataservice.GetNotificationData(connectionString, sessionToken, out notificationsTransaction);
                     *
                     * if (notificationsTransaction.ReturnStatus)
                     * {
                     *  if (!SignalRNotifier.Instance.lastSentNotificationData.ContainsKey(sessionToken) || SignalRNotifier.Instance.lastSentNotificationData[sessionToken].AnyTileDataChanged(response))
                     *  {
                     *
                     *      if (!SignalRNotifier.Instance.lastSentNotificationData.ContainsKey(sessionToken))
                     *          SignalRNotifier.Instance.lastSentNotificationData.Add(sessionToken, response);
                     *      else
                     *          SignalRNotifier.Instance.lastSentNotificationData[sessionToken] = response;
                     *
                     *      GlobalHost.ConnectionManager.GetHubContext<NotificationsHub>().Clients.Group(userLoginEmail).updateNotifications(response);
                     *
                     *  }
                     * }
                     */
                }
                catch (Exception ex)
                {
                    GlobalHost.ConnectionManager.GetHubContext <NotificationsHub>().Clients.Group(userLoginEmail).sessionExpired(new { redirectTo = GlobalProperties.LOGIN_PAGE });
                    SignalRNotifier.Instance.usersThatAreAlreadyReceievingNotifications.Remove(userLoginEmail);
                    SignalRNotifier.Instance.usersThatAreAlreadyReceievingNewDashboardData.Remove(userLoginEmail);
                    notificationTimer.Dispose();
                }
            }
            else
            {
                SignalRNotifier.Instance.usersThatAreAlreadyReceievingNewDashboardData.Remove(userLoginEmail);
                notificationTimer.Dispose();
            }
        }
Exemplo n.º 5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            OtherMethods.ActiveRightMenuStyleChanche("hlNewsFeed", this.Page);
            Page.Title = PagesTitles.ManagerNewsFromFeedView + BackendHelper.TagToValue("page_title_part");

            if (Request.Params["title"] != null)
            {
                var userInSession = (Users)Session["userinsession"];
                var news          = new News {
                    TitleUrl = Request.Params["title"].ToString()
                };
                news.GetByTitleUrl();
                if (!IsPostBack && news.NewsTypeID == 2)
                {
                    lblTitle.Text      = news.Title;
                    lblBody.InnerHtml  = news.Body;
                    lblCreateDate.Text = news.CreateDate.ToString();

                    //если новость просмотрел клиент - записываем ему просмотр и обновляем список непрочтенных новостей
                    if (userInSession.Role == Users.Roles.User.ToString())
                    {
                        var dm = new DataManager();
                        var isUserViewCount = Convert.ToInt32(
                            dm.QueryWithReturnDataSet(
                                String.Format("select count(*) from `usertonewsview` WHERE `UserID` = {0} AND `NewsID` = {1};", userInSession.ID, news.ID)
                                ).Tables[0].Rows[0][0].ToString()
                            );
                        //записываем данные о инфе, что усер просмотрел новость
                        if (isUserViewCount == 0)
                        {
                            var userView = new UserToNewsView {
                                UserID = userInSession.ID, NewsID = news.ID
                            };
                            userView.Create();
                        }
                        //пересчитываем просмотренные новости
                        //обновляем\задаем авторизационную куку с данными пользователя
                        AuthenticationMethods.SetUserCookie(userInSession);
                    }
                }
                else
                {
                    //Response.Redirect("~/UserUI/NewsFeedView.aspx");
                }
            }
            else
            {
                //Response.Redirect("~/UserUI/NewsFeedView.aspx");
            }
        }
Exemplo n.º 6
0
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            //òóò ïðîâåðÿåì, åëè ñåèÿ ðàçðóøåíà îîòâåòñòâóþò ëè êóêè íóæíîìó ïîëüçîâàòåëþ. Åñëè ñîîòâåòòâóþò - ïîäíèìàåì ïîëüçîâàòåëÿ. Òàêèì îáðàçîì ïî êóêè ñåèÿ æèâåò ïîêà êóêè âåðû.
            var user = (Users)Session["userinsession"];

            if (user == null)
            {
                var httpCookie = Request.Cookies["_AUTHGRB"];
                if (httpCookie != null)
                {
                    if (httpCookie.Value.Length > 33)
                    {
                        var    authCookie  = httpCookie.Value;
                        var    base64Login = authCookie.Remove(0, 32);
                        byte[] byteLogin   = Convert.FromBase64String(base64Login);
                        var    login       = System.Text.Encoding.UTF8.GetString(byteLogin);
                        var    password    = authCookie.Substring(0, 32);
                        var    userOld     = new Users {
                            Login = login
                        };
                        userOld.GetByLogin();
                        if ((login == userOld.Login) && (password == userOld.Password))
                        {
                            if (userOld.Status == 1)
                            {
                                //ðàçðóøàåì êóêè
                                var cookie = new HttpCookie("_AUTHGRB")
                                {
                                    Expires = DateTime.Now.AddDays(-1000)
                                };
                                Response.Cookies.Add(cookie); //ðàçðóøàåì ñåññèþ
                                Session["userinsession"] = null;
                                Response.Redirect("~/");
                            }
                            else
                            {
                                //проверка на доступ по WhiteList
                                AuthenticationMethods.CheckAccessByWhiteList(userOld, HttpContext.Current);

                                //обновляем\задаем авторизационную куку с данными пользователя
                                AuthenticationMethods.SetUserCookie(userOld);
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 7
0
        /// <inheritdoc/>
        public override bool Equals(object obj)
        {
            var registration = obj as EndpointRegistration;

            return(base.Equals(registration) &&
                   DiscovererId == registration.DiscovererId &&
                   SupervisorId == registration.SupervisorId &&
                   ApplicationId == registration.ApplicationId &&
                   EndpointUrlLC == registration.EndpointUrlLC &&
                   SupervisorId == registration.SupervisorId &&
                   SecurityLevel == registration.SecurityLevel &&
                   SecurityPolicy == registration.SecurityPolicy &&
                   SecurityMode == registration.SecurityMode &&
                   AuthenticationMethods.DecodeAsList().SetEqualsSafe(
                       AuthenticationMethods.DecodeAsList(), JToken.DeepEquals));
        }
        public override async Task AuthenticationCheck(string routePath)
        {
            var authMethod = AuthenticationMethods.FirstOrDefault(x => x.Path.Equals(routePath));

            if (authMethod != null)
            {
                var token       = HttpContextExt.Current.Headers.FirstOrDefault(x => x.Key == "Authentication").Value;
                var accountInfo = await GetAccountInfo(HttpContextExt.Current.RequestService.Resolve <IStateManager>());

                HttpContextExt.SetUser(accountInfo);
                if (!HttpContextExt.Current.User.IgnorePermission && authMethod.CheckPermission && !HttpContextExt.Current.GetAuthIgnore() && HttpContextExt.Current.User.Permissions != null && !HttpContextExt.Current.User.Permissions.Contains(routePath))
                {
                    throw new InfrastructureException("当前登录用户缺少使用该接口的必要权限,请重试!");
                }
            }
        }
Exemplo n.º 9
0
        /// <inheritdoc/>
        public override bool Equals(object obj)
        {
            var registration = obj as EndpointRegistration;

            return(base.Equals(registration) &&
                   (Activated ?? false) == (registration.Activated ?? false) &&
                   EndpointUrlLC == registration.EndpointUrlLC &&
                   SupervisorId == registration.SupervisorId &&
                   JToken.DeepEquals(Credential, registration.Credential) &&
                   State == registration.State &&
                   CredentialType == registration.CredentialType &&
                   SecurityLevel == registration.SecurityLevel &&
                   SecurityPolicy == registration.SecurityPolicy &&
                   SecurityMode == registration.SecurityMode &&
                   AuthenticationMethods.DecodeAsList().SetEqualsSafe(
                       AuthenticationMethods.DecodeAsList(), JToken.DeepEquals));
        }
Exemplo n.º 10
0
    /// <summary>
    /// Creates an IdentityServer claims principal
    /// </summary>
    /// <returns></returns>
    /// <exception cref="ArgumentNullException"></exception>
    public ClaimsPrincipal CreatePrincipal()
    {
        if (SubjectId.IsMissing())
        {
            throw new ArgumentException("SubjectId is mandatory", nameof(SubjectId));
        }
        var claims = new List <Claim> {
            new Claim(JwtClaimTypes.Subject, SubjectId)
        };

        if (DisplayName.IsPresent())
        {
            claims.Add(new Claim(JwtClaimTypes.Name, DisplayName));
        }

        if (IdentityProvider.IsPresent())
        {
            claims.Add(new Claim(JwtClaimTypes.IdentityProvider, IdentityProvider));
        }

        if (Tenant.IsPresent())
        {
            claims.Add(new Claim(IdentityServerConstants.ClaimTypes.Tenant, Tenant));
        }

        if (AuthenticationTime.HasValue)
        {
            claims.Add(new Claim(JwtClaimTypes.AuthenticationTime, new DateTimeOffset(AuthenticationTime.Value).ToUnixTimeSeconds().ToString()));
        }

        if (AuthenticationMethods.Any())
        {
            foreach (var amr in AuthenticationMethods)
            {
                claims.Add(new Claim(JwtClaimTypes.AuthenticationMethod, amr));
            }
        }

        claims.AddRange(AdditionalClaims);

        var id = new ClaimsIdentity(claims.Distinct(new ClaimComparer()), Constants.IdentityServerAuthenticationType, JwtClaimTypes.Name, JwtClaimTypes.Role);

        return(new ClaimsPrincipal(id));
    }
 /// <summary>
 /// Convert to service model
 /// </summary>
 /// <returns></returns>
 public EndpointInfoModel ToServiceModel()
 {
     return(new EndpointInfoModel {
         ApplicationId = ApplicationId,
         Registration = new EndpointRegistrationModel {
             Id = DeviceId,
             SiteId = string.IsNullOrEmpty(SiteId) ?
                      null : SiteId,
             SupervisorId = string.IsNullOrEmpty(SupervisorId) ?
                            null : SupervisorId,
             Certificate = Certificate.DecodeAsByteArray(),
             AuthenticationMethods = AuthenticationMethods?.DecodeAsList(j =>
                                                                         j.ToObject <AuthenticationMethodModel>()),
             SecurityLevel = SecurityLevel,
             EndpointUrl = string.IsNullOrEmpty(EndpointRegistrationUrl) ?
                           (string.IsNullOrEmpty(EndpointUrl) ?
                            EndpointUrlLC : EndpointUrl) : EndpointRegistrationUrl,
             Endpoint = new EndpointModel {
                 Url = string.IsNullOrEmpty(EndpointUrl) ?
                       EndpointUrlLC : EndpointUrl,
                 AlternativeUrls = AlternativeUrls?.DecodeAsList().ToHashSetSafe(),
                 User = CredentialType == null ? null :
                        new CredentialModel {
                     Value = Credential,
                     Type = CredentialType == Models.CredentialType.None ?
                            null : CredentialType
                 },
                 SecurityMode = SecurityMode == Models.SecurityMode.Best ?
                                null : SecurityMode,
                 SecurityPolicy = string.IsNullOrEmpty(SecurityPolicy) ?
                                  null : SecurityPolicy,
                 ClientCertificate = ClientCertificate.DecodeAsByteArray(),
                 ServerThumbprint = ServerThumbprint.DecodeAsByteArray()
             }
         },
         ActivationState = ActivationState,
         NotSeenSince = NotSeenSince,
         EndpointState = ActivationState == EndpointActivationState.ActivatedAndConnected ?
                         State : (EndpointConnectivityState?)null,
         OutOfSync = Connected && !_isInSync ? true : (bool?)null
     });
 }
Exemplo n.º 12
0
        public IIkeV1 GetIkeV1Instance(AuthenticationMethods authMethods, HashFunction hash)
        {
            var sha  = _shaFactory.GetShaInstance(hash);
            var hmac = _hmacFactory.GetHmacInstance(hash);

            switch (authMethods)
            {
            case AuthenticationMethods.Dsa:
                return(new DsaIkeV1(hmac));

            case AuthenticationMethods.Pke:
                return(new PkeIkeV1(hmac, sha));

            case AuthenticationMethods.Psk:
                return(new PskIkeV1(hmac));

            default:
                throw new ArgumentException("No such authentication mode");
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (_isDisposed)
            {
                return;
            }

            if (disposing)
            {
                if (AuthenticationMethods != null)
                {
                    foreach (var authenticationMethods in AuthenticationMethods.OfType <IDisposable>())
                    {
                        authenticationMethods.Dispose();
                    }
                }

                _isDisposed = true;
            }
        }
Exemplo n.º 14
0
        private void btnSaveUser_Click(object sender, EventArgs e)
        {
            if (_globalState == State.UserManagement_AddUser)
            {
                string name  = tbxUserName.Text;
                string phone = tbxUserPhone.Text;
                User.PermissionLevels perm = ExtractPermissionLevel(cbxUserPermission);
                AuthenticationMethods auth = ExtractAuthenticationMethods(cbxPrimAuth, cbxSecAuth);
                _selectedUser = User.Create(name, perm, phone, null, auth);
            }
            else if (_globalState == State.UserManagement)
            {
                _selectedUser.Name                  = tbxUserName.Text;
                _selectedUser.PhoneNumber           = tbxUserPhone.Text;
                _selectedUser.PermissionLevel       = ExtractPermissionLevel(cbxUserPermission);
                _selectedUser.AuthenticationMethods = ExtractAuthenticationMethods(cbxPrimAuth, cbxSecAuth);
            }

            _globalState = State.UserManagement;
            populateUsers(null, EventArgs.Empty);
            UpdateComponents();
        }
Exemplo n.º 15
0
        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called.
            if (!_isDisposed)
            {
                // If disposing equals true, dispose all managed
                // and unmanaged resources.
                if (disposing)
                {
                    // Dispose managed resources.
                    if (AuthenticationMethods != null)
                    {
                        foreach (var authenticationMethods in AuthenticationMethods.OfType <IDisposable>())
                        {
                            authenticationMethods.Dispose();
                        }
                    }
                }

                // Note disposing has been done.
                _isDisposed = true;
            }
        }
Exemplo n.º 16
0
        public void Page_Load(object sender, EventArgs e)
        {
            Page.Title = PagesTitles.ManagerDefaultTitle + BackendHelper.TagToValue("page_title_part");
            OtherMethods.ActiveRightMenuStyleChanche("hlMain", this.Page);
            var user = (Users)Session["userinsession"];

            lblUserName.Text = user.Name;
            lblUID.Text      = user.ID.ToString();
            lblLogin.Text    = user.Login;
            lblEmail.Text    = user.Email;
            lblRole.Text     = user.RussRole;

            var userInSession = (Users)Session["userinsession"];
            var rolesList     = Application["RolesList"] as List <Roles>;
            var currentRole   = (Roles)rolesList.SingleOrDefault(u => u.Name.ToLower() == userInSession.Role.ToLower());

            if (currentRole.Name == Users.Roles.SuperAdmin.ToString())
            {
                lbRestartSubMemcache.Visible = true;
            }
            var dm = new DataManager();

            lblAllUsers.Text =
                MoneyMethods.MoneySeparator(dm.QueryWithReturnDataSet("SELECT COUNT(*) FROM `users` WHERE `Role` = 'User';").Tables[0].Rows[0][0].ToString());
            lblBlockedUsers.Text =
                MoneyMethods.MoneySeparator(dm.QueryWithReturnDataSet("SELECT COUNT(*) FROM `users` WHERE `Role` = 'User' AND `Status` = 3;").Tables[0].Rows[0][0].ToString());
            lblActiveUsers.Text =
                MoneyMethods.MoneySeparator(dm.QueryWithReturnDataSet("SELECT COUNT(*) FROM `users` WHERE `Role` = 'User' AND `Status` = 2;").Tables[0].Rows[0][0].ToString());
            lblNewUsers.Text =
                MoneyMethods.MoneySeparator(dm.QueryWithReturnDataSet("SELECT COUNT(*) FROM `users` WHERE `Role` = 'User' AND `Status` = 1;").Tables[0].Rows[0][0].ToString());
            pnlUsers.Visible = true;

            if (currentRole.PageUserTicketView == 1 || currentRole.PageUserTicketNotProcessedView == 1 || currentRole.PageUserTicketByDeliveryOnMinsk == 1 || currentRole.PageUserTicketByDeliveryOnBelarus == 1)
            {
                lblTicketsAll.Text =
                    MoneyMethods.MoneySeparator(dm.QueryWithReturnDataSet("select count(*) from `tickets`;").Tables[0].Rows[0][0].ToString());
                lblCreateToday.Text =
                    MoneyMethods.MoneySeparator(dm.QueryWithReturnDataSet(String.Format("select count(*) from `tickets` WHERE (`CreateDate` > '{0}' AND `CreateDate` < '{1}' );", DateTime.Now.ToString("yyyy-MM-dd"), DateTime.Now.AddDays(1).ToString("yyyy-MM-dd"))).Tables[0].Rows[0][0].ToString());
                lblNewToday.Text =
                    MoneyMethods.MoneySeparator(dm.QueryWithReturnDataSet(String.Format("select count(*) from `tickets` WHERE (`CreateDate` > '{0}' AND `CreateDate` < '{1}' AND `StatusID` = 1);", DateTime.Now.ToString("yyyy-MM-dd"), DateTime.Now.AddDays(1).ToString("yyyy-MM-dd"))).Tables[0].Rows[0][0].ToString());
                lblNewAll.Text =
                    MoneyMethods.MoneySeparator(dm.QueryWithReturnDataSet("select count(*) from `tickets` WHERE `StatusID` = 1;").Tables[0].Rows[0][0].ToString());
                lblDeliveryToday.Text =
                    MoneyMethods.MoneySeparator(dm.QueryWithReturnDataSet(String.Format("select count(*) from `tickets` WHERE (`DeliveryDate` = '{0}');", DateTime.Now.ToString("yyyy-MM-dd"))).Tables[0].Rows[0][0].ToString());
                lblDeliveryTomorow.Text =
                    MoneyMethods.MoneySeparator(dm.QueryWithReturnDataSet(String.Format("select count(*) from `tickets` WHERE (`DeliveryDate` = '{0}');", DateTime.Now.AddDays(1).ToString("yyyy-MM-dd"))).Tables[0].Rows[0][0].ToString());
                lblInProgress.Text =
                    MoneyMethods.MoneySeparator(dm.QueryWithReturnDataSet("select count(*) from `tickets` WHERE `StatusID` = 3;").Tables[0].Rows[0][0].ToString());
                lblDelivered.Text =
                    MoneyMethods.MoneySeparator(dm.QueryWithReturnDataSet("select count(*) from `tickets` WHERE `StatusID` = 12;").Tables[0].Rows[0][0].ToString());
                lblProcessed.Text =
                    MoneyMethods.MoneySeparator(dm.QueryWithReturnDataSet("select count(*) from `tickets` WHERE `StatusID` = 5;").Tables[0].Rows[0][0].ToString());
                lblCompleted.Text =
                    MoneyMethods.MoneySeparator(dm.QueryWithReturnDataSet("select count(*) from `tickets` WHERE `StatusID` = 6;").Tables[0].Rows[0][0].ToString());
                pnlTickets.Visible = true;
            }

            if (currentRole.PageCategoryView == 1)
            {
                lblTitles.Text =
                    MoneyMethods.MoneySeparator(dm.QueryWithReturnDataSet("select count(*) from `titles`;").Tables[0].Rows[0][0].ToString());
                pnlCategory.Visible = true;
            }

            if (currentRole.PageCityView == 1)
            {
                lblCity.Text =
                    MoneyMethods.MoneySeparator(dm.QueryWithReturnDataSet("select count(*) from `city`;").Tables[0].Rows[0][0].ToString());
                pnlCity.Visible = true;
            }

            if (currentRole.PageDriversView == 1)
            {
                lblDrivers.Text =
                    MoneyMethods.MoneySeparator(dm.QueryWithReturnDataSet("SELECT COUNT(*) FROM `drivers` WHERE `StatusID` = 1;").Tables[0].Rows[0][0].ToString());
                pnlDrivers.Visible = true;
            }

            if (currentRole.PageManagersView == 1)
            {
                lblManagers.Text =
                    MoneyMethods.MoneySeparator(dm.QueryWithReturnDataSet("SELECT COUNT(*) FROM `users` WHERE `Role` <> 'User';").Tables[0].Rows[0][0].ToString());
                pnlManagers.Visible = true;
            }

            if (currentRole.PageNewsView == 1)
            {
                lblNews.Text =
                    MoneyMethods.MoneySeparator(dm.QueryWithReturnDataSet("select count(*) from `news`;").Tables[0].Rows[0][0].ToString());
                pnlNews.Visible = true;
            }

            if (currentRole.PageErrorsLogView == 1)
            {
                lblErrors.Text =
                    MoneyMethods.MoneySeparator(dm.QueryWithReturnDataSet("select count(*) from `errorslog`;").Tables[0].Rows[0][0].ToString());
                pnlErrors.Visible = true;
            }

            if (currentRole.PageFeedbacksView == 1)
            {
                lblFeedback.Text =
                    MoneyMethods.MoneySeparator(dm.QueryWithReturnDataSet("SELECT COUNT(*) FROM `feedback` WHERE StatusID = 0;").Tables[0].Rows[0][0].ToString());
                pnlFeedback.Visible = true;
            }

            if (currentRole.PageTracksView == 1)
            {
                lblTracks.Text =
                    MoneyMethods.MoneySeparator(dm.QueryWithReturnDataSet("select count(*) from `tracks`;").Tables[0].Rows[0][0].ToString());
                pnlTracks.Visible = true;
            }

            if (currentRole.PageLogsView == 1)
            {
                lblLogs.Text =
                    MoneyMethods.MoneySeparator(dm.QueryWithReturnDataSet("select count(*) from `userslog`;").Tables[0].Rows[0][0].ToString());
                pnlLogs.Visible = true;
            }

            if (currentRole.PageApiLogView == 1)
            {
                lblApiLogs.Text =
                    MoneyMethods.MoneySeparator(dm.QueryWithReturnDataSet("select count(*) from `apilog`;").Tables[0].Rows[0][0].ToString());
                pnlApiLogs.Visible = true;
            }

            if (currentRole.PageClientsView == 1)
            {
                lblCategory.Text =
                    MoneyMethods.MoneySeparator(dm.QueryWithReturnDataSet("select count(*) from `category`;").Tables[0].Rows[0][0].ToString());
                pnlClients.Visible = true;
            }

            lblProvidersView.Text =
                MoneyMethods.MoneySeparator(dm.QueryWithReturnDataSet("select count(*) from `providers`;").Tables[0].Rows[0][0].ToString());

            var lastNews = dm.QueryWithReturnDataSet("SELECT `CreateDate`, `Title`, `Body`, `TitleUrl` FROM `news` WHERE `NewsTypeID` = '1' ORDER BY ID DESC LIMIT 1;").Tables[0];

            if (lastNews.Rows.Count != 0)
            {
                lblNewsDate.Text  = Convert.ToDateTime(lastNews.Rows[0][0]).ToString("dd.MM.yyyy");
                lblNewsTitle.Text = lastNews.Rows[0][1].ToString();
                var body = lastNews.Rows[0][2].ToString();
                if (body.Length > 300)
                {
                    lblNewsText.Text = body.Remove(300, body.Length - 300) + "...";
                }
                else
                {
                    lblNewsText.Text = body;
                }
                hlNewsTitle.NavigateUrl = string.Format("~/ManagerUI/Menu/NewsFeed/NewsFromFeedView.aspx?title={0}", lastNews.Rows[0][3].ToString());
            }

            //пересчитываем просмотренные новости
            //обновляем\задаем авторизационную куку с данными пользователя
            AuthenticationMethods.SetUserCookie(userInSession);

            //механизм нотификаций
            lblStatus.Text = String.Empty;
            if (Session["flash:now"] != null && Session["flash:now"].ToString() != String.Empty)
            {
                lblStatus.Text       = Session["flash:now"].ToString();
                Session["flash:now"] = String.Empty;
            }
        }
Exemplo n.º 17
0
        private void verifySessionAndUpdateNotifications(object state)
        {
            try
            {
                var sessionProvider = ProviderFactory.Instance.CreateSessionServiceProvider();

                if (SignalRNotifier.Instance.usersThatAreAlreadyReceievingNotifications.Contains(userLoginEmail))
                {
                    foreach (var sessionToken in SignalRNotifier.Instance.userSessionTokens)
                    {
                        try
                        {
                            var session = AuthenticationMethods.GetSessionData(sessionToken);
                            if (session == null || !sessionProvider.CheckIfSessionIsValid(sessionToken) || !sessionProvider.CheckIfSessionExists(sessionToken))
                            {
                                SignalRNotifier.Instance.lastSentNotificationData.Remove(sessionToken);
                                GlobalHost.ConnectionManager.GetHubContext <SessionHub>().Clients.Group(sessionToken).sessionExpired(new { redirectTo = GlobalProperties.LOGIN_PAGE });
                                SignalRNotifier.Instance.usersThatAreAlreadyReceievingNotifications.Remove(userLoginEmail);
                                sessionTimer.Dispose();
                            }

                            var transaction = new TransactionalInformation();
                            var response    = mainDataservice.GetNotificationData(connectionString, sessionToken, out transaction);

                            if (transaction.ReturnStatus)
                            {
                                if (!SignalRNotifier.Instance.lastSentNotificationData.ContainsKey(sessionToken) || SignalRNotifier.Instance.lastSentNotificationData[sessionToken].AnyTileDataChanged(response))
                                {
                                    if (!SignalRNotifier.Instance.lastSentNotificationData.ContainsKey(sessionToken))
                                    {
                                        SignalRNotifier.Instance.lastSentNotificationData.Add(sessionToken, response);
                                    }
                                    else
                                    {
                                        SignalRNotifier.Instance.lastSentNotificationData[sessionToken] = response;
                                    }

                                    GlobalHost.ConnectionManager.GetHubContext <SessionHub>().Clients.Group(userLoginEmail).updateNotifications(response);
                                }
                            }
                        }
                        catch
                        {
                            SignalRNotifier.Instance.lastSentNotificationData.Remove(sessionToken);
                            if (userLoginEmail != null)
                            {
                                GlobalHost.ConnectionManager.GetHubContext <SessionHub>().Clients.Group(sessionToken).sessionExpired(new { redirectTo = GlobalProperties.LOGIN_PAGE });
                                SignalRNotifier.Instance.usersThatAreAlreadyReceievingNotifications.Remove(userLoginEmail);
                            }
                            sessionTimer.Dispose();
                        }
                    }
                }
                else
                {
                    sessionTimer.Change(Timeout.Infinite, Timeout.Infinite);
                    sessionTimer.Dispose();
                }
            }
            catch
            {
            }
        }
Exemplo n.º 18
0
        public void LsaOpenPolicy_StandardRead()
        {
            LsaHandle handle = AuthenticationMethods.LsaOpenLocalPolicy(PolicyAccessRights.POLICY_READ);

            handle.IsInvalid.Should().BeFalse();
        }
		public bool LogIn(string login, string password, AuthenticationMethods authenticationMethod)
			=> _client.Login(login, password, authenticationMethod);
Exemplo n.º 20
0
        public void LsaOpenPolicy_GenericRead()
        {
            Action action = () => AuthenticationMethods.LsaOpenLocalPolicy((PolicyAccessRights)GenericAccessRights.Read);

            action.ShouldThrow <UnauthorizedAccessException>();
        }
Exemplo n.º 21
0
        public void ShouldReturnCorrectIke(AuthenticationMethods authMode, Type expectedType)
        {
            var result = _subject.GetIkeV1Instance(authMode, new HashFunction(ModeValues.SHA1, DigestSizes.d160));

            Assert.IsInstanceOf(expectedType, result);
        }
Exemplo n.º 22
0
        private void btnOptionsSave_Click(object sender, EventArgs e)
        {
            if (_globalState == State.Initializing)
            {
                // TODO: Add capability for additional users with User.PermissionLevels = NONE

                // Save user preferences and information to database
                string name        = tbxUserName.Text;
                string phoneNumber = tbxUserPhone.Text;
                User.PermissionLevels permissionLevel = (User.GetAll().Count() == 0) ? User.PermissionLevels.FULL : User.PermissionLevels.NONE;
                AuthenticationMethod  primary         = null;
                AuthenticationMethod  secondary       = null;
                switch (cbxPrimAuth.SelectedItem.ToString())
                {
                case "Bluetooth":
                    primary = (BluetoothDevice)cbxBTSelect1.SelectedItem;
                    break;

                case "Card":
                    primary = new Card(tbxCard.Text);
                    break;
                }
                switch (cbxSecAuth.SelectedItem.ToString())
                {
                case "Card":
                    secondary = new Card(tbxCard.Text);
                    break;

                case "Bluetooth":
                    secondary = (BluetoothDevice)cbxBTSelect2.SelectedItem;
                    break;

                case "PIN":
                    secondary = new Pin(tbxPin.Text);
                    break;
                }
                AuthenticationMethods authenticationMethods = new AuthenticationMethods(primary, secondary);
                User.Create(name, permissionLevel, phoneNumber, null, authenticationMethods);

                // Go to idle state
                _globalState = State.Idle;
                UpdateComponents();
                tbxCard.Text = "";
            }
            else if (_globalState == State.SecondFactor)
            {
                bool success = false;
                switch (_currentAuthSequence.NextAuthenticationMethod)
                {
                case Card card:
                    success = _currentAuthSequence.Continue(new Card(tbxSecFactorPinOrCard.Text));
                    break;

                case Pin pin:
                    success = _currentAuthSequence.Continue(new Pin(tbxSecFactorPinOrCard.Text));
                    break;

                case BluetoothDevice btDevice:
                    success = bluetoothFound && _currentAuthSequence.Continue(btDevice);
                    break;

                default:
                    break;
                }

                if (success && _currentAuthSequence.NextAuthenticationMethod == null)
                {
                    // Successful Authentication
                    _currentUser = _currentAuthSequence.User;
                    _globalState = State.Authenticated;
                    UpdateComponents();
                }
                else
                {
                    if (--numTriesLeftSecondFactor == 0)
                    {
                        _globalState = State.AccessDenied;
                        UpdateComponents();
                    }
                    else
                    {
                        txtSecondFactorStatus.Visible = true;
                        string pluralTries = numTriesLeftSecondFactor == 1 ? "try" : "tries";
                        txtSecondFactorStatus.Text = "Secondary authentication failed. You have " + numTriesLeftSecondFactor + " " + pluralTries + " left. Please try again.";
                        tbxSecFactorPinOrCard.Text = "";
                        cardInput = ""; // just in case
                    }
                }
            }
            else if (_globalState == State.Authenticated)
            {
                if (_currentUser.PermissionLevel == User.PermissionLevels.FULL)
                {
                    _globalState = State.UserManagement;
                    _formUserManagement.Show();
                }
                else
                {
                    _globalState = State.UserOptions;
                    _formOptions.Show();
                }
                UpdateComponents();
                this.Hide();
            }
        }