Пример #1
0
        public LoginRequest get_login(LoginRequest request)
        {
            if (request.Status == LoginStatus.NotAuthenticated)
            {
                request.Status = _lockedOutRule.IsLockedOut(request);
            }

            _service.SetRememberMeCookie(request);

            if (request.UserName.IsEmpty())
            {
                string remembered = _cookies.User.Value;

                if (remembered.IsNotEmpty())
                {
                    request.UserName = remembered;
                    request.RememberMe = true;
                }
            }

            if (request.Status == LoginStatus.LockedOut)
            {
                request.Message = LoginKeys.LockedOut.ToString();
            }
            else if (request.Status == LoginStatus.Failed && request.Message.IsEmpty())
            {
                request.Message = LoginKeys.Unknown.ToString();
            }

            return request;
        }
        // POST api/CustomLogin
        public HttpResponseMessage Post(LoginRequest loginRequest)
        {
            XamarinPushDemoContext context = new XamarinPushDemoContext();
            Account account = context.Accounts
                .Where(a => a.Username == loginRequest.username).SingleOrDefault();
            if (account != null)
            {
                byte[] incoming = CustomLoginProviderUtils
                    .hash(loginRequest.password, account.Salt);

                if (CustomLoginProviderUtils.slowEquals(incoming, account.SaltedAndHashedPassword))
                {
                    ClaimsIdentity claimsIdentity = new ClaimsIdentity();
                    claimsIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, loginRequest.username));
                    LoginResult loginResult = new CustomLoginProvider(handler)
                        .CreateLoginResult(claimsIdentity, Services.Settings.MasterKey);
                    var customLoginResult = new CustomLoginResult()
                    {
                        UserId = loginResult.User.UserId,
                        MobileServiceAuthenticationToken = loginResult.AuthenticationToken
                    };
                    return this.Request.CreateResponse(HttpStatusCode.OK, customLoginResult);
                }
            }
            return this.Request.CreateResponse(HttpStatusCode.Unauthorized,
                "Invalid username or password");
        }
Пример #3
0
        private void btnLogin_Click(object sender, EventArgs e)
        {
            string username = txbUserName.Text;
            string password = txbPassword.Text;
            LoginRequest request = new LoginRequest();
            request.UserName = username;
            request.Password = password;
            var response = SDKFactory.Client.Execute(request);
            if (!response.IsError)
            {
                AppData.token = response.Result?.token;
                AppData.User = response.Result?.User?.User;
                AppData.UserInfo = response.Result?.User?.UserInfo;

                LoginInfo info = new LoginInfo { RemberMe = chkRemberMe.Checked, UserName = txbUserName.Text };
                string xml = XMLHelper.Serialize(info);
                FileInfo file = new FileInfo(_loginfilepath);
                if (!file.Directory.Exists) file.Directory.Create();
                File.WriteAllText(file.FullName, xml);

                Startup form = this.Owner as Startup;
                form.Token = AppData.token;
                form.SetInfo(AppData.UserInfo?.CnName);
                form.CreateMenu(response.Result.Menu);
                form.Show();
                this.Close();
            }
            else SOAFramework.Client.Controls.MessageBox.Show(this, response.ErrorMessage, "Error", MessageBoxButtons.OK);
        }
        // POST api/CustomLogin
        public HttpResponseMessage Post(LoginRequest loginRequest)
        {
            homesecurityContext context = new homesecurityContext();
            Account account = context.Accounts
                .Where(a => a.Email == loginRequest.Email).SingleOrDefault();
            if (account != null)
            {
                byte[] incoming = CustomLoginProviderUtils
                    .hash(loginRequest.Password, account.Salt);

                if (CustomLoginProviderUtils.slowEquals(incoming, account.SaltedAndHashedPassword))
                {
                    ClaimsIdentity claimsIdentity = new ClaimsIdentity();
                    claimsIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, loginRequest.Email));
                    LoginResult loginResult = new CustomLoginProvider(handler)
                        .CreateLoginResult(claimsIdentity, Services.Settings.MasterKey);
                    var customLoginResult = new CustomLoginResult()
                    {
                        UserId = loginResult.User.UserId,
                        MobileServiceAuthenticationToken = loginResult.AuthenticationToken,
                        Verified = account.Verified
                    };
                    return this.Request.CreateResponse(HttpStatusCode.OK, customLoginResult);
                }
            }
            var message = "Fail";
            return this.Request.CreateResponse(HttpStatusCode.Unauthorized,
                new { message });
        }
 private void SetRememberMeCookie(LoginRequest request)
 {
     if (request.RememberMe && request.UserName.IsNotEmpty())
     {
         _cookies.User.Value = request.UserName;
     }
 }
        public LoginResponse LogIn(LoginRequest request)
        {
            var response = new LoginResponse();

            try
            {
                var persist = false;

                if (request.Persistence != null)
                {
                    //var x = new FormsAuthenticationTicket("authentication", true, (int)request.Persistence.Value.TotalMinutes);
                    persist = true;
                    this.context.Response.Cookies[0].Expires = DateTime.Now.Add((TimeSpan)request.Persistence);
                }

#pragma warning disable CS0618
                if (FormsAuthentication.Authenticate(request.UserName, request.Password))
                {
                    FormsAuthentication.SetAuthCookie(request.UserName, persist);
                    response.Status = StatusCode.OK;
                }
                else
                {
                    response.Status = StatusCode.Unauthorized;
                }
#pragma warning restore CS0618
            }
            catch (Exception ex)
            {
                response.Status = StatusCode.InternalServerError;
                this.exceptionHandler.HandleException(ex);
            }

            return response;
        }
        public void is_not_locked_out_with_less_than_the_maximum_attempts()
        {
            var request = new LoginRequest();
            request.NumberOfTries = theSettings.MaximumNumberOfFailedAttempts - 1;

            theRule.IsLockedOut(request).ShouldEqual(LoginStatus.NotAuthenticated);
        }
Пример #8
0
        public LoginResponse LogIn(LoginRequest request)
        {
            var response = new LoginResponse();

            try
            {
                var persist = false;

                if (request.Persistence != null)
                {
                    persist = true;
                    this.context.Response.Cookies[0].Expires = DateTime.Now.Add((TimeSpan)request.Persistence);
                }

                if (WebSecurity.Login(request.UserName, request.Password, persist))
                {
                    response.Status = StatusCode.OK;
                }
                else
                {
                    response.Status = StatusCode.Unauthorized;
                }
            }
            catch (Exception ex)
            {
                response.Status = StatusCode.InternalServerError;
                this.exceptionHandler.HandleException(ex);
            }

            return response;
        }
        public void is_locked_out_if_the_maximum_number_of_attempts_has_been_reached()
        {
            var request = new LoginRequest();
            request.NumberOfTries = theSettings.MaximumNumberOfFailedAttempts;

            theRule.IsLockedOut(request).ShouldEqual(LoginStatus.LockedOut);
        }
        public LoginRequest Login(LoginRequest request)
        {
            if (request.UserName.IsEmpty())
            {
                var remembered = _cookies.User.Value;

                if (remembered.IsNotEmpty())
                {
                    request.UserName = remembered;
                    request.RememberMe = true;
                }
            }

            if (request.Status != LoginStatus.Failed)
            {
                return request;
            }

            if (request.Message.IsEmpty())
            {
                request.Message = LoginKeys.Unknown.ToString();
            }

            return request;
        }
 public void setting_return_url_sets_url()
 {
     var loginRequest = new LoginRequest();
     var testing_url = "the/best/url";
     loginRequest.ReturnUrl = testing_url;
     loginRequest.Url.ShouldEqual(testing_url);
 }
Пример #12
0
        public async Task Edit(string currentPassword = "",
            string username = null, string email = null, string password = null,
            Stream avatar = null, ImageType avatarType = ImageType.Png)
        {
            if (currentPassword == null) throw new ArgumentNullException(nameof(currentPassword));

            var request = new UpdateProfileRequest()
            {
                CurrentPassword = currentPassword,
                Email = email ?? Email,
                Password = password,
                Username = username ?? Client.PrivateUser.Name,
                AvatarBase64 = avatar.Base64(avatarType, Client.PrivateUser.AvatarId)
            };

            await Client.ClientAPI.Send(request).ConfigureAwait(false);

            if (password != null)
            {
                var loginRequest = new LoginRequest()
                {
                    Email = Email,
                    Password = password
                };
                var loginResponse = await Client.ClientAPI.Send(loginRequest).ConfigureAwait(false);
                Client.ClientAPI.Token = loginResponse.Token;
                Client.GatewaySocket.Token = loginResponse.Token;
                Client.GatewaySocket.SessionId = null;
            }
        }
Пример #13
0
        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            if (Validation() == true)
            {
                // show Loader
                myIndeterminateProbar.Visibility = Visibility.Visible;

                //====================================================================================================================
                // Login Check
                //====================================================================================================================

                // Parameters
                LoginRequest obj = new LoginRequest();
                obj.email = txtUserName.Text.Trim(); // "djhs16";
                obj.password = txtPassWord.Password.Trim(); //"qaz";
                String data = "email=" + obj.email + "&password="******"Content-Type"] = "application/x-www-form-urlencoded";
                webClient.Headers[HttpRequestHeader.AcceptLanguage] = "en_US";
                webClient.UploadStringAsync(new Uri(Utilities.GetURL("auth/signIn/")), "POST", data);
                //Assign Event Handler
                webClient.UploadStringCompleted += wc_UploadStringCompleted;
            }
        }
Пример #14
0
        public async Task InvalidUser_ShouldThrowNotFoundException(string username)
        {
            LoginRequest request = new LoginRequest()
            {
                UserName = username
            };
            var serviceMock = new Mock<IPasswordService>();
            serviceMock
                .Setup(s =>
                        s.ValidatePassword(It.IsAny<string>(), It.IsAny<string>()))
                .Returns(true);

            var setMock = new Mock<DbSet<User>>()
                    .SetupData(new User[] { new User() { Username = "******" } });
            var contextMock = new Mock<BoxingDbContext>();
            contextMock.Setup(c => c.Users).Returns(setMock.Object);


            var service = serviceMock.Object;
            var handler = new LoginHandler(service, contextMock.Object);

            await Assert.ThrowsAsync<EntityDoesNotExistException>(async () =>
            {
                await handler.HandleAsync(request);
            });
        }
Пример #15
0
        public Task<LoginResponse> LoginAsync(string userName, string passWord)
        {
            return Task.Run (() => {
            var client = new RestClient("http://70.187.52.39:3000/LoginApp");
            var req = new RestRequest(Method.POST);
            string user = userName;
            string pass = passWord;
            var loginObject = new LoginRequest {
                username = user,
                password = pass,
            };

            var json = req.JsonSerializer.Serialize(loginObject);
            req.AddParameter("application/json; charset=utf-8", json, ParameterType.RequestBody);
            Console.WriteLine ("HELLLOOOO!>>?????");
            var returnStuff =  client.Execute(req);
            LoginResponse info = JsonConvert.DeserializeObject<LoginResponse> (returnStuff.Content);
                Console.WriteLine ("login sucessful?? Username: "******"KEY: "+ info.KEY);

            //var dict = JsonConvert.DeserializeObject<JsonArrayAttribute> (asd);
            return info;

            }
            );
        }
Пример #16
0
    private void OnConnection(ConnectionEvent e)
    {
        _server.EventDispatcher.ConnectionEvent -= OnConnection;

        LoginRequest request = new LoginRequest("user", "pass");

        _server.Send(request);
    }
Пример #17
0
	/// <summary>
	/// Login in to the server with the specified username and password.
	/// </summary>
	/// <param name="username">Username to login with.</param>
	/// <param name="password">Password for username.</param>
	public void Login(string username, string password)
	{
		_server.EventDispatcher.LoginEvent += OnLogin;

		LoginRequest login = new LoginRequest(username, password);

		_server.Send(login);
	}
 public IHttpActionResult Post(LoginRequest request)
 {
     LoggedIn loggedIn = _adapter.LoginVerify(request);
     if (loggedIn != null)
         return Ok(loggedIn);
     else
         return Unauthorized();
 }
        public void is_not_locked_out_if_the_maximum_number_of_attempts_was_reached_but_the_locked_out_time_has_expired()
        {
            var request = new LoginRequest();
            request.LockedOutUntil = DateTime.Today.ToUniversalTime();

            theSystemTime.LocalNow(DateTime.Today.AddMinutes(theSettings.CooloffPeriodInMinutes + 1));

            theRule.IsLockedOut(request).ShouldEqual(LoginStatus.NotAuthenticated);
        }
Пример #20
0
        private string Authorize(string enteredLogin, string enteredPassword)
        {
            var request = new LoginRequest()
            {
                Login = enteredLogin,
                Password = enteredPassword
            };

            return client.Login(request).Message;
        }
Пример #21
0
        public void is_locked_out_if_the_locked_out_time_is_not_expired()
        {
            theSettings.CooloffPeriodInMinutes = 20;

            var request = new LoginRequest();
            request.NumberOfTries = theSettings.MaximumNumberOfFailedAttempts;
            request.LockedOutUntil = DateTime.Today.AddMinutes(10).ToUniversalTime();

            theSystemTime.LocalNow(DateTime.Today);
        }
        public void CanLoginSuccessfullyWithCorrcectUserNameAndPassword()
        {
            var request = new LoginRequest {Username = Username, Password = Password};
            SetupMockUserRepo();
            var handler = new LoginRequestHandle(_mockUserRepo.Object);

            var response = handler.Handle(request);

            Assert.That(response.Status, Is.EqualTo(ResponseCodes.Success));
        }
        public void ReturnsFailureCodeIfAUserCouldNotBeFoundWithCredentials()
        {
            var request = new LoginRequest { Username = "******", Password = Password };
            SetupMockUserRepo();
            var handler = new LoginRequestHandle(_mockUserRepo.Object);

            var response = handler.Handle(request);

            Assert.That(response.Status, Is.EqualTo(ResponseCodes.LoginAndPasswordMismatch));
        }
Пример #24
0
            public void MapsRequestToViewModel()
            {
                var endpoint = TestableLoginEndpoint.Build(Session);
                var request = new LoginRequest();
                var expectedViewModel = new LoginViewModel();

                endpoint.MappingEngine.Setup(x => x.Map<LoginRequest, LoginViewModel>(request)).Returns(expectedViewModel);
                var viewModel = endpoint.Login(request);
                viewModel.ShouldEqual(expectedViewModel);
            }
        private bool authenticate(string user, string pass)
        {
            var request = new LoginRequest
                              {
                                  UserName = user,
                                  Password = pass
                              };

            return theService.Authenticate(request);
        }
        public void Redirect(LoginRequest request)
        {
            var url = request.Url;
            if (url.IsEmpty())
            {
                url = "~/";
            }

            _writer.RedirectToUrl(url);
        }
Пример #27
0
        public object Any(LoginRequest request)
        {
            AutoMapper.Mapper.CreateMap<LoginRequest, LoginRequestModel>();
            var requestModel = AutoMapper.Mapper.Map<LoginRequestModel>(request);

            var repo = new MemberRepository().Login(requestModel);

            AutoMapper.Mapper.CreateMap<LoginResponseModel, LoginResponse>();
            return AutoMapper.Mapper.Map<LoginResponse>(repo);

        }
Пример #28
0
        public FubuContinuation post_login(LoginRequest request)
        {
            bool authenticated = _service.Authenticate(request);

            _service.SetRememberMeCookie(request);

            if (authenticated)
            {
                return _handler.LoggedIn(request);
            }

            return FubuContinuation.TransferTo(request, "GET");
        }
        public FubuContinuation post_login(LoginRequest request)
        {
            _auditor.ApplyHistory(request);

            var authenticated = _service.Authenticate(request);
            _auditor.Audit(request);

            if (authenticated)
            {
                return _handler.LoggedIn(request);
            }

            return FubuContinuation.TransferTo(request, "GET");
        }
Пример #30
0
        /// <summary>
        /// Login to the system.
        /// </summary>
        /// <param name="username">User name.</param>
        /// <param name="password">Password.</param>
        /// <returns>Success or failure flag.</returns>
        public bool Login(string username, string password)
        {
            LoginRequest request = new LoginRequest();
            request.RequestId = NewRequestId;
            request.ClientTag = ClientTag;
            request.AccessToken = AccessToken;

            request.UserName = username;
            request.Password = password;

            LoginResponse response = ActionServiceClient.Login(request);

            return (response.Acknowledge == AcknowledgeType.Success);
        }
Пример #31
0
 public async Task <ActionResult <User> > Login(LoginRequest model)
 {
     return(await _context.Users.FirstOrDefaultAsync(u => u.Email == model.Email && u.Password == model.Password));
 }
Пример #32
0
        //[ValidateAntiForgeryToken] only applied for cookies? http://angular-tips.com/blog/2014/05/json-web-tokens-introduction/
        public async Task <IActionResult> Login([FromBody] LoginRequest model)
        {
            // check if we are in the context of an authorization request
            var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

            //// the user clicked the "cancel" button
            //if (button != "login")
            //{
            //    if (context != null)
            //    {
            //        // if the user cancels, send a result back into IdentityServer as if they
            //        // denied the consent (even if this client does not require consent).
            //        // this will send back an access denied OIDC error response to the client.
            //        await _interaction.GrantConsentAsync(context, ConsentResponse.Denied);

            //        // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
            //        if (await _clientStore.IsPkceClientAsync(context.ClientId))
            //        {
            //            // if the client is PKCE then we assume it's native, so this change in how to
            //            // return the response is for better UX for the end user.
            //            return View("Redirect", new RedirectViewModel { RedirectUrl = model.ReturnUrl });
            //        }

            //        return Redirect(model.ReturnUrl);
            //    }
            //    else
            //    {
            //        // since we don't have a valid context, then we just go back to the home page
            //        return Redirect("~/");
            //    }
            //}

            if (ModelState.IsValid)
            {
                // validate username/password against in-memory store
                if (_users.ValidateCredentials(model.Username, model.Password))
                {
                    var user = _users.FindByUsername(model.Username);
                    await _events.RaiseAsync(new UserLoginSuccessEvent(user.Username, user.SubjectId, user.Username, clientId : context?.ClientId));

                    // only set explicit expiration here if user chooses "remember me".
                    // otherwise we rely upon expiration configured in cookie middleware.
                    AuthenticationProperties props = null;
                    if (model.RememberMe)
                    {
                        props = new AuthenticationProperties
                        {
                            IsPersistent = true,
                            ExpiresUtc   = DateTimeOffset.UtcNow.Add(TimeSpan.FromDays(30))
                        };
                    }
                    ;

                    // issue authentication cookie with subject ID and username
                    await HttpContext.SignInAsync(user.SubjectId, user.Username, props);

                    if (context != null)
                    {
                        if (await _clientStore.IsPkceClientAsync(context.ClientId))
                        {
                            // if the client is PKCE then we assume it's native, so this change in how to
                            // return the response is for better UX for the end user.
                            //return View("Redirect", new RedirectViewModel { RedirectUrl = model.ReturnUrl });
                        }

                        // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                        return(Redirect(model.ReturnUrl));
                    }

                    // request for a local page
                    if (Url.IsLocalUrl(model.ReturnUrl))
                    {
                        return(Redirect(model.ReturnUrl));
                    }
                    else if (string.IsNullOrEmpty(model.ReturnUrl))
                    {
                        return(Redirect("~/"));
                    }
                    else
                    {
                        // user might have clicked on a malicious link - should be logged
                        throw new Exception("invalid return URL");
                    }
                }

                await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials", clientId : context?.ClientId));

                return(new JsonResult("{'error':'Invalid username or password'}"));
            }

            //// something went wrong, show form with error
            //var vm = await BuildLoginViewModelAsync(model);
            //return View(vm);
            return(NotFound());
        }
Пример #33
0
        /**
         * Login.
         * Returns an access token if successful, along with the access token's expiry time.
         */
        public static async Task <Tuple <string, DateTime> > Login(AmazonDynamoDBClient dbClient, LoginRequest loginRequest)
        {
            Debug.Tested();
            Debug.AssertValid(dbClient);
            Debug.AssertValid(loginRequest);
            Debug.AssertEmail(loginRequest.emailAddress);
            Debug.AssertString(loginRequest.password);

            // Find user with email and password hash
            //??--User user = IdentityServiceLogicLayer.Users.Find(u => (u.EmailAddress == loginRequest.emailAddress));
            User user = await IdentityServiceDataLayer.FindUserByEmailAddress(dbClient, loginRequest.emailAddress);

            Debug.AssertValidOrNull(user);
            if (user != null)
            {
                // User found with specified email address
                Debug.Tested();
                Debug.AssertID(user.ID);
                if (user.Closed != null)
                {
                    Debug.Tested();
                    throw new Exception(IdentityServiceLogicLayer.ERROR_USER_ACCOUNT_CLOSED);
                }
                else if (user.Blocked)
                {
                    Debug.Tested();
                    throw new Exception(IdentityServiceLogicLayer.ERROR_USER_BLOCKED);
                }
                else if (user.Locked)
                {
                    Debug.Tested();
                    throw new Exception(IdentityServiceLogicLayer.ERROR_USER_LOCKED);
                }
                else
                {
                    // User is not closed, blocked or locked.
                    Debug.Tested();
                    if (user.PasswordHash == Helper.Hash(loginRequest.password))
                    {
                        // Correct password - log the user in.
                        Debug.Tested();
                        // Invalidate any existing access tokens
                        await IdentityServiceLogicLayer.InvalidateUserAccessTokens(dbClient, user.ID);

                        // Set the last login time to now
                        user.LastLoggedIn = DateTime.Now;
                        // Mark failed login attempts as zero
                        user.FailedLoginAttempts = 0;

                        // Save the user
                        await IdentityServiceDataLayer.SaveUser(dbClient, user);

                        // Create a new access token
                        //??--Int64 accessTokenLifetime = (Int64)GetIdentityGlobalSetting(GLOBAL_SETTING_ACCESS_TOKEN_LIFETIME, DEFAULT_ACCESS_TOKEN_LIFETIME);
                        Int64 accessTokenLifetime = await IdentityServiceLogicLayer.GetInt64IdentityGlobalSetting(dbClient, IdentityServiceLogicLayer.GLOBAL_SETTING_ACCESS_TOKEN_LIFETIME, IdentityServiceLogicLayer.DEFAULT_ACCESS_TOKEN_LIFETIME);

                        AccessToken accessToken = new AccessToken()
                        {
                            ID      = RandomHelper.Next().ToString(),
                            UserID  = user.ID,
                            Expires = DateTime.Now.AddSeconds(accessTokenLifetime)
                        };
                        // Setup the access token max expiry time
                        //??--Int64 maxUserLoginTime = (Int64)GetIdentityGlobalSetting(GLOBAL_SETTING_MAX_USER_LOGIN_TIME, DEFAULT_MAX_USER_LOGIN_TIME);
                        Int64 maxUserLoginTime = await IdentityServiceLogicLayer.GetInt64IdentityGlobalSetting(dbClient, IdentityServiceLogicLayer.GLOBAL_SETTING_MAX_USER_LOGIN_TIME, IdentityServiceLogicLayer.DEFAULT_MAX_USER_LOGIN_TIME);

                        if ((user.MaxTimeLoggedIn == null) || (user.MaxTimeLoggedIn == 0))
                        {
                            Debug.Tested();
                            if (maxUserLoginTime != 0)
                            {
                                Debug.Tested();
                                accessToken.MaxExpiry = DateTime.Now.AddMinutes((UInt64)maxUserLoginTime);
                            }
                            else
                            {
                                Debug.Tested();
                            }
                        }
                        else
                        {
                            Debug.Tested();
                            if (maxUserLoginTime != 0)
                            {
                                Debug.Untested();
                                UInt64 maxUserLoginTime_ = Math.Min((UInt64)maxUserLoginTime, (UInt64)user.MaxTimeLoggedIn);
                                accessToken.MaxExpiry = DateTime.Now.AddMinutes(maxUserLoginTime_);
                            }
                            else
                            {
                                Debug.Tested();
                                accessToken.MaxExpiry = DateTime.Now.AddMinutes((UInt64)user.MaxTimeLoggedIn);
                            }
                        }
                        // Ensure the max expiry has not been exceeded
                        if ((accessToken.MaxExpiry != null) && (accessToken.Expires > accessToken.MaxExpiry))
                        {
                            Debug.Untested();
                            accessToken.Expires = (DateTime)accessToken.MaxExpiry;
                        }
                        else
                        {
                            Debug.Tested();
                        }
                        // Add the access token
                        //??--AccessTokens.Add(accessToken.ID, accessToken);
                        await IdentityServiceDataLayer.AddAccessToken(dbClient, accessToken);

                        // Return the access token ID and expiry date/time
                        //??--expiryTime = accessToken.Expires;
                        return(new Tuple <string, DateTime>(accessToken.ID, (DateTime)accessToken.Expires));
                    }
                    else
                    {
                        // Incorrect password
                        Debug.Tested();
                        //??--Int16 maxLoginAttempts = (Int16)GetIdentityGlobalSetting(GLOBAL_SETTING_LOCK_ON_FAILED_LOGIN_ATTEMPTS, DEFAULT_MAX_LOGIN_ATTEMPTS);
                        Int64 maxLoginAttempts = await IdentityServiceLogicLayer.GetInt64IdentityGlobalSetting(dbClient, IdentityServiceLogicLayer.GLOBAL_SETTING_LOCK_ON_FAILED_LOGIN_ATTEMPTS, IdentityServiceLogicLayer.DEFAULT_MAX_LOGIN_ATTEMPTS);

                        if (++user.FailedLoginAttempts == maxLoginAttempts)
                        {
                            // Too many password attempts - user locked.
                            Debug.Tested();
                            user.Locked = true;

                            // Save the user
                            await IdentityServiceDataLayer.SaveUser(dbClient, user);

                            throw new Exception(IdentityServiceLogicLayer.ERROR_USER_LOCKED);
                        }
                        else
                        {
                            Debug.Tested();
                            throw new Exception(IdentityServiceLogicLayer.ERROR_INCORRECT_PASSWORD);
                        }
                    }
                }
            }
            else
            {
                Debug.Tested();
                throw new Exception(SharedLogicLayer.ERROR_UNRECOGNIZED_EMAIL_ADDRESS);
            }
        }
Пример #34
0
        public async Task <string> Login(LoginRequest request)
        {
            var res = await _seltronFacade.Login(request.Username, request.Password);

            return("OK");
        }
Пример #35
0
 public async Task <string> Authencate(LoginRequest request)
 {
     return(await userRepository.Authencate(request));
 }
 public Task <LoginResponse> LoginUsingFacebook(LoginRequest loginRequest, string issuer)
 {
     throw new NotImplementedException("Feature not implemented !!");
 }
Пример #37
0
        public async Task <UserManagerResponse> LoginAsync(LoginRequest request)
        {
            var response = await client.PostAsync <UserManagerResponse>($"{_baseUrl}/api/auth/login", request);

            return(response.Result);
        }
Пример #38
0
 void Start()
 {
     loginRequest = GetComponent <LoginRequest>();
 }
Пример #39
0
 public async Task <Login> Login(LoginRequest request)
 {
     return(await _authService.Login(request));
 }
Пример #40
0
        async void OnLoginButtonClicked(object sender, EventArgs e)
        {
            string message = String.Empty;
            HttpResponseMessage httpResponse = new HttpResponseMessage();

            Login.IsEnabled = false;
            PopupImagePage waiting = new PopupImagePage(null, String.Empty);

            try
            {
                HttpClient client = new HttpClient();

                //client.Timeout = new TimeSpan(0, 0, 0, 3, 0); //if this is uncommented - the timeout value is NOT respected

                client.BaseAddress = new Uri(((App)App.Current).LAN_Address);

                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));

                User = this.Name.Text;
                Pwd  = this.Password.Text;

                client.DefaultRequestHeaders.Add("EO-Header", User + " : " + Pwd);

                LoginRequest request = new LoginRequest(User, Pwd);

                string jsonData = JsonConvert.SerializeObject(request);
                var    content  = new StringContent(jsonData, Encoding.UTF8, "application/json");

                Navigation.PushPopupAsync(waiting);

                httpResponse = await client.PostAsync("api/Login/Login", content);

                Navigation.PopPopupAsync();

                if (httpResponse.IsSuccessStatusCode)
                {
                    IEnumerable <string> values;
                    httpResponse.Headers.TryGetValues("EO-Header", out values);
                    if (values != null && values.ToList().Count == 1)
                    {
                        Stream streamData = await httpResponse.Content.ReadAsStreamAsync();

                        StreamReader  strReader     = new StreamReader(streamData);
                        string        strData       = strReader.ReadToEnd();
                        LoginResponse loginResponse = JsonConvert.DeserializeObject <LoginResponse>(strData);

                        ((App)App.Current).User = User;
                        ((App)App.Current).Role = loginResponse.RoleId;

                        if (loginResponse.RoleId == 1)
                        {
                            if (!Navigation.NavigationStack.Any(p => p is DashboardPage))
                            {
                                await Navigation.PushAsync(new DashboardPage());
                            }
                        }
                        else
                        {
                            if (!Navigation.NavigationStack.Any(p => p is MainPage))
                            {
                                await Navigation.PushAsync(new MainPage());
                            }
                        }

                        this.Name.Text     = String.Empty;
                        this.Password.Text = String.Empty;
                    }
                }
                else
                {
                    if (httpResponse.StatusCode == System.Net.HttpStatusCode.Forbidden ||
                        httpResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                    {
                        message = "Unrecognized username / password";
                    }
                }
            }
            catch (Exception ex)
            {
                Navigation.PopPopupAsync();

                if (ex.Message.Contains("failed to connect"))
                {
                    message = "Device not connected to network.";
                }
                else
                {
                    message = "Could not connect to server.";
                }
            }
            finally
            {
                if (!String.IsNullOrEmpty(message))
                {
                    await DisplayAlert("Error", message, "Cancel");
                }

                Login.IsEnabled = true;
            }
        }
 public override void DeSerialize(MemoryStream stream)
 {
     data = ProtoBuf.Serializer.Deserialize <LoginRequest>(stream);
 }
Пример #42
0
        private EmployeeInfo AuthenticateLogin(LoginRequest loginInfo)
        {
            EmployeeInfo employeeInfo = _context.EmployeeInfo.FirstOrDefault(x => x.EmployeeEmail == loginInfo.EmployeeEmail && x.Password == loginInfo.Password);

            return(employeeInfo);
        }
Пример #43
0
 public async Task <Response> LoginAsync(LoginRequest request, CancellationToken cancellationToken)
 {
     return(await client.LoginAsync(request, cancellationToken : cancellationToken));
 }
Пример #44
0
 /// <inheritdoc/>
 public async Task <BearerAuthenticationResult> RequestTokenAsync(LoginRequest loginRequest)
 {
     return(await this.PostAsync <LoginRequest, BearerAuthenticationResult>("/api/auth/login", loginRequest));
 }
Пример #45
0
        public async Task <IActionResult> Login([FromForm] LoginRequest request)
        {
            var user = await _context.Users
                       .Where(x => x.Email == request.Email.Trim()).FirstOrDefaultAsync();

            if (user == null)
            {
                return(BadRequest(new
                {
                    Message = "UserName or Password is not correct!"
                }));
            }

            if (user.TypeAccount != ETypeAccount.System)
            {
                return(BadRequest(new
                {
                    Message = "Please login with " + user.TypeAccount.ToString()
                }));
            }

            if (user.PassWord != request.Password.Trim())
            {
                return(BadRequest(new
                {
                    Message = "UserName or Password is not correct!"
                }));
            }

            if (user.Status == EUserStatus.IsVerifying)
            {
                var info = new LoginInfo()
                {
                    Email           = user.Email,
                    FullName        = user.FullName,
                    IsMailConfirmed = false,
                    Message         = MessageMail.VerifyMail,
                    UserId          = user.Id,
                    UserName        = user.UserName
                };

                return(BadRequest(new
                {
                    Message = MessageMail.VerifyMail
                }));
            }

            if (user.Status == EUserStatus.Inactive)
            {
                return(BadRequest(new
                {
                    Message = "Your account has been locked!"
                }));
            }

            var userResponse = new UserResponse(user, _storageService);

            userResponse.Token = this.GenerateJSONWebToken(user);

            //_sessionService.SetSessionUser(user);

            return(Ok(userResponse));
        }
Пример #46
0
        //public async Task SendPasswordLinkReset(ForgotPassword forgotPassword)
        //{
        //    await api.SendPasswordLinkReset(forgotPassword);
        //}
        public async Task Login(LoginRequest loginParameters)
        {
            await api.Login(loginParameters);

            NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
        }
Пример #47
0
        public async Task <IActionResult> Login(LoginRequest request)
        {
            var result = await _authService.LoginUser(request);

            return(Ok(result));
        }
 public TokenAutenticacaoModel Login([FromBody] LoginRequest request) => null;
        public NegotiatedContentResult <LoginResponse> PostLogin([FromBody] LoginRequest request)
        {
            LoginResponse resp = AgentBossServices.Login(request);

            return(Content(HttpStatusCode.OK, resp));
        }
Пример #50
0
        public void Login(LoginRequest request)
        {
            this.Validator.Validate(request);

            this.FxSession.login(request.Username, request.Password, request.Url, request.AccountType);
        }
Пример #51
0
 public async Task <LoginResponse> Login(LoginRequest loginRequest)
 {
     return(await _ICommonRepository.Login(loginRequest));
 }
Пример #52
0
        static void Main(string[] args)
        {
            //Connect
            TcpClient tcpClient = new TcpClient();

            tcpClient.Connect("localhost", 3334);
            MessageSender   messageSender   = new MessageSender(tcpClient.Session);
            MessageReceiver messageReceiver = new MessageReceiver(tcpClient.Session);
            MessageExecutor messageExecutor =
                new MessageExecutor(messageSender, messageReceiver, new InstantTaskScheduler());

            messageExecutor.Configuration.DefaultTimeout = 10000;
            var notificationListener = new NotificationListener();

            messageReceiver.AddListener(-1, notificationListener);

            //auth
            AuthorizeHciRequest request = new AuthorizeHciRequest();

            request.ClientId = -1;
            request.Locale   = "en-US";
            var future = messageExecutor.Submit <AuthorizeHciResponse>(request);

            future.Wait();
            AuthorizeHciResponse AuthorizeHciResponse = future.Value;
            int clientId = AuthorizeHciResponse.ClientId;

            System.Console.WriteLine("AuthorizeHciResponse precessed");

            //login
            LoginRequest loginRequest = new LoginRequest();

            loginRequest.UserLogin    = "******";
            loginRequest.UserPassword = "******";
            loginRequest.ClientId     = clientId;
            var loginResponcetask = messageExecutor.Submit <LoginResponse>(loginRequest);

            loginResponcetask.Wait();

            // Id of the emu-copter is 2
            var vehicleToControl = new Vehicle {
                Id = 3
            };

            TcpClientt.TcpListener server = new TcpClientt.TcpListener(IPAddress.Any, 8080);
            server.Start(); // run server
            byte[] ok = new byte[100];
            ok = Encoding.Default.GetBytes("ok");
            while (true) // бесконечный цикл обслуживания клиентов
            {
                TcpClientt.TcpClient     client = server.AcceptTcpClient();
                TcpClientt.NetworkStream ns     = client.GetStream();
                while (client.Connected)
                {
                    byte[] msg   = new byte[100];
                    int    count = ns.Read(msg, 0, msg.Length);
                    Console.Write(Encoding.Default.GetString(msg, 0, count));
                    string allMessage  = Encoding.Default.GetString(msg);
                    string result      = allMessage.Substring(0, count - 1);
                    var    commandName = result.ToString().Split(":")[0];


                    switch (commandName)
                    {
                    case "takeoff_command":
                    {
                        Console.Write("got command: {0}", commandName);

                        SendCommandRequest takeoff = new SendCommandRequest
                        {
                            ClientId = clientId,
                            Command  = new Command
                            {
                                Code              = "takeoff_command",
                                Subsystem         = Subsystem.S_FLIGHT_CONTROLLER,
                                Silent            = true,
                                ResultIndifferent = true
                            }
                        };
                        takeoff.Vehicles.Add(vehicleToControl);
                        var takeoffCmd = messageExecutor.Submit <SendCommandResponse>(takeoff);
                        takeoffCmd.Wait();
                        Thread.Sleep(5000);
                        ns.Write(ok, 0, ok.Length);
                        break;
                    }

                    case "direct_vehicle_control":
                    {
                        Console.Write("got command: {0}", commandName);
                        var commandArgs = result.Split(":")[1];
                        Console.Write("args of command: {0}", commandArgs);
                        // Vehicle control in joystick mode
                        SendCommandRequest vehicleJoystickControl = new SendCommandRequest
                        {
                            ClientId = clientId,
                            Command  = new UGCS.Sdk.Protocol.Encoding.Command
                            {
                                Code              = "direct_vehicle_control",
                                Subsystem         = Subsystem.S_FLIGHT_CONTROLLER,
                                Silent            = true,
                                ResultIndifferent = true
                            }
                        };


                        vehicleJoystickControl.Vehicles.Add(vehicleToControl);

                        List <CommandArgument> listJoystickCommands = new List <CommandArgument>();
                        var    directionCommand = commandArgs.ToString().Split(",")[0];
                        string commandValueStr  = commandArgs.ToString().Split(",")[1];
                        double commandValue     = double.Parse(commandValueStr,
                                                               System.Globalization.CultureInfo.InvariantCulture);

                        switch (directionCommand)
                        {
                        case "roll":
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "roll",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "pitch",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "yaw",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "throttle",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            break;

                        case "pitch":
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "pitch",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "roll",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "yaw",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "throttle",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            break;

                        case "throttle":
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "throttle",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "pitch",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "roll",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "yaw",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            break;

                        case "yaw":
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "yaw",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "pitch",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "roll",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "throttle",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            break;
                        }


                        vehicleJoystickControl.Command.Arguments.AddRange(listJoystickCommands);
                        var sendJoystickCommandResponse =
                            messageExecutor.Submit <SendCommandResponse>(vehicleJoystickControl);
                        sendJoystickCommandResponse.Wait();
                        System.Console.WriteLine("Was sent {0}", commandValue);

                        Thread.Sleep(2000);
                        ns.Write(ok, 0, ok.Length);
                        break;
                    }

                    case "set_relative_heading":
                    {
                        Console.Write("got command: {0}", commandName);
                        var commandArgs = result.Split(":")[1];
                        Console.Write("args of command: {0}", commandArgs);
                        // Vehicle control in joystick mode
                        SendCommandRequest vehicleRelativeOffsetControl = new SendCommandRequest
                        {
                            ClientId = clientId,
                            Command  = new UGCS.Sdk.Protocol.Encoding.Command
                            {
                                Code              = "set_relative_heading",
                                Subsystem         = Subsystem.S_FLIGHT_CONTROLLER,
                                Silent            = false,
                                ResultIndifferent = false
                            }
                        };


                        vehicleRelativeOffsetControl.Vehicles.Add(vehicleToControl);

                        List <CommandArgument> listRelativeOffsetCommands = new List <CommandArgument>();
                        var    directionCommand = commandArgs.ToString().Split(",")[0];
                        string commandValueStr  = commandArgs.ToString().Split(",")[1];
                        double commandValue     = double.Parse(commandValueStr,
                                                               System.Globalization.CultureInfo.InvariantCulture);

                        switch (directionCommand)
                        {
                        case "relative_heading":
                            listRelativeOffsetCommands.Add(new CommandArgument
                                {
                                    Code  = "relative_heading",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            break;
                        }

                        vehicleRelativeOffsetControl.Command.Arguments.AddRange(listRelativeOffsetCommands);
                        var sendRelativeOffsetCommandResponse =
                            messageExecutor.Submit <SendCommandResponse>(vehicleRelativeOffsetControl);
                        sendRelativeOffsetCommandResponse.Wait();
                        System.Console.WriteLine("Was sent {0}", commandValue);

                        Thread.Sleep(2000);
                        ns.Write(ok, 0, ok.Length);
                        break;
                    }

                    case "set_position_offset":
                    {
                        Console.Write("got command: {0}", commandName);
                        var commandArgs = result.Split(":")[1];
                        Console.Write("args of command: {0}", commandArgs);
                        // Vehicle control in joystick mode
                        SendCommandRequest vehicleJoystickOffset = new SendCommandRequest
                        {
                            ClientId = clientId,
                            Command  = new UGCS.Sdk.Protocol.Encoding.Command
                            {
                                Code              = "set_position_offset",
                                Subsystem         = Subsystem.S_FLIGHT_CONTROLLER,
                                Silent            = false,
                                ResultIndifferent = false
                            }
                        };


                        vehicleJoystickOffset.Vehicles.Add(vehicleToControl);

                        List <CommandArgument> listJoystickOffsetCommands = new List <CommandArgument>();
                        var    directionCommand = commandArgs.ToString().Split(",")[0];
                        string commandValueStr  = commandArgs.ToString().Split(",")[1];
                        double commandValue     = double.Parse(commandValueStr,
                                                               System.Globalization.CultureInfo.InvariantCulture);

                        switch (directionCommand)
                        {
                        case "x":
                            listJoystickOffsetCommands.Add(new CommandArgument
                                {
                                    Code  = "x",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            listJoystickOffsetCommands.Add(new CommandArgument
                                {
                                    Code  = "y",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listJoystickOffsetCommands.Add(new CommandArgument
                                {
                                    Code  = "z",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            break;

                        case "y":
                            listJoystickOffsetCommands.Add(new CommandArgument
                                {
                                    Code  = "y",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            listJoystickOffsetCommands.Add(new CommandArgument
                                {
                                    Code  = "x",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listJoystickOffsetCommands.Add(new CommandArgument
                                {
                                    Code  = "z",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            break;

                        case "z":
                            listJoystickOffsetCommands.Add(new CommandArgument
                                {
                                    Code  = "z",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            listJoystickOffsetCommands.Add(new CommandArgument
                                {
                                    Code  = "y",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listJoystickOffsetCommands.Add(new CommandArgument
                                {
                                    Code  = "x",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            break;
                        }


                        vehicleJoystickOffset.Command.Arguments.AddRange(listJoystickOffsetCommands);
                        var sendJoystickOffsetResponse =
                            messageExecutor.Submit <SendCommandResponse>(vehicleJoystickOffset);
                        sendJoystickOffsetResponse.Wait();
                        System.Console.WriteLine("Was sent {0}", commandValue);

                        Thread.Sleep(2000);
                        ns.Write(ok, 0, ok.Length);
                        break;
                    }


                    case "payload_control":
                    {
                        Console.Write("got command: {0}", commandName);
                        var commandArgs = result.ToString().Split(":")[1];
                        Console.Write("args of command: {0}", commandArgs);
                        SendCommandRequest vehiclePayloadCommandRequest = new SendCommandRequest
                        {
                            ClientId = clientId,
                            Command  = new UGCS.Sdk.Protocol.Encoding.Command
                            {
                                Code              = "payload_control",
                                Subsystem         = Subsystem.S_CAMERA,
                                Silent            = false,
                                ResultIndifferent = false
                            }
                        };
                        vehiclePayloadCommandRequest.Vehicles.Add(vehicleToControl);
                        List <CommandArgument> listPayloadCommands = new List <CommandArgument>();
                        var    directionCommand = commandArgs.ToString().Split(",")[0];
                        string commandValueStr  = commandArgs.ToString().Split(",")[1];
                        double commandValue     = double.Parse(commandValueStr,
                                                               System.Globalization.CultureInfo.InvariantCulture);

                        switch (directionCommand)
                        {
                        case "tilt":
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "tilt",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "roll",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "yaw",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "zoom_level",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            break;

                        case "roll":
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "roll",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "tilt",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "yaw",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "zoom_level",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            break;

                        case "zoom_level":
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "zoom_level",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "tilt",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "roll",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "yaw",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            break;

                        case "yaw":
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "yaw",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "tilt",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "roll",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "zoom_level",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            break;
                        }

                        vehiclePayloadCommandRequest.Command.Arguments.AddRange(listPayloadCommands);
                        var sendPayloadCommandResponse =
                            messageExecutor.Submit <SendCommandResponse>(vehiclePayloadCommandRequest);
                        sendPayloadCommandResponse.Wait();
                        System.Console.WriteLine("Was sent {0}", commandValue);
                        Thread.Sleep(2000);
                        ns.Write(ok, 0, ok.Length);
                        break;
                    }

                    case "land_command":
                    {
                        SendCommandRequest land = new SendCommandRequest
                        {
                            ClientId = clientId,
                            Command  = new UGCS.Sdk.Protocol.Encoding.Command
                            {
                                Code              = "land_command",
                                Subsystem         = Subsystem.S_FLIGHT_CONTROLLER,
                                Silent            = false,
                                ResultIndifferent = false
                            }
                        };
                        land.Vehicles.Add(vehicleToControl);
                        var landCmd = messageExecutor.Submit <SendCommandResponse>(land);
                        landCmd.Wait();
                        Thread.Sleep(5000);
                        ns.Write(ok, 0, ok.Length);
                        break;
                    }

                    case "joystick":
                    {
                        SendCommandRequest joystickModeCommand = new SendCommandRequest
                        {
                            ClientId = clientId,
                            Command  = new UGCS.Sdk.Protocol.Encoding.Command
                            {
                                Code              = "joystick",
                                Subsystem         = Subsystem.S_FLIGHT_CONTROLLER,
                                Silent            = false,
                                ResultIndifferent = false
                            }
                        };

                        joystickModeCommand.Vehicles.Add(vehicleToControl);
                        var joystickMode = messageExecutor.Submit <SendCommandResponse>(joystickModeCommand);
                        joystickMode.Wait();
                        ns.Write(ok, 0, ok.Length);
                        break;
                    }

                    case "manual":
                    {
                        break;
                    }
                    }
                }

                // System.Console.ReadKey();
                // tcpClient.Close();
                // messageSender.Cancel();
                // messageReceiver.Cancel();
                // messageExecutor.Close();
                // notificationListener.Dispose();
            }
        }
Пример #53
0
 public async Task <ApiResponse <LoginResponse> > LoginAsync(LoginRequest loginRequest, CancellationToken cancellationToken = default)
 {
     return(await LoginAsyncInternal(loginRequest, cancellationToken));
 }
Пример #54
0
        public async Task <IActionResult> UserExists([FromBody] LoginRequest loginRequest)
        {
            Response result = await _userService.UserExists(loginRequest);

            return(Ok(result));
        }
Пример #55
0
 public async Task <IActionResult> AuthenticateUser([FromBody] LoginRequest model)
 {
     return(Ok(await _accountService.AuthenticateAsync(model)));
 }
Пример #56
0
        public Response <object> Login(LoginRequest loginRequest)
        {
            Response <object> result = new Response <object>();
            bool showCaptcha         = false;

            if (string.IsNullOrEmpty(loginRequest.account))
            {
                showCaptcha = OprateLoginCaptcha();
                result.data = new
                {
                    result      = false,
                    errorcode   = 1,
                    showcaptcha = showCaptcha
                };
                return(result);
            }

            Regex passwordRegex = new Regex("[A-Za-z].*[0-9]|[0-9].*[A-Za-z]");

            if (string.IsNullOrEmpty(loginRequest.password))
            {
                showCaptcha = OprateLoginCaptcha();
                result.data = new { result = false, errorcode = 2, showcaptcha = showCaptcha };
                return(result);
            }
            if (loginRequest.password == Encryption.SHA256Encrypt(Encryption.MD5(loginRequest.password)))
            {
                showCaptcha = OprateLoginCaptcha();
                result.data = new { result = false, errorcode = 2, showcaptcha = showCaptcha };
                return(result);
            }
            if (CaptchaDisplayHelper.IsDisplay(CaptchaDispalyType.Login) && !CaptchaImageHelper.Check(loginRequest.key, loginRequest.code))
            {
                CaptchaDisplayHelper.SetDisplay(CaptchaDispalyType.Login);
                result.data = new { result = false, errorcode = 6, showcaptcha = true };
                return(result);
            }

            //ResultOfUserLoginInfoDtoUserLoginReturnEnum loginResult = UserDataService.UserLoginValidation(loginRequest.account, Encryption.SHA256Encrypt(Encryption.MD5(loginRequest.password)));

            //if (loginResult == null)
            //{
            //    showCaptcha = OprateLoginCaptcha();

            //    result.data = new { result = false, errorcode = 7, showcaptcha = showCaptcha };
            //    return result;
            //}

            //switch (loginResult.Status)
            //{
            //    case UserLoginReturnEnum.Success:
            //        try
            //        {
            //            LogDataService.Log("Save The Login userInfo", LogType.SaveUserLoginInfo, $"userid={loginResult.Data.UserId};userIp={IPHelper.GetClicentIp()};userMacAddress={CommonTool.GetMacAddress()};");
            //        }
            //        catch (Exception ex)
            //        {
            //            LogDataService.Exception("Save The Login userInfo Exception", ex.Message, ex.Source, $"userid={loginResult.Data.UserId}");
            //        }

            //        break;
            //    case UserLoginReturnEnum.Closed://账户关闭,客户登录失败
            //        result.data = new { result = false, errorcode = 8 };
            //        return result;

            //    case UserLoginReturnEnum.NullOrEmpty:
            //        if (!loginRequest.isheadlogin)
            //        {
            //            showCaptcha = OprateLoginCaptcha();

            //        }
            //        result.data = new { result = false, errorcode = 9, showcaptcha = showCaptcha };
            //        return result;

            //    case UserLoginReturnEnum.SystemError:
            //        if (!loginRequest.isheadlogin)
            //        {
            //            showCaptcha = OprateLoginCaptcha();

            //        }
            //        result.data = new { result = false, errorcode = 10, showcaptcha = showCaptcha };
            //        return result;

            //    case UserLoginReturnEnum.UnActivate:
            //        LoginSuccessOprate(loginResult.Data.UserId, loginResult.Data.UserName, loginRequest.key, loginRequest.remember, loginRequest.account);
            //        result.data = new { result = false, errorcode = 11, userid = loginResult.Data.UserId };
            //        return result;
            //    case UserLoginReturnEnum.UnFound:
            //        showCaptcha = OprateLoginCaptcha();
            //        result.data = new { result = false, errorcode = 12, showcaptcha = showCaptcha };
            //        return result;
            //}

            //LoginSuccessOprate(loginResult.Data.UserId, loginResult.Data.UserName, loginRequest.key, loginRequest.remember, loginRequest.account);
            //播种Cookie种子
            //var seed = new CookiesPlant().GetSeed();
            //SowCookie("SEED", seed, false, DateTime.MaxValue);

            result.data = new { result = true };
            return(result);
        }
Пример #57
0
 public async Task <User> ValidateUserAsync(LoginRequest rqst) => await _unitOfWork.Users.Find(x => x.UserName == rqst.UserName && x.Password == rqst.Password).SingleOrDefaultAsync();
Пример #58
0
        public async Task <IActionResult> Login([FromBody] LoginRequest request)
        {
            GenericResponse <LoginResponse> response;

            try
            {
                string          patron        = config["AppSettings:PatronConfig"];
                LoginWithPatron requestPatron = new LoginWithPatron()
                {
                    pass_user = request.pass_user,
                    username  = request.username,
                    Patron    = patron
                };

                //Consulta al useCase LoginUsuario, encargado de devolvernos el registro de usuario si llegace a existir en la base.
                var item = await useCase.LoginUsuario(requestPatron);


                //Validar que el username no sea null
                if (item != null && !string.IsNullOrEmpty(item.username))
                {
                    //validar que usuario no esté inactivo
                    if (item.Estado == 0)
                    {
                        LoginResponse loginResponseUnauthorized = new LoginResponse()
                        {
                            Jwt            = "0",
                            ExpirationDate = DateTime.Today.AddDays(-1)
                                             //Se devuelve el LoginResponse sin token
                        };
                        response = new GenericResponse <LoginResponse>()
                        {
                            Item   = loginResponseUnauthorized,
                            status = new HttpCodeStatus()
                            {
                                Code        = System.Net.HttpStatusCode.Unauthorized,
                                Description = "USUARIO INHABILITADO"
                            }
                        };
                        //Se manda el Gererin response indicando que usuario está inhabilitado
                    }
                    else
                    {
                        //Si sse especifica
                        var tokenHandler    = new JwtSecurityTokenHandler();
                        var key             = Encoding.ASCII.GetBytes(config["JWT:key"]);
                        var tokenDescriptor = new SecurityTokenDescriptor
                        {
                            Subject = new ClaimsIdentity(new Claim[]
                            {
                                new Claim(ClaimTypes.Name, $"{item.nombre_user}"),
                                new Claim(ClaimTypes.Email, $"{item.email_user}")
                            }),
                            Audience           = request.username,
                            IssuedAt           = DateTime.UtcNow,
                            Issuer             = config["JWT:Issuer"],
                            Expires            = DateTime.UtcNow.AddMinutes(300),//Caducidad de 5 horas
                            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                        };
                        tokenDescriptor.Subject.AddClaim(new Claim(ClaimTypes.Sid, item.email_user));
                        if (!string.IsNullOrEmpty(item.email_user))
                        {
                            tokenDescriptor.Subject.AddClaim(new Claim(ClaimTypes.Email, item.email_user));
                        }
                        var    securityToken = tokenHandler.CreateToken(tokenDescriptor);
                        string Token         = tokenHandler.WriteToken(securityToken);

                        LoginResponse loginResponse = new LoginResponse()
                        {
                            Jwt            = Token,
                            ExpirationDate = tokenDescriptor.Expires.Value
                        };
                        response = new GenericResponse <LoginResponse>()
                        {
                            Item   = loginResponse,
                            status = new HttpCodeStatus()
                            {
                                Code        = System.Net.HttpStatusCode.OK,
                                Description = "OK"
                            }
                        };
                    }
                }
                else
                {
                    response = new GenericResponse <LoginResponse>()
                    {
                        status = new HttpCodeStatus()
                        {
                            Code        = System.Net.HttpStatusCode.NotFound,
                            Description = $"No se ha encontrado el usuario con nombre {request.username}"
                        }
                    }
                };
                return(Ok(response));
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{ex.Message} {ex.InnerException?.Message}");
                response = new GenericResponse <LoginResponse>()
                {
                    status = new HttpCodeStatus()
                    {
                        Code        = System.Net.HttpStatusCode.InternalServerError,
                        Description = ex.Message
                    }
                };
                return(StatusCode(StatusCodes.Status500InternalServerError, response));
            }
        }
Пример #59
0
            public Boolean requestLogin()
            {
                loginCount++;

                if (loginCount >= 5)
                {
                    return(false);
                }

                string path = @"C:\token.txt";

                string token = null;//readAuthToken(path);

                if (token == null)
                {
                    try
                    {
                        RecaptchaSolver Solver = new RecaptchaSolver();
                        Solver.solve();
                        //token = Solver.realResult;
                        Console.WriteLine("real reslt= " + Solver.realResult);


                        var request = (HttpWebRequest)WebRequest.Create("https://dev.golike.net/api/login");

                        //var postData = "username="******"nonamekkbk");
                        //postData += "&password="******"cuocsong@@!11235");
                        //postData += "&re_captcha_token=" + Uri.EscapeDataString(Solver.realResult);

                        LoginRequest loginReq = new LoginRequest();
                        loginReq.username         = "******";
                        loginReq.password         = "******";
                        loginReq.re_captcha_token = Solver.realResult;

                        string datastr = JsonConvert.SerializeObject(loginReq);

                        Console.WriteLine("data = " + datastr);

                        Thread.Sleep(10000);

                        var data = Encoding.UTF8.GetBytes(datastr);

                        request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36";
                        request.Method    = "POST";
                        request.Headers.Add("t", "VFZSVk5VNTZWVEpOVkZVd1RVRTlQUT09");
                        request.ContentType   = "application/json;charset=utf-8";
                        request.ContentLength = data.Length;


                        using (var stream = request.GetRequestStream())
                        {
                            stream.Write(data, 0, data.Length);
                        }

                        //if (response.)

                        var response = (HttpWebResponse)request.GetResponse();

                        if (response.StatusCode != HttpStatusCode.OK)
                        {
                            doInBackground(null, null);
                        }
                        else
                        {
                            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
                            Console.WriteLine(responseString);

                            LoginResponse res = JsonConvert.DeserializeObject <LoginResponse>(responseString);

                            writeAuthToken(res.token, path);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                        doInBackground(null, null);
                    }
                }

                return(true);
            }
Пример #60
0
 public IActionResult Login([FromBody] LoginRequest request)
 {
     return(Ok(_authenticationModule.Login(request)));
 }