public ConnectionDescription InitializeConnection(IConnection connection, CancellationToken cancellationToken)
        {
            Ensure.IsNotNull(connection, nameof(connection));
            var isMasterCommand  = CreateInitialIsMasterCommand(connection.Settings.Authenticators);
            var isMasterProtocol = IsMasterHelper.CreateProtocol(isMasterCommand);
            var isMasterResult   = IsMasterHelper.GetResult(connection, isMasterProtocol, cancellationToken);

            var buildInfoProtocol = CreateBuildInfoProtocol();
            var buildInfoResult   = new BuildInfoResult(buildInfoProtocol.Execute(connection, cancellationToken));

            var description = new ConnectionDescription(connection.ConnectionId, isMasterResult, buildInfoResult);

            AuthenticationHelper.Authenticate(connection, description, cancellationToken);

            try
            {
                var getLastErrorProtocol = CreateGetLastErrorProtocol();
                var getLastErrorResult   = getLastErrorProtocol.Execute(connection, cancellationToken);

                description = UpdateConnectionIdWithServerValue(description, getLastErrorResult);
            }
            catch
            {
                // if we couldn't get the server's connection id, so be it.
            }

            return(description);
        }
        public ConnectionDescription Authenticate(IConnection connection, ConnectionDescription description, CancellationToken cancellationToken)
        {
            Ensure.IsNotNull(connection, nameof(connection));
            Ensure.IsNotNull(description, nameof(description));

            var authenticators = GetAuthenticators(connection.Settings);

            AuthenticationHelper.Authenticate(connection, description, authenticators, cancellationToken);

            var connectionIdServerValue = description.HelloResult.ConnectionIdServerValue;

            if (connectionIdServerValue.HasValue)
            {
                description = UpdateConnectionIdWithServerValue(description, connectionIdServerValue.Value);
            }
            else
            {
                try
                {
                    var getLastErrorProtocol = CreateGetLastErrorProtocol(_serverApi);
                    var getLastErrorResult   = getLastErrorProtocol.Execute(connection, cancellationToken);

                    description = UpdateConnectionIdWithServerValue(description, getLastErrorResult);
                }
                catch
                {
                    // if we couldn't get the server's connection id, so be it.
                }
            }

            return(description);
        }
        public IHttpActionResult Login(LoginModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var result = MemberBusiness.Login(model.Number, model.Password, model.Code);

            if (!result.Success)
            {
                return(BadRequest(result.Message));
            }
            var tokenModel = new TokenModel
            {
                Member = result.Data,
                Token  = AuthenticationHelper.Authenticate(result.Data.PhoneNumber, null, true, new Dictionary <string, dynamic>
                {
                    { AuthenticationHelper.UserIDKey, result.Data.Id },
                    { AuthenticationHelper.UserTicketIssueTimeKey, DateTimeOffset.Now }
                })
            };

            //var tokenModel = new TokenModel
            //{
            //    Member = null,
            //    Token = AuthenticationHelper.Authenticate("13112345678", null, true, new Dictionary<string, dynamic>
            //    {
            //        { AuthenticationHelper.UserIDKey, Guid.NewGuid()},
            //        { AuthenticationHelper.UserTicketIssueTimeKey,DateTimeOffset.Now  }
            //    })
            //};

            return(Ok(tokenModel));
        }
        public void CannotAuthenticateInvalidRepository()
        {
            // Arrange
            var repo = new AuthenticationHelper(UserControllerTest.GetMockRepo(false), GetConfiguration());

            // Act
            var result = repo.Authenticate(EmailAdmin, PassAdmin);

            // Assert
            Assert.Null(result);
        }
        public void CannotAuthenticateInvalidPassword()
        {
            // Arrange
            var repo = new AuthenticationHelper(UserControllerTest.GetMockRepo(), GetConfiguration());

            // Act
            var result = repo.Authenticate(EmailAdmin, "Not my password");

            // Assert
            Assert.Null(result);
        }
        public void CannotAuthenticateEmptyParameters()
        {
            // Arrange
            var repo = new AuthenticationHelper(UserControllerTest.GetMockRepo(), GetConfiguration());

            // Act
            var result = repo.Authenticate(string.Empty, string.Empty);

            // Assert
            Assert.Null(result);
        }
Exemple #7
0
        public IHttpActionResult Authenticate(LoginRequest loginRequest)
        {
            var user = AuthenticationHelper.Authenticate(loginRequest.Username, loginRequest.Password);

            if (user == null)
            {
                return(NotFound());
            }

            return(Ok(user));
        }
Exemple #8
0
        public async Task <IActionResult> Login(LoginViewModel model)
        {
            var data = await AuthenticationHelper.Authenticate(model.Username, model.Password);

            if (data.AuthenticationStatus != AuthenticationStatus.Succeeded)
            {
                return(View());
            }

            HttpContext.Session.SetObjectAsJson("token", data.Data);
            return(RedirectToAction("Index", "Dashboard"));
        }
Exemple #9
0
        private async void TryLogin(object sender, EventArgs e)
        {
            isLoging = true;
            await DoRequest(() => AuthenticationHelper.Authenticate(), "Autenticación realizada");

            if (AuthenticationHelper.IsAuthenticated())
            {
                listOfEmployeesPage = new ListOfEmployeesPage();
                await Navigation.PushAsync(listOfEmployeesPage);
            }

            isLoging = false;
        }
Exemple #10
0
        public void WithoutRightsUserTest()
        {
            BLHelper.InitBL(dalType: DALType.Service);
            BLHelper.RegisterServiceClient("Auto", ClientTypeCode.DCL);

            var auth = IoC.Instance.Resolve <IAuthenticationProvider>();

            auth.Authenticate("T1", "T1");

            AuthenticationHelper.Authenticate("T1", "T1");
            var mgr = IoC.Instance.Resolve <IBaseManager <GlobalParamValue> >();

            mgr.GetAll();
        }
Exemple #11
0
        private static bool Authenticate()
        {
//#if DEBUG
//            // пробуем под собой
//            if (AuthenticationHelper.Authenticate(Environment.UserName.ToUpper(), "123"))
//                return true;
//            // пробуем под DEBUG
//            if (AuthenticationHelper.Authenticate(DCL.Resources.StringResources.DEBUG, DCL.Resources.StringResources.DEBUG))
//                return true;
//            return false;
//#else
            return(AuthenticationHelper.Authenticate(SplashScreenHelper.SplashScreenHandle));
//#endif
        }
Exemple #12
0
        public void PostShouldReturnCreated(string url)
        {
            var token    = AuthenticationHelper.Authenticate(browser);
            var response = browser.Post(url, with => {
                with.HttpRequest();
                with.Header("User-Agent", "test");
                with.Header("Authorization", "Token " + token);
                with.JsonBody <Send>(new Send {
                    RemindOn = DateTime.Now
                });
            });

            Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);
        }
Exemple #13
0
        public void PostShouldReturnCreatedDataAsJson(string url)
        {
            var token    = AuthenticationHelper.Authenticate(browser);
            var response = browser.Post(url, with => {
                with.HttpRequest();
                with.Header("User-Agent", "test");
                with.Header("Authorization", "Token " + token);
                with.JsonBody <Send>(new Send {
                    RemindOn = DateTime.Now
                });
            });

            Assert.AreEqual("application/json; charset=utf-8", response.ContentType);
            Assert.That(response.Context.JsonBody <Send>(), Is.InstanceOf <Send>());
        }
        public void CanAuthenticate()
        {
            // Arrange
            var userRepo = UserControllerTest.GetMockRepo();
            var repo     = new AuthenticationHelper(userRepo, GetConfiguration());
            var user     = userRepo.GetById(1).Value;

            // Act
            var result = repo.Authenticate(EmailAdmin, PassAdmin);

            // Assert
            Assert.NotNull(result);
            Assert.Equal(result.Id, user.Id);
            Assert.Equal(result.Name, user.Name);
            Assert.Equal(result.Surname, user.Surname);
            Assert.Equal(result.IsAdmin, user.IsAdmin);
            Assert.False(string.IsNullOrWhiteSpace(result.Token));
        }
        public IActionResult Login([FromBody] dynamic login)
        {
            if (login["Email"] == null || login["Password"] == null)
            {
                return(BadRequest("Missing Email or Password"));
            }
            var user = _authenticationHelper.Authenticate(login);

            HttpContext.Session.Set("User", user);

            if (user == null)
            {
                return(StatusCode(403, "Bad Credentials"));
            }

            var tokenString = _authenticationHelper.BuildToken(user);

            return(Ok(new { user = user, token = tokenString }));
        }
Exemple #16
0
        private async void Login()
        {
            Logoff();

            if (AuthenticationHelper.Authenticate())
            {
                try
                {
                    WaitIndicatorVisible = true;

                    // чистим кэш после перерисовки
                    await DoClearCacheAsync();

                    // перевычитывем главное меню
                    ShowMainMenu();
                }
                finally
                {
                    WaitIndicatorVisible = false;
                }
            }
        }
        public ConnectionDescription InitializeConnection(IConnection connection, CancellationToken cancellationToken)
        {
            Ensure.IsNotNull(connection, nameof(connection));
            var authenticators = connection.Settings.AuthenticatorFactories.Select(f => f.Create()).ToList();
            var helloCommand   = CreateInitialHelloCommand(authenticators);
            var helloProtocol  = HelloHelper.CreateProtocol(helloCommand, _serverApi);
            var helloResult    = HelloHelper.GetResult(connection, helloProtocol, cancellationToken);

            var buildInfoProtocol = CreateBuildInfoProtocol(_serverApi);
            var buildInfoResult   = new BuildInfoResult(buildInfoProtocol.Execute(connection, cancellationToken));

            var description = new ConnectionDescription(connection.ConnectionId, helloResult, buildInfoResult);

            AuthenticationHelper.Authenticate(connection, description, authenticators, cancellationToken);

            var connectionIdServerValue = helloResult.ConnectionIdServerValue;

            if (connectionIdServerValue.HasValue)
            {
                description = UpdateConnectionIdWithServerValue(description, connectionIdServerValue.Value);
            }
            else
            {
                try
                {
                    var getLastErrorProtocol = CreateGetLastErrorProtocol(_serverApi);
                    var getLastErrorResult   = getLastErrorProtocol.Execute(connection, cancellationToken);

                    description = UpdateConnectionIdWithServerValue(description, getLastErrorResult);
                }
                catch
                {
                    // if we couldn't get the server's connection id, so be it.
                }
            }

            return(description);
        }
Exemple #18
0
        private async void Login()
        {
            Logoff();

            if (AuthenticationHelper.Authenticate())
            {
                try
                {
                    SignalRHelper.TryConnectToServer();
                    WaitIndicatorVisible = true;

                    // чистим кэш после перерисовки
                    await DoLiteClearCacheAsync();

                    // перевычитывем главное меню
                    LoadCustomization();
                    ShowTree();
                }
                finally
                {
                    WaitIndicatorVisible = false;
                }
            }
        }
 public void TestInitialize()
 {
     AuthenticationHelper.Authenticate();
 }
Exemple #20
0
        public static void Main(string[] args)
        {
            Logger.Init();

            // LOAD REFERENCES CONF
            FactoryConf fc = null;

            using (StreamReader file = File.OpenText("resources/reference.conf"))
            {
                JsonSerializer serializer = new JsonSerializer();
                fc = (FactoryConf)serializer.Deserialize(file, typeof(FactoryConf));
            }

            // Authentication
            AuthenticationHelper authenticationHelper = new AuthenticationHelper(fc.authenticationConf);

            authenticationHelper.Authenticate().Wait();
            //authenticationHelper.AuthenticateWithInput();

            // Register Device model and device
            DeviceRegister deviceRegister = new DeviceRegister(fc.deviceRegisterConf, authenticationHelper.GetOAuthCredentials().access_token);

            deviceRegister.Register();

            // Build the client (stub)
            AssistantClient assistantClient = new AssistantClient(authenticationHelper.GetOAuthCredentials(), fc.authenticationConf, fc.assistantConf,
                                                                  deviceRegister.GetDeviceModel(), deviceRegister.GetDevice());

            // Main loop
            bool isDone = false;

            while (!isDone)
            {
                // Check if we need to refresh the access token to request the api
                if (authenticationHelper.Expired())
                {
                    authenticationHelper.RefreshAccessToken();

                    assistantClient.UpdateCredentials(authenticationHelper.GetOAuthCredentials());
                }

                {
                    Logger.Get().Debug("Tap your request and press enter... (Tap quit to exit)");

                    string query = Console.ReadLine();

                    if (query.ToLower().Equals("quit"))
                    {
                        break;
                    }
                    if (query.Length == 0)
                    {
                        continue;
                    }

                    // requesting assistant with text query
                    assistantClient.TextRequestAssistant(query).Wait();

                    Logger.Get().Debug(">> " + assistantClient.GetTextResponse());
                    Logger.Get().Debug("   (AUDIO : " + (assistantClient.GetAudioResponse() != null ? assistantClient.GetAudioResponse().Length:0) + ")");
                }
            }

            Logger.Get().Debug("FINISH");
        }
Exemple #21
0
        protected override void Seed(ERPContext context)
        {
            base.Seed(context);
            //
            EntityBase.ERPContext = context;

            //
            foreach (var user2 in EntityBase.ERPContext.UserMaster)
            {
                EntityBase.ERPContext.UserMaster.Remove(user2);
            }

            foreach (var id in EntityBase.ERPContext.Identity)
            {
                EntityBase.ERPContext.Identity.Remove(id);
            }

            foreach (var instanceValues in EntityBase.ERPContext.ApplicationDefaults)
            {
                EntityBase.ERPContext.ApplicationDefaults.Remove(instanceValues);
            }

            foreach (var entity1 in EntityBase.ERPContext.EntityMaster)
            {
                EntityBase.ERPContext.EntityMaster.Remove(entity1);
            }

            EntityBase.ERPContext.SaveChanges();

            var applicationDefault = new ApplicationDefaults();

            applicationDefault.PropertyName = "EncryptionKey";
            applicationDefault.DataType     = "System.String";
            applicationDefault.Value        = "MAKV2SPBNI99212";
            applicationDefault.IsActive     = true;
            applicationDefault.SaveAll();
            //
            var entity = new EntityMaster();

            entity.EntityType    = Common.EntityTypeName.UserMaster;
            entity.EntityName    = "UserMaster";
            entity.AssemblyName  = "ERPSolution";
            entity.NamespaceName = "ERPSolution.Models.UserMaster";
            entity.IsParent      = true;
            entity.IsChild       = false;
            entity.SaveAll();

            var entity2 = new EntityMaster();

            entity2.EntityType    = Common.EntityTypeName.Identity;
            entity2.EntityName    = "Identity";
            entity2.AssemblyName  = "ERPSolution";
            entity2.NamespaceName = "ERPSolution.Models.Identity";
            entity2.IsParent      = true;
            entity2.IsChild       = false;
            entity2.SaveAll();
            //
            EntityBase.InstanceValues = EntityBase.ERPContext.ApplicationDefaults.Where(ad => ad.IsActive == true).ToList <ApplicationDefaults>();
            //
            Metadata.Entities = EntityBase.ERPContext.EntityMaster.ToList <EntityMaster>();

            //foreach (var secureData2 in EntityBase.ERPContext.SecureData)
            //    EntityBase.ERPContext.SecureData.Remove(secureData2);

            //EntityBase.ERPContext.SaveChanges();
            //
            var identity = new Identity();

            identity.Name             = "Pratik";
            identity.Code             = "CodenameDJ";
            identity.EMailId          = "*****@*****.**";
            identity.MobileNo         = "8055333533";
            identity.ValidationStatus = Common.EnumMaster.ValidationStatus.Suspended;
            var result = identity.SaveAll();

            var user = new UserMaster();

            user.IdentityId = identity.Id;
            user.ContactId  = Guid.NewGuid();
            user.Code       = identity.Code;
            user.Gender     = Common.EnumMaster.Gender.Male;
            user.Name       = identity.Name;
            user.MobileNo   = identity.MobileNo;
            user.SaveAll();

            var secureData = new SecureData();

            secureData.IdentityId = identity.Id;
            secureData.Data       = "q";
            secureData.SaveAll();

            //var user3 = EntityBase.ERPContext.UserMaster.Where(um => um.Code == "CodenameDj").First();
            //user3.Code = "CodenameDj2410";
            //user3.SaveAll();

            //var userEdit = new UserMaster(Guid.Parse(user.Id.ToString()));
            AuthenticationHelper.Authenticate(identity.Code, secureData.Data);
            //Type typeName = Type.GetType("ERPSolution.Models.UserMaster");
            var userdata = EntityHelper.GetEntity(Common.EntityTypeName.UserMaster, user.Id) as UserMaster;

            userdata.MobileNo = "7020328833";
            userdata.SaveAll();
        }
        public async Task <IActionResult> Login([FromBody] AuthInput login)
        {
            var result = await _authenticationHelper.Authenticate(login.Username, login.Password);

            return(Ok(result));
        }
Exemple #23
0
 protected void cmdLoginOauth_Click(object sender, EventArgs e)
 {
     Session ["login_referrer"] = Request.QueryString ["referrer"];
     AuthenticationHelper.Authenticate();
 }
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            HttpContext httpContext = context.HttpContext;
            AuthenticationInternalResult authresult = AuthenticationHelper.Authenticate(context);

            if (authresult != null)
            {
                if (authresult.IsRredirect)
                {
                    context.Result = new RedirectResult(authresult.RedirectUrl, true);
                    return;
                }
                else if (authresult.KeepUnauthenticated)
                {
                    IAuthenticationResult unauthenticatedResult = AuthenticationResult.Unauthenticated();
                    AuthenticationHelper.SaveAuthenticationResult(httpContext, unauthenticatedResult);
                    return;
                }
                else
                {
                    IAuthenticationResult authenticationResult = AuthenticationResult.Authenticated(authresult.Authenticator.Type, authresult.User);
                    AuthenticationHelper.SaveAuthenticationResult(httpContext, authenticationResult);
                    return;
                }
            }

            switch (FailedAction)
            {
            case AuthenticationFailedAction.KeepUnauthenticated:
            {
                IAuthenticationResult unauthenticatedResult = AuthenticationResult.Unauthenticated();
                AuthenticationHelper.SaveAuthenticationResult(httpContext, unauthenticatedResult);
                return;
            }

            case AuthenticationFailedAction.RedirectCAS:
                context.Result = new HttpCASRedirectResult();
                return;

            case AuthenticationFailedAction.Return403:
                context.Result = new HttpAuthenticationForbiddenResult();
                return;

            case AuthenticationFailedAction.CustomHandler:
            {
                List <Type> customAuthenticators = null;
                AuthenticationFailedHandlerAttribute[] handlers = null;
                switch (context.ActionDescriptor)
                {
                case ControllerActionDescriptor controllerActionDescriptor:
                    customAuthenticators = GetCustomAuthenticators(controllerActionDescriptor);
                    handlers             = GetCustomHandlers(controllerActionDescriptor);
                    break;

                case CompiledPageActionDescriptor compiledPageActionDescriptor:
                    customAuthenticators = GetCustomAuthenticators(compiledPageActionDescriptor);
                    handlers             = GetCustomHandlers(compiledPageActionDescriptor);
                    break;

                default:
                    throw new Exception($"not handled with action descriptor of type {context.ActionDescriptor.GetType().Name}");
                }

                if (handlers != null && handlers.Length > 0)
                {
                    IActionResult actionResult = AuthenticationHelper.ExecuteHandler(handlers[0].Handler, handlers[0].ConstructParameters, httpContext, Policy, customAuthenticators.ToArray());
                    if (actionResult != null)
                    {
                        context.Result = actionResult;
                        return;
                    }
                    else
                    {
                        // not handled
                        throw new Exception($"not handled");
                    }
                }
            }
                return;
            }
        }