Ejemplo n.º 1
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 LoginResponse Login(NetworkCredential cred)
        {
            RobloxLoginRequest loginData = new RobloxLoginRequest();
            loginData.username = cred.UserName;
            loginData.password = cred.Password;
            CookieContainer container;

            var request = (HttpWebRequest)WebRequest.Create("https://www.roblox.com/MobileAPI/Login");

            request.Method = "POST";
            request.ContentType = "application/json";
            var buffer = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(loginData));
            request.ContentLength = buffer.Length;
            var requestStream = request.GetRequestStream();
            requestStream.Write(buffer, 0, buffer.Length);
            requestStream.Close();

            container = request.CookieContainer = new CookieContainer();

            var response = request.GetResponse();
            LoginResponse resp = new LoginResponse();
            string raw = "";
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                raw = reader.ReadToEnd();
                resp = JsonConvert.DeserializeObject<LoginResponse>(raw);
                resp.Raw = raw;
            }
            response.Close();
            CookieContainer = container;

            return resp;
        }
        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;
        }
Ejemplo n.º 4
0
        public LoginResponse SignIn(string loginname, string password)
        {
            var response = new LoginResponse();

            try
            {
                // Authenticate the customer
                var authenticateUserResponse = Exigo.WebService().AuthenticateUser(new AuthenticateUserRequest
                {
                    LoginName = loginname,
                    Password = password
                });

                if (authenticateUserResponse.Result.Status == ResultStatus.Failure)
                {
                    response.Fail("Unable to authenticate");
                    return response;
                }

                CreateFormsAuthenticationTicket(loginname, authenticateUserResponse);

                // Mark the response as successful
                response.Success();
            }
            catch (Exception ex)
            {
                response.Fail(ex.Message);
            }

            return response;
        }
Ejemplo n.º 5
0
		private void OnLoginSucc(LoginResponse response)
		{
			response.Framework.InitUserSerssion(
				response.userId,
				response.Response.Headers [LoginRequest.COOKIE_ID]
			);
			didLogin = true;
		}
Ejemplo n.º 6
0
 private void onLogin(LoginResponse response)
 {
     if ((response != null) && (response.IbAuthCookie.Length > 0))
     {
         configuration.Authentication.Type = OneApi.Model.Authentication.AuthType.IBSSO;
         configuration.Authentication.IbssoToken = response.IbAuthCookie;
     }
 }
Ejemplo n.º 7
0
	public static void SavePassword (HttpResponse response, LoginResponse ws_response)
	{
		HttpCookie cookie = new HttpCookie ("cookie", ws_response.Cookie);
		cookie.Expires = DateTime.Now.AddDays (1);
		response.Cookies.Add (cookie);
		HttpCookie person = new HttpCookie ("user", ws_response.User);
		person.Expires = DateTime.Now.AddDays (1);
		response.Cookies.Add (person);
	}
        private static byte[] getBytes(LoginResponse response, String uuid)
        {
            List<Byte> bytes = new List<byte>();

            bytes.Add(response.getResponse());
            bytes.Add((byte)0x0);
            foreach (byte b in NetUtils.stringToBytes(uuid))
                bytes.Add(b);

            return NetUtils.byteListToArray(bytes);
        }
Ejemplo n.º 9
0
 public void LoginCallback(LoginResponse response)
 {
     if (!response.isSuccessful)
         errorText.text = response.errorMessage;
     else
     {
         LoginInformation.username = usernameInputField.text;
         LoginInformation.guid = new Guid(response.userId);
         LoginInformation.loggedIn = true;
         MenuManager.instance.ChangePanel(MenuManager.instance.startupGui);
     }
 }
Ejemplo n.º 10
0
       async  void LoginBAL_OnLogonCompleted(int arg1, string arg2)
        {
            LoginBAL.OnLogonCompleted -= LoginBAL_OnLogonCompleted;

            if (arg1 == 200 && !string.IsNullOrEmpty(arg2))
            {

                string resp = Utilities.RemoveNameSpace.RemoveAllNamespaces(arg2.ToString());
                XDocument document = XDocument.Parse(resp);
                var XMLresult = document.Root.Descendants("LoginResponse");
                LoginResponse _LoginResponse = new LoginResponse();
                foreach (var item in XMLresult)
                {
                    _LoginResponse = CommonFUnction.DeSerializeData<LoginResponse>(_LoginResponse, item.ToString());
                   
                    break;
                }
                if (_LoginResponse != null && _LoginResponse.LoginResult != null && _LoginResponse.LoginResult.Headers != null)
                {
                    StateUtilities.LoginHeaders = _LoginResponse.LoginResult.Headers;
                    if (StateUtilities.LoginHeaders != null && !string.IsNullOrEmpty(StateUtilities.LoginHeaders.LoginResponse) && (StateUtilities.LoginHeaders.LoginResponse == "UsernameInvalid" || StateUtilities.LoginHeaders.LoginResponse == "PasswordInvalid"))
                    {
                        if (OnLogonCompleted != null)
                            OnLogonCompleted(900, arg2);
                    }
                    else
                    {
                        StateUtilities.LoginHeaders.URL = AppConstants.BaseURl;

                        await App.Connection.ExecuteAsync("delete from Headers");
                        await App.Connection.InsertAsync(StateUtilities.LoginHeaders);

                        if (OnLogonCompleted != null)
                            OnLogonCompleted(arg1, arg2);
                    }
                }
                else
                {
                    if (OnLogonCompleted != null)
                        OnLogonCompleted(arg1, arg2);
                }
            }
            else
            {
                if (OnLogonCompleted != null)
                    OnLogonCompleted(900, arg2);
            }
        }
Ejemplo n.º 11
0
        public void AuthorizeWithPinCompleted_ShouldNotifyUser()
        {
            const string successMessage = "You have successfully authorized NGTweet to access Twitter.";

            LoginResponse loginResponse = new LoginResponse { OAuthAccessToken = new OAuthAccessToken() };

            Mock.Get(_mockAuthenticationService)
                .Setup(m => m.EndLogin(It.IsAny<IAsyncResult>()))
                .Returns(loginResponse);

            Mock.Get(_mockApplicationSettingsProvider)
                .SetupSet(m => m["accessToken"] = loginResponse.OAuthAccessToken);

            _viewModel.AuthorizeWithPinCompleted(new Mock<IAsyncResult>().Object);

            Assert.IsFalse(_viewModel.IsVerificationDetailsVisible);

            Mock.Get(_mockApplicationSettingsProvider).VerifyAll();
            Mock.Get(_mockAuthenticationService).VerifyAll();
        }
Ejemplo n.º 12
0
        public static void HandleMessage(Byte[] msgData, GameSession session, GamePlayer client)
        {
            using(MemoryStream stream = new MemoryStream(msgData))
            {
                BaseMessage msg = Serializer.Deserialize<BaseMessage>(stream);

                switch((MessageType)msg.messageType)
                {
                    case MessageType.LoginRequest:
                        {
                            LoginRequest loginMsg = (LoginRequest) msg;

                            int status = LoginManager.GetInstance().ValidateCredentials(new User.GCUser.LoginInfo(loginMsg.username), loginMsg.password);

                            LoginResponse response = new LoginResponse() { success = (status == 0) };
                            client.DispatchMessage(response);
                            break;
                        }
                    case MessageType.ChatMessage:
                        {
                            session.SendToPlayers(msgData);
                            break;
                        }
                    case MessageType.CreateUserRequest:
                        {
                            CreateUserRequest createUserMessage = (CreateUserRequest)msg;

                            int status = (int)DBEnum.DBResponseCodes.SUCCESS;//LoginManager.GetInstance().CreateUser(new User.GCUser.LoginInfo(createUserMessage.mUsername), createUserMessage.mPassword);

                            CreateUserResponse response = new CreateUserResponse() { success = ((int)DBEnum.DBResponseCodes.SUCCESS == status) };
                            client.DispatchMessage(response);
                            break;
                        }
                    case MessageType.Heartbeat:
                    default:
                        {
                            break;
                        }
                }
            }
        }
        public LoginResponse Login(string email, string password)
        {
            var result = new LoginResponse();
            var request = Core.CoreRequest.Create(LoginServer, LoginServerPort, "login");

            request.Params.Add("e", email);
            request.Params.Add("p", password);
            request.Params.Add("protoversion", "8.2");
            request.Params.Add("client", ClientID);
            request.Params.Add("h", Host);
            request.Params.Add("build", Build);

            result.RequestTime = DateTime.Now;
            var response = request.GetResponse();
            result.ResponseTime = DateTime.Now;

            result.Parse(response);

            this.SessionID = result.Session;
            this.Server = result.RedirectIP;
            this.Port = result.RedirectPort;

            return result;
        }
Ejemplo n.º 14
0
 public void Login(OpenSubtitlesServiceParameters parameters)
 {
     LoginResponse = _proxy.LogIn(string.Empty, string.Empty, parameters.Language, parameters.UserAgent);
 }
Ejemplo n.º 15
0
 public void Login()
 {
     _response = DBConnection.instance.Login(new LoginMessage { userName = usernameInputField.text, password = passwordInputField.text });
     _isResponse = true;
 }
Ejemplo n.º 16
0
        //==============================================================================================================================================================================//

        // This is a test function. It is meant to connect to a PHP web service that remembers the username of the user who logs in (this is done via $_SESSION in the PHP file).
        // This function will perform four actions:
        // 1: it will attempt to login.
        // 2: it will attempt to get request data -- this should only succeed if the previous login attempt succeeded.
        // 3: it will attempt to logout.
        // 4: it will attempt to get request data again -- this should fail provided the previous logout was successful.
        public async void test_Login_GetRequestData_Logout_GetRequestData_WithSession()
        {
            Debug.WriteLine("********** RestService.test_Login_GetRequestData_Logout_GetRequestData_WithSession() START **********");

            // The user to login as.
            string email    = "*****@*****.**";
            string password = "******";

            // Get at most two rows from the database.
            int maxNumRowsToGet = 2;

            // Skip the first two rows.
            int startRowOffset = 2;

            //----------------------------------------------------------------------------------------------------------//
            // Attempt login.

            var uri = new Uri("http://75.108.69.184:1337/server_side_files/application_files/login.php");

            try
            {
                FormUrlEncodedContent formUrlEncodedContent = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair <string, string>("email", email),
                    new KeyValuePair <string, string>("password", password)
                });

                HttpResponseMessage response = await client.PostAsync(uri, formUrlEncodedContent);

                string responseContent = await response.Content.ReadAsStringAsync();

                Debug.WriteLine("RestService.test_Login_GetRequestData_Logout_GetRequestData_WithSession(): LOGIN: RESPONSE CONTENT AS FOLLOWS:");

                Debug.WriteLine(responseContent);

                Debug.WriteLine("-----------------------------------------------------------------------------------------");

                try
                {
                    LoginResponse loginResponse = JsonConvert.DeserializeObject <LoginResponse>(responseContent);

                    Debug.WriteLine(loginResponse.GetContents());
                }

                catch (Exception e)
                {
                    Debug.Fail("RestService.test_Login_GetRequestData_Logout_GetRequestData_WithSession(): LOGIN: something went wrong while deserializing \"responseContent\":");
                    Debug.WriteLine(e);
                }

                Debug.WriteLine("RestService.test_Login_GetRequestData_Logout_GetRequestData_WithSession(): LOGIN: RESPONSE CONTENT END");
            }

            catch (Exception e)
            {
                Debug.WriteLine(e);
                Debug.Fail("RestService.test_Login_GetRequestData_Logout_GetRequestData_WithSession(): LOGIN: something went wrong while logging in!");
            }

            //----------------------------------------------------------------------------------------------------------//
            // Attempt to get request data.

            uri = new Uri("http://75.108.69.184:1337/server_side_files/get_request_data.php");

            try
            {
                FormUrlEncodedContent formUrlEncodedContent = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair <string, string>("maxNumRowsToGet", maxNumRowsToGet.ToString()),
                    new KeyValuePair <string, string>("startRowOffset", startRowOffset.ToString())
                });

                HttpResponseMessage response = await client.PostAsync(uri, formUrlEncodedContent);

                string responseContent = await response.Content.ReadAsStringAsync();

                Debug.WriteLine("RestService.test_Login_GetRequestData_Logout_GetRequestData_WithSession(): GET REQUEST DATA: RESPONSE CONTENT AS FOLLOWS:");

                Debug.WriteLine(responseContent);

                Debug.WriteLine("-----------------------------------------------------------------------------------------");

                try
                {
                    List <RequestViewModel> rvmList = JsonConvert.DeserializeObject <List <RequestViewModel> >(responseContent);

                    foreach (RequestViewModel rvm in rvmList)
                    {
                        Debug.WriteLine(rvm.GetContents());
                    }
                }

                catch (Exception e)
                {
                    Debug.Fail("RestService.test_Login_GetRequestData_Logout_GetRequestData_WithSession(): GET REQUEST DATA: something went wrong while deserializing \"responseContent\":");
                    Debug.WriteLine(e);
                }

                Debug.WriteLine("RestService.test_Login_GetRequestData_Logout_GetRequestData_WithSession(): GET REQUEST DATA: RESPONSE CONTENT END");
            }

            catch (Exception e)
            {
                Debug.WriteLine(e);
                Debug.Fail("RestService.test_Login_GetRequestData_Logout_GetRequestData_WithSession(): GET REQUEST DATA: something went wrong while trying to get request data!");
            }

            //----------------------------------------------------------------------------------------------------------//
            // Attempt to logout.

            uri = new Uri("http://75.108.69.184:1337/server_side_files/application_files/logout.php");

            try
            {
                HttpResponseMessage response = await client.GetAsync(uri);

                string responseContent = await response.Content.ReadAsStringAsync();

                Debug.WriteLine("RestService.test_Login_GetRequestData_Logout_GetRequestData_WithSession(): LOGOUT: RESPONSE CONTENT AS FOLLOWS:");
                Debug.WriteLine(responseContent);
                Debug.WriteLine("RestService.test_Login_GetRequestData_Logout_GetRequestData_WithSession(): LOGOUT: RESPONSE CONTENT END");
            }

            catch (Exception e)
            {
                Debug.WriteLine(e);
                Debug.Fail("RestService.test_Login_GetRequestData_Logout_GetRequestData_WithSession(): LOGOUT: something went wrong while attempting to logout!");
            }

            //----------------------------------------------------------------------------------------------------------//
            // Attempt to get request data again. This should fail since we've already logged out.

            uri = new Uri("http://75.108.69.184:1337/server_side_files/application_files/get_request_data.php");

            try
            {
                FormUrlEncodedContent formUrlEncodedContent = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair <string, string>("maxNumRowsToGet", maxNumRowsToGet.ToString()),
                    new KeyValuePair <string, string>("startRowOffset", startRowOffset.ToString())
                });

                HttpResponseMessage response = await client.PostAsync(uri, formUrlEncodedContent);

                string responseContent = await response.Content.ReadAsStringAsync();

                Debug.WriteLine("RestService.test_Login_GetRequestData_Logout_GetRequestData_WithSession(): GET REQUEST DATA: RESPONSE CONTENT AS FOLLOWS:");

                Debug.WriteLine(responseContent);

                Debug.WriteLine("-----------------------------------------------------------------------------------------");

                try
                {
                    List <RequestViewModel> rvmList = JsonConvert.DeserializeObject <List <RequestViewModel> >(responseContent);

                    foreach (RequestViewModel rvm in rvmList)
                    {
                        Debug.WriteLine(rvm.GetContents());
                    }
                }

                catch (Exception e)
                {
                    Debug.Fail("RestService.test_Login_GetRequestData_Logout_GetRequestData_WithSession(): GET REQUEST DATA: something went wrong while deserializing \"responseContent\":");
                    Debug.WriteLine(e);
                }

                Debug.WriteLine("RestService.test_Login_GetRequestData_Logout_GetRequestData_WithSession(): GET REQUEST DATA: RESPONSE CONTENT END");
            }

            catch (Exception e)
            {
                Debug.WriteLine(e);
                Debug.Fail("RestService.test_Login_GetRequestData_Logout_GetRequestData_WithSession(): GET REQUEST DATA: something went wrong while trying to get request data!");
            }

            //----------------------------------------------------------------------------------------------------------//

            Debug.WriteLine("********** RestService.test_Login_GetRequestData_Logout_GetRequestData_WithSession() END **********");
        }
Ejemplo n.º 17
0
        public async Task <ServiceResponse <LoginResponse> > Login(string username, string password)
        {
            // throw new System.NotImplementedException();
            ServiceResponse <LoginResponse> response = new ServiceResponse <LoginResponse>();
            UserMaster user = new UserMaster();

            //           UserMaster user = await _context.UserMaster.FirstOrDefaultAsync
            //    (x => x.EmailId.ToLower().Equals
            //    (
            //       username.ToLower())
            //);
            if (username.IndexOf('@') > -1)
            {
                //Validate email format
                string emailRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                                    @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                                    @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
                Regex re = new Regex(emailRegex);
                if (!re.IsMatch(username))
                {
                    response.Success = false;
                    //response.Message = "Emailid not valid.";
                    response.Message = "Mobile No Or Email ID not valid.";
                    return(response);
                }
                else
                {
                    user = await _context.UserMaster.FirstOrDefaultAsync
                               (x => x.EmailId.ToLower().Equals
                               (
                                   username.ToLower())
                               );
                }
            }
            else
            {
                //validate Username format
                string mobileRegex = @"^[6-9]\d{9}$";
                Regex  re          = new Regex(mobileRegex);
                if (!re.IsMatch(username))

                {
                    response.Success = false;
                    //response.Message = "Mobile No  not valid.";
                    response.Message = "Mobile No Or Email ID not valid.";
                    return(response);
                }
                else
                {
                    user = await _context.UserMaster.FirstOrDefaultAsync
                               (x => x.MobileNo.Equals
                               (
                                   Convert.ToInt64(username))
                               );
                }
            }

            LoginResponse Login_Res = new LoginResponse();

            if (user == null)
            {
                response.Success = false;
                response.Message = "User not found.";
                return(response);
            }
            else if (!VerifyPasswordHash(password, user.PasswordHash, user.PasswordSalt))
            {
                response.Success = false;
                response.Message = "Wrong password";
                return(response);
            }
            else
            {
                Login_Res.UserId  = user.UserId;
                Login_Res.EmailId = user.EmailId;
                Login_Res.Status  = user.Status;
                TokenMaster tm = CreateToken(user);
                Login_Res.Token          = tm.Token;
                Login_Res.TokenExpiresIn = tm.tokenExpiresIn;// DateFormat.AddingTSeprator(tm.tokenExpiresIn);
                Login_Res.FirstName      = user.FirstName;
                Login_Res.LastName       = user.LastName;
                Login_Res.MobileNo       = user.MobileNo;
                Login_Res.UserTypeId     = user.UserTypeId;
                Login_Res.PlanId         = user.PlanId;
                Login_Res.AddedOn        = user.AddedOn;
                Login_Res.UpdatedOn      = user.UpdatedOn;
                //  response.Data = user.UserId.ToString();
                //return jwt token
                response.Data = Login_Res;
            }

            return(response);
        }
Ejemplo n.º 18
0
        public DriverHomePage()
        {
            BindingContext = this;
            geoCoder       = new Geocoder();
            InitializeComponent();
            var nextBtnClick = new TapGestureRecognizer();

            nextBtnClick.Tapped += NextBtnClick_Tapped;



            var carSelectionClicked = new TapGestureRecognizer();

            carSelectionClicked.Tapped += CarSelectionClicked_Tapped;

            var arrivedStartRideClick = new TapGestureRecognizer();

            arrivedStartRideClick.Tapped += btnstartRide_click;

            var finishRideClick = new TapGestureRecognizer();

            finishRideClick.Tapped += btnFinishRide_click;

            //var requestPayment = new TapGestureRecognizer();
            //requestPayment.Tapped += btnrequestPayment_click;
            //btnRequestPayment.GestureRecognizers.Add(requestPayment);

            var calltoRider = new TapGestureRecognizer();

            calltoRider.Tapped += btnCallToRider_click;

            btnCallToRider.GestureRecognizers.Add(calltoRider);

            btnStartRide.GestureRecognizers.Add(arrivedStartRideClick);
            btnFinishRide.GestureRecognizers.Add(finishRideClick);



            btnNext.GestureRecognizers.Add(nextBtnClick);
            btnSuv.GestureRecognizers.Add(carSelectionClicked);
            btnMini.GestureRecognizers.Add(carSelectionClicked);
            btnSedan.GestureRecognizers.Add(carSelectionClicked);
            txtLocation.Completed += TxtLocation_Completed;

            selectedCar   = "Mini";
            rbMini.Source = "radio_checked.png";
            Icon          = "hamburger.png";
            Title         = "Home";



            /*map = new Map
             * {
             *  IsShowingUser = true,
             *  HeightRequest = 100,
             *  WidthRequest = 960,
             *  VerticalOptions = LayoutOptions.FillAndExpand
             * };*/


            map = new Map(
                MapSpan.FromCenterAndRadius(
                    new Position(37, -122), Distance.FromMiles(0.3)))
            {
                IsShowingUser   = true,
                HeightRequest   = 100,
                WidthRequest    = 960,
                VerticalOptions = LayoutOptions.FillAndExpand
            };

            map.IsShowingUser = true;

            // var position = locator.GetPositionAsync();
            //Console.WriteLine("Position Status: {0}", position.Timestamp);
            //Console.WriteLine("Position Latitude: {0}", position.Latitude);
            //Console.WriteLine("Position Longitude: {0}", position.Longitude);


            /*map.MoveToRegion(MapSpan.FromCenterAndRadius(
             *  new Position(36.9628066, -122.0194722), Distance.FromMiles(3))); // Santa Cruz golf course*/

            /*var position = new Position(36.9628066, -122.0194722); // Latitude, Longitude
             * var pin = new Pin
             * {
             *  Type = PinType.Place,
             *  Position = position,
             *  Label = "Santa Cruz",
             *  Address = "custom detail info"
             * };
             * map.Pins.Add(pin);*/

            mapLayout.Children.Add(map);

            /*Content = new StackLayout
             * {
             *  Spacing = 0,
             *  Children = {
             *      map
             *  }
             * };*/


            // MoveToUserLocation();
            LoginResponse loginUser = Application.Current.Properties["userData"] as LoginResponse;

            if (loginUser.role_id == "3")
            {
                SlSearch.IsVisible       = false;
                SlLowaerButton.IsVisible = false;
                newRideRequesCall(loginUser.id);
                DriverMoveToUserLocation();
            }
            else
            {
                SlSearch.IsVisible       = true;
                SlLowaerButton.IsVisible = true;

                MoveToUserLocation();
            }
        }
        public NegotiatedContentResult <LoginResponse> PostLogin([FromBody] LoginRequest request)
        {
            LoginResponse resp = SuperUserServices.Login(request);

            return(Content(HttpStatusCode.OK, resp));
        }
Ejemplo n.º 20
0
        public static void Authenticate(string user_host_address, DB db, WebServiceLogin login, WebServiceResponse response, bool @readonly)
        {
            string      ip = user_host_address;
            int         person_id;
            DBLoginView view = null;

            Logger.Log(2, "WebService.Authenticate (Ip4: {0}, UserHostAddress: {1}, User: {2}, Cookie: {3}, Password: {4}", login == null ? null : login.Ip4, user_host_address, login == null ? null : login.User, login == null ? null : login.Cookie, login == null ? null : login.Password);

            // Check if credentials were passed in
            if (login == null || string.IsNullOrEmpty(login.User) || (string.IsNullOrEmpty(login.Password) && string.IsNullOrEmpty(login.Cookie)))
            {
                Logger.Log(2, "No credentials.");
                VerifyAnonymousAllowed();
                return;
            }

            if (!string.IsNullOrEmpty(login.Ip4))
            {
                ip = login.Ip4;
            }
            else
            {
                ip = user_host_address;
            }

            if (!string.IsNullOrEmpty(login.Password))
            {
                DBLogin result = DBLogin_Extensions.Login(db, login.User, login.Password, ip, @readonly);
                if (result != null)
                {
                    if (@readonly)
                    {
                        person_id = result.person_id;
                    }
                    else
                    {
                        view = DBLoginView_Extensions.VerifyLogin(db, login.User, result.cookie, ip);
                        if (view == null)
                        {
                            Logger.Log(2, "Invalid cookie");
                            VerifyAnonymousAllowed();
                            return;
                        }
                        person_id = view.person_id;
                    }
                }
                else
                {
                    Logger.Log(2, "Invalid user/password");
                    VerifyAnonymousAllowed();
                    return;
                }
            }
            else
            {
                view = DBLoginView_Extensions.VerifyLogin(db, login.User, login.Cookie, ip);
                if (view == null)
                {
                    Logger.Log(2, "Invalid cookie");
                    VerifyAnonymousAllowed();
                    return;
                }
                person_id = view.person_id;
                Logger.Log(2, "Verifying login, cookie: {0} user: {1} ip: {2}", login.Cookie, login.User, ip);
            }

            Logger.Log(2, "Valid credentials");

            if (response == null)
            {
                return;
            }

            DBPerson      person         = DBPerson_Extensions.Create(db, person_id);
            LoginResponse login_response = response as LoginResponse;

            if (login_response != null)
            {
                login_response.Cookie   = view != null ? view.cookie : null;
                login_response.FullName = person.fullname;
                login_response.ID       = person_id;
            }

            response.UserName  = person.login;
            response.UserRoles = person.Roles;
            Logger.Log(2, "Authenticate2 Roles are: {0}", response.UserRoles == null ? "null" : string.Join(";", response.UserRoles));
        }
 protected override bool UnRegister(LoginResponse member, string sPassword, int iPrivilege)
 {
     return(base.UnRegister(member, sPassword, iPrivilege));
 }
Ejemplo n.º 22
0
 /// <summary>
 /// On Connect
 /// </summary>
 /// <param name="loginResponse"></param>
 private void OnConnected(LoginResponse loginResponse)
 {
     Console.WriteLine("Connected");
 }
Ejemplo n.º 23
0
        /// <summary>
        /// 处理登录请求
        /// </summary>
        /// <param name="request"></param>
        public LoginResponse LoginRequest(LoginRequest request)
        {
            LoginResponse response = new LoginResponse();

            response.Uid          = request.Uid;
            response.ActivityType = request.ActivityType;

            //查询用户是否存在,若不存在 则自动创建用户和一系列训练课程、活动 byCQZ 2019.3.28
            MemberEntity memberEntity = memberDAO.GetMember(request.Uid);

            if (memberEntity == null)
            {
                //自动创建用户及计划 保证正常锻炼 接收数据
                memberService.AutoInsertUser(request.Uid);
                Console.WriteLine("收到的UID:{0}在数据库中不存在,自动创建用户及计划", request.Uid);
            }
            else
            {
                Console.WriteLine("用户存在");
            }

            var pSetting = personalSettingDAO.GetSettingByMemberId(request.Uid, request.DeviceType, request.ActivityType);

            if (pSetting != null)
            {//存在个人设置
                response.ExisitSetting = true;
            }
            else
            {
                return(response);
            }

            response.TrainMode = (TrainMode)Enum.Parse(typeof(TrainMode), pSetting.Training_mode);
            MemberEntity member = memberDAO.Load(pSetting.Fk_member_id);

            response.DefatModeEnable = member.Is_open_fat_reduction;
            response.SeatHeight      = pSetting.Seat_height == null ? 0 : (int)pSetting.Seat_height;
            response.BackDistance    = pSetting.Backrest_distance == null ? 0 : (int)pSetting.Backrest_distance;
            // 可动杠杆长度cm
            response.LeverLength  = pSetting.Lever_length == null ? 0 : (int)pSetting.Lever_length;
            response.ForwardLimit = pSetting.Front_limit == null ? 0 : (int)pSetting.Front_limit;
            response.BackLimit    = pSetting.Back_limit == null ? 0 : (int)pSetting.Back_limit;
            //杠杆角度
            response.LeverAngle   = pSetting.Lever_angle == null ? 0 : (double)pSetting.Lever_angle;
            response.ForwardForce = pSetting.Consequent_force == null ? 0 : (double)pSetting.Consequent_force;
            response.ReverseForce = pSetting.Reverse_force == null ? 0 : (double)pSetting.Reverse_force;
            response.Power        = pSetting.Power == null ? 0 : (double)pSetting.Power;
            //课程ID、训练活动ID、训练活动记录ID

            var setDto = personalSettingDAO.GetSettingCourseInfoByMemberId(request.Uid, request.ActivityType);

            response.CourseId   = setDto.Course_id;
            response.ActivityId = setDto.Activity_id;

            var recordEntity = trainingActivityRecordDAO.GetByActivityPrimaryKey(setDto.Activity_id, setDto.Current_course_count);

            if ((recordEntity == null) || (recordEntity != null && recordEntity.Is_complete == true))
            {//没有训练课程记录就插入一条新的
                recordEntity = new TrainingActivityRecordEntity
                {
                    Id                    = KeyGenerator.GetNextKeyValueLong("bdl_training_activity_record"),
                    Gmt_create            = DateTime.Now,
                    Fk_activity_id        = pSetting.Fk_training_activity_id,
                    Activity_type         = ((int)request.ActivityType).ToString(),
                    Is_complete           = false,
                    Fk_training_course_id = setDto.Course_id,
                    Course_count          = setDto.Current_course_count
                };
                trainingActivityRecordDAO.Insert(recordEntity);
                //插入至上传表
                UploadManagementDAO uploadManagementDao = new UploadManagementDAO();
                uploadManagementDao.Insert(new UploadManagement(recordEntity.Id, "bdl_training_activity_record", 0));
            }
            response.ActivityRecordId = recordEntity.Id;
            //踏板距离
            response.PedalDistance = pSetting.Footboard_distance == null ? 0 : (int)pSetting.Footboard_distance;
            //最大心率计算值
            response.HeartRateMax = member.Max_heart_rate == null ? 0 : (int)member.Max_heart_rate;
            //角色ID
            response.RoleId = member.Role_id == null ? 0 : (int)member.Role_id;
            response.Weight = member.Weight == null ? 0.0 : (double)member.Weight;
            response.Age    = member.Age == null ? 0 : (int)member.Age;
            //当前系统版本
            List <SystemSettingEntity> list = SystemSettingDAO.ListAll();

            if (list != null && list.Count > 0)
            {
                int ver = list[0].System_version == null?0: (int)list[0].System_version;
                response.SysVersion = ver;
            }
            else
            {
                response.SysVersion = 0;
            }

            // 待训练列表 修改传入的fk_activity_id和course_count参数为活动记录表主键activityRecordId  --ByCQZ 4.7
            List <DeviceType> todoDevices = GenToDoDevices(request.Uid, request.ActivityType, setDto.Is_open_fat_reduction, recordEntity.Id);

            response.DeviceTypeArr.AddRange(todoDevices);
            return(response);
        }
Ejemplo n.º 24
0
 internal async Task DisplayTextResult(LoginResponse response)
 {
     MessageDialog message = new MessageDialog(response.current_user.slug);
     await message.ShowAsync();
 }
Ejemplo n.º 25
0
        private void HandleLogin(HttpListenerContext context)
        {
            LoginRequest request;

            try
            {
                request = RestMethods.ReadBody <LoginRequest>(context.Request);
            }
            catch (ArgumentException e)
            {
                RestMethods.WriteError(context.Response, HttpStatusCode.BadRequest, e.Message);
                return;
            }

            if (_usernames.TryGetValue(request.Username, out int id))
            {
                if (_users[id].Online)
                {
                    context.Response.AppendHeader(HttpResponseHeader.WwwAuthenticate.ToString(), "Token realm = 'Username is already in use'");
                    RestMethods.WriteError(context.Response, HttpStatusCode.Unauthorized, "username is already in use");
                    return;
                }

                _users.TryRemove(id, out _);
                _usernames.TryRemove(request.Username, out id);
                _tokens.TryRemove(_tokens.First(tokenId => tokenId.Value == id).Key, out id);
            }

            lock (this)
            {
                id = ++_userId;
            }

            var token = Convert.ToBase64String(Guid.NewGuid().ToByteArray())
                        .TrimEnd(Padding)
                        .Replace('+', '-')
                        .Replace('/', '_');

            var loginResponse = new LoginResponse
            {
                Username = request.Username,
                Id       = id,
                Online   = true,
                Token    = token
            };

            var user = new User
            {
                Username = loginResponse.Username,
                Id       = id,
                Online   = true
            };

            lock (_usernames)
            {
                if (!_usernames.TryAdd(loginResponse.Username, id))
                {
                    context.Response.AppendHeader(HttpResponseHeader.WwwAuthenticate.ToString(), "Token realm = 'Username is already in use'");
                    RestMethods.WriteError(context.Response, HttpStatusCode.Unauthorized, "username is already in use");
                }
                _users.TryAdd(id, user);
                _tokens.TryAdd(token, id);
            }

            SendToAllSubscribers(WebSocketJsonType.User, user);

            RestMethods.WriteToResponse(context.Response, loginResponse);
        }
Ejemplo n.º 26
0
        public static void SignUpAndLogin(string userName, out IHttpContext context, out LoginResponse result)
        {
            UserManager userProxy;

            SignUpAndLogin(userName, out context, out result, out userProxy);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Prepare a login to the given region.  This involves both telling the region to expect a connection
        /// and appropriately customising the response to the user.
        /// </summary>
        /// <param name="regionInfo"></param>
        /// <param name="user"></param>
        /// <param name="response"></param>
        /// <returns>true if the region was successfully contacted, false otherwise</returns>
        private bool PrepareLoginToRegion(RegionProfileData regionInfo, UserProfileData user, LoginResponse response)
        {
            try
            {
                response.SimAddress = Util.GetHostFromURL(regionInfo.serverURI).ToString();
                response.SimPort    = uint.Parse(regionInfo.serverURI.Split(new char[] { '/', ':' })[4]);
                response.RegionX    = regionInfo.regionLocX;
                response.RegionY    = regionInfo.regionLocY;

                string capsPath = CapsUtil.GetRandomCapsObjectPath();

                // Take off trailing / so that the caps path isn't //CAPS/someUUID
                if (regionInfo.httpServerURI.EndsWith("/"))
                {
                    regionInfo.httpServerURI = regionInfo.httpServerURI.Substring(0, regionInfo.httpServerURI.Length - 1);
                }
                response.SeedCapability = regionInfo.httpServerURI + CapsUtil.GetCapsSeedPath(capsPath);

                // Notify the target of an incoming user
                m_log.InfoFormat(
                    "[LOGIN]: Telling {0} @ {1},{2} ({3}) to prepare for client connection",
                    regionInfo.regionName, response.RegionX, response.RegionY, regionInfo.httpServerURI);

                // Update agent with target sim
                user.CurrentAgent.Region = regionInfo.UUID;
                user.CurrentAgent.Handle = regionInfo.regionHandle;

                // Prepare notification
                Hashtable loginParams = new Hashtable();
                loginParams["session_id"]        = user.CurrentAgent.SessionID.ToString();
                loginParams["secure_session_id"] = user.CurrentAgent.SecureSessionID.ToString();
                loginParams["firstname"]         = user.FirstName;
                loginParams["lastname"]          = user.SurName;
                loginParams["agent_id"]          = user.ID.ToString();
                loginParams["circuit_code"]      = (Int32)Convert.ToUInt32(response.CircuitCode);
                loginParams["startpos_x"]        = user.CurrentAgent.Position.X.ToString();
                loginParams["startpos_y"]        = user.CurrentAgent.Position.Y.ToString();
                loginParams["startpos_z"]        = user.CurrentAgent.Position.Z.ToString();
                loginParams["regionhandle"]      = user.CurrentAgent.Handle.ToString();
                loginParams["caps_path"]         = capsPath;

                // Get appearance
                AvatarAppearance appearance = m_userManager.GetUserAppearance(user.ID);
                if (appearance != null)
                {
                    loginParams["appearance"] = appearance.ToHashTable();
                    m_log.DebugFormat("[LOGIN]: Found appearance for {0} {1}", user.FirstName, user.SurName);
                }
                else
                {
                    m_log.DebugFormat("[LOGIN]: Appearance not for {0} {1}. Creating default.", user.FirstName, user.SurName);
                    appearance = new AvatarAppearance(user.ID);
                }

                ArrayList SendParams = new ArrayList();
                SendParams.Add(loginParams);

                // Send
                XmlRpcRequest  GridReq  = new XmlRpcRequest("expect_user", SendParams);
                XmlRpcResponse GridResp = GridReq.Send(regionInfo.httpServerURI, 6000);

                if (!GridResp.IsFault)
                {
                    bool responseSuccess = true;

                    if (GridResp.Value != null)
                    {
                        Hashtable resp = (Hashtable)GridResp.Value;
                        if (resp.ContainsKey("success"))
                        {
                            if ((string)resp["success"] == "FALSE")
                            {
                                responseSuccess = false;
                            }
                        }
                    }

                    if (responseSuccess)
                    {
                        handlerUserLoggedInAtLocation = OnUserLoggedInAtLocation;
                        if (handlerUserLoggedInAtLocation != null)
                        {
                            handlerUserLoggedInAtLocation(user.ID, user.CurrentAgent.SessionID,
                                                          user.CurrentAgent.Region,
                                                          user.CurrentAgent.Handle,
                                                          user.CurrentAgent.Position.X,
                                                          user.CurrentAgent.Position.Y,
                                                          user.CurrentAgent.Position.Z,
                                                          user.FirstName, user.SurName);
                        }
                    }
                    else
                    {
                        m_log.ErrorFormat("[LOGIN]: Region responded that it is not available to receive clients");
                        return(false);
                    }
                }
                else
                {
                    m_log.ErrorFormat("[LOGIN]: XmlRpc request to region failed with message {0}, code {1} ", GridResp.FaultString, GridResp.FaultCode);
                    return(false);
                }
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[LOGIN]: Region not available for login, {0}", e);
                return(false);
            }

            return(true);
        }
Ejemplo n.º 28
0
        private IPrincipal GetPrincipal(LoginResponse user)
        {
            var identity = new CustomIdentity(_UserName, _AuthType, user.PersonID, user.RoleID, _Token);

            return(new CustomPrincipal(identity));
        }
Ejemplo n.º 29
0
        public LoginResponse LoginStudent(string login, string haslo)
        {
            ICryptoService cryptoService = new PBKDF2();

            var st   = new Student();
            var resp = new LoginResponse();

            using (SqlConnection con = new SqlConnection(ConString))
                using (SqlCommand com = new SqlCommand())
                {
                    com.Connection  = con;
                    com.CommandText = "select IndexNumber,Password,salt from Student WHERE IndexNumber=@Index";
                    com.Parameters.AddWithValue("Index", login);

                    con.Open();
                    SqlDataReader sqlRead = com.ExecuteReader();
                    if (sqlRead.Read())
                    {
                        st.IndexNumber = sqlRead["IndexNumber"].ToString();
                        string BaseSalt        = sqlRead["salt"].ToString();
                        string password        = sqlRead["Password"].ToString();
                        string hasloLocal      = cryptoService.Compute(haslo, BaseSalt);
                        bool   isPasswordValid = cryptoService.Compare(password, hasloLocal);
                        if (!isPasswordValid)
                        {
                            return(null);
                        }
                    }
                    else
                    {
                        return(null);
                    }
                    con.Close();

                    var claims = new[]
                    {
                        new Claim(ClaimTypes.NameIdentifier, "1"),
                        new Claim(ClaimTypes.Name, st.IndexNumber),
                        new Claim(ClaimTypes.Role, "student")
                    };

                    var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["SecretKey"]));
                    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                    var token = new JwtSecurityToken
                                (
                        issuer: "Gakko",
                        audience: "Students",
                        claims: claims,
                        expires: DateTime.Now.AddMinutes(10),
                        signingCredentials: creds
                                );

                    resp.accessToken  = new JwtSecurityTokenHandler().WriteToken(token);
                    resp.refreshToken = Guid.NewGuid();

                    con.Open();
                    com.CommandText = "UPDATE Student SET refreshToken=@Refresh WHERE IndexNumber=@Index";
                    com.Parameters.AddWithValue("Refresh", resp.refreshToken);

                    com.ExecuteNonQuery();
                    con.Close();
                }

            return(resp);
        }
Ejemplo n.º 30
0
 protected abstract bool UnRegister(LoginResponse member, string sPassword, int iPrivilege);
Ejemplo n.º 31
0
        public void HandleMessage(string incommingMessage, TalkBackDBContext dbContext)
        {
            MappedType t           = MappedType.UNDEFINED;
            XDocument  serialized  = XDocument.Parse(incommingMessage);
            XElement   typeElement = serialized.Root.Element("Type");

            if (typeElement == null)
            {
                // ignore
                return;
            }
            string type = typeElement.Value;

            if (ModelXmlMapper.map.TryGetValue(type, out t))
            {
                switch (t)
                {
                case MappedType.MESSAGE:
                    MessageModel msg = new MessageModel();
                    if (msg.FromXml(serialized.Root))
                    {
                        HandleChatMessageMsg(msg, dbContext);
                    }
                    break;

                case MappedType.USER:
                    UserModel user = new UserModel();
                    user.FromXml(serialized.Root);
                    break;

                case MappedType.CONTACT:
                    Contact contact = new Contact();
                    contact.FromXml(serialized.Root);
                    break;

                case MappedType.CHAT_REQUEST:
                    ChatRequest req = new ChatRequest();
                    if (req.FromXml(serialized.Root))
                    {
                        HandleChatRequestMsg(req, dbContext);
                    }
                    break;

                case MappedType.CHAT_REQUEST_RESPONSE:
                    ChatRequestResponse resp = new ChatRequestResponse();
                    if (resp.FromXml(serialized.Root))
                    {
                        HandleChatResponseMsg(resp, dbContext);
                    }
                    break;

                case MappedType.LOGIN:
                    Login login = new Login();
                    if (login.FromXml(serialized.Root))
                    {
                        HandleLoginMsg(login, dbContext);
                    }
                    break;

                case MappedType.LOGIN_RESPONSE:
                    LoginResponse loginResp = new LoginResponse();
                    loginResp.FromXml(serialized.Root);
                    break;

                case MappedType.UNDEFINED:
                    throw new Exception("Don't know how to parse this type");
                }
            }
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Customises the login response and fills in missing values.  This method also tells the login region to
        /// expect a client connection.
        /// </summary>
        /// <param name="response">The existing response</param>
        /// <param name="theUser">The user profile</param>
        /// <param name="startLocationRequest">The requested start location</param>
        /// <returns>true on success, false if the region was not successfully told to expect a user connection</returns>
        public bool CustomiseResponse(LoginResponse response, UserProfileData theUser, string startLocationRequest, IPEndPoint client)
        {
            // add active gestures to login-response
            AddActiveGestures(response, theUser);

            // HomeLocation
            RegionInfo homeInfo = null;

            // use the homeRegionID if it is stored already. If not, use the regionHandle as before
            UUID homeRegionId = theUser.HomeRegionID;
            ulong homeRegionHandle = theUser.HomeRegion;
            if (homeRegionId != UUID.Zero)
            {
                homeInfo = GetRegionInfo(homeRegionId);
            }
            else
            {
                homeInfo = GetRegionInfo(homeRegionHandle);
            }

            if (homeInfo != null)
            {
                response.Home =
                    string.Format(
                        "{{'region_handle':[r{0},r{1}], 'position':[r{2},r{3},r{4}], 'look_at':[r{5},r{6},r{7}]}}",
                        (homeInfo.RegionLocX * Constants.RegionSize),
                        (homeInfo.RegionLocY * Constants.RegionSize),
                        theUser.HomeLocation.X, theUser.HomeLocation.Y, theUser.HomeLocation.Z,
                        theUser.HomeLookAt.X, theUser.HomeLookAt.Y, theUser.HomeLookAt.Z);
            }
            else
            {
                m_log.InfoFormat("not found the region at {0} {1}", theUser.HomeRegionX, theUser.HomeRegionY);
                // Emergency mode: Home-region isn't available, so we can't request the region info.
                // Use the stored home regionHandle instead.
                // NOTE: If the home-region moves, this will be wrong until the users update their user-profile again
                ulong regionX = homeRegionHandle >> 32;
                ulong regionY = homeRegionHandle & 0xffffffff;
                response.Home =
                    string.Format(
                        "{{'region_handle':[r{0},r{1}], 'position':[r{2},r{3},r{4}], 'look_at':[r{5},r{6},r{7}]}}",
                        regionX, regionY,
                        theUser.HomeLocation.X, theUser.HomeLocation.Y, theUser.HomeLocation.Z,
                        theUser.HomeLookAt.X, theUser.HomeLookAt.Y, theUser.HomeLookAt.Z);

                m_log.InfoFormat("[LOGIN] Home region of user {0} {1} is not available; using computed region position {2} {3}",
                                 theUser.FirstName, theUser.SurName,
                                 regionX, regionY);
            }

            // StartLocation
            RegionInfo regionInfo = null;
            if (startLocationRequest == "home")
            {
                regionInfo = homeInfo;
                theUser.CurrentAgent.Position = theUser.HomeLocation;
                response.LookAt = String.Format("[r{0},r{1},r{2}]", theUser.HomeLookAt.X.ToString(), 
                                                theUser.HomeLookAt.Y.ToString(), theUser.HomeLookAt.Z.ToString());
            }
            else if (startLocationRequest == "last")
            {
                UUID lastRegion = theUser.CurrentAgent.Region;
                regionInfo = GetRegionInfo(lastRegion);
                response.LookAt = String.Format("[r{0},r{1},r{2}]", theUser.CurrentAgent.LookAt.X.ToString(),
                                                theUser.CurrentAgent.LookAt.Y.ToString(), theUser.CurrentAgent.LookAt.Z.ToString());
            }
            else
            {
                Regex reURI = new Regex(@"^uri:(?<region>[^&]+)&(?<x>\d+)&(?<y>\d+)&(?<z>\d+)$");
                Match uriMatch = reURI.Match(startLocationRequest);
                if (uriMatch == null)
                {
                    m_log.InfoFormat("[LOGIN]: Got Custom Login URL {0}, but can't process it", startLocationRequest);
                }
                else
                {
                    string region = uriMatch.Groups["region"].ToString();
                    regionInfo = RequestClosestRegion(region);
                    if (regionInfo == null)
                    {
                        m_log.InfoFormat("[LOGIN]: Got Custom Login URL {0}, can't locate region {1}", startLocationRequest, region);
                    }
                    else
                    {
                        theUser.CurrentAgent.Position = new Vector3(float.Parse(uriMatch.Groups["x"].Value),
                                                                    float.Parse(uriMatch.Groups["y"].Value), float.Parse(uriMatch.Groups["z"].Value));
                    }
                }
                response.LookAt = "[r0,r1,r0]";
                // can be: last, home, safe, url
                response.StartLocation = "url";
            }

            if ((regionInfo != null) && (PrepareLoginToRegion(regionInfo, theUser, response, client)))
            {
                return true;
            }

            // Get the default region handle
            ulong defaultHandle = Utils.UIntsToLong(m_defaultHomeX * Constants.RegionSize, m_defaultHomeY * Constants.RegionSize);

            // If we haven't already tried the default region, reset regionInfo
            if (regionInfo != null && defaultHandle != regionInfo.RegionHandle)
                regionInfo = null;

            if (regionInfo == null)
            {
                m_log.Error("[LOGIN]: Sending user to default region " + defaultHandle + " instead");
                regionInfo = GetRegionInfo(defaultHandle);
            }

            if (regionInfo == null)
            {
                m_log.ErrorFormat("[LOGIN]: Sending user to any region");
                regionInfo = RequestClosestRegion(String.Empty);
            }

            theUser.CurrentAgent.Position = new Vector3(128f, 128f, 0f);
            response.StartLocation = "safe";

            return PrepareLoginToRegion(regionInfo, theUser, response, client);
        }
Ejemplo n.º 33
0
        /// <summary>
        ///     Handles incoming messages.
        /// </summary>
        /// <param name="sender">The <see cref="IMessageConnection"/> instance from which the message originated.</param>
        /// <param name="message">The message.</param>
        public async void HandleMessage(object sender, byte[] message)
        {
            var code = new MessageReader <MessageCode.Server>(message).ReadCode();

            Diagnostic.Debug($"Server message received: {code}");

            try
            {
                switch (code)
                {
                case MessageCode.Server.ParentMinSpeed:
                case MessageCode.Server.ParentSpeedRatio:
                case MessageCode.Server.WishlistInterval:
                    SoulseekClient.Waiter.Complete(new WaitKey(code), IntegerResponse.FromByteArray <MessageCode.Server>(message));
                    break;

                case MessageCode.Server.Login:
                    SoulseekClient.Waiter.Complete(new WaitKey(code), LoginResponse.FromByteArray(message));
                    break;

                case MessageCode.Server.RoomList:
                    SoulseekClient.Waiter.Complete(new WaitKey(code), RoomList.FromByteArray(message));
                    break;

                case MessageCode.Server.PrivilegedUsers:
                    SoulseekClient.Waiter.Complete(new WaitKey(code), PrivilegedUserList.FromByteArray(message));
                    break;

                case MessageCode.Server.NetInfo:
                    var netInfo = NetInfo.FromByteArray(message);

                    try
                    {
                        await SoulseekClient.DistributedConnectionManager.AddParentConnectionAsync(netInfo.Parents).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        Diagnostic.Debug($"Error handling NetInfo message: {ex.Message}");
                    }

                    break;

                case MessageCode.Server.ConnectToPeer:
                    ConnectToPeerResponse connectToPeerResponse = default;

                    try
                    {
                        connectToPeerResponse = ConnectToPeerResponse.FromByteArray(message);

                        if (connectToPeerResponse.Type == Constants.ConnectionType.Transfer)
                        {
                            // ensure that we are expecting at least one file from this user before we connect. the response
                            // doesn't contain any other identifying information about the file.
                            if (!SoulseekClient.Downloads.IsEmpty && SoulseekClient.Downloads.Values.Any(d => d.Username == connectToPeerResponse.Username))
                            {
                                var(connection, remoteToken) = await SoulseekClient.PeerConnectionManager.GetTransferConnectionAsync(connectToPeerResponse).ConfigureAwait(false);

                                var download = SoulseekClient.Downloads.Values.FirstOrDefault(v => v.RemoteToken == remoteToken && v.Username == connectToPeerResponse.Username);

                                if (download != default(Transfer))
                                {
                                    SoulseekClient.Waiter.Complete(new WaitKey(Constants.WaitKey.IndirectTransfer, download.Username, download.Filename, download.RemoteToken), connection);
                                }
                            }
                            else
                            {
                                throw new SoulseekClientException($"Unexpected transfer request from {connectToPeerResponse.Username} ({connectToPeerResponse.IPAddress}:{connectToPeerResponse.Port}); Ignored");
                            }
                        }
                        else if (connectToPeerResponse.Type == Constants.ConnectionType.Peer)
                        {
                            await SoulseekClient.PeerConnectionManager.GetOrAddMessageConnectionAsync(connectToPeerResponse).ConfigureAwait(false);
                        }
                        else if (connectToPeerResponse.Type == Constants.ConnectionType.Distributed)
                        {
                            await SoulseekClient.DistributedConnectionManager.AddChildConnectionAsync(connectToPeerResponse).ConfigureAwait(false);
                        }
                        else
                        {
                            throw new MessageException($"Unknown Connect To Peer connection type '{connectToPeerResponse.Type}'");
                        }
                    }
                    catch (Exception ex)
                    {
                        Diagnostic.Debug($"Error handling ConnectToPeer response from {connectToPeerResponse?.Username} ({connectToPeerResponse?.IPAddress}:{connectToPeerResponse.Port}): {ex.Message}");
                    }

                    break;

                case MessageCode.Server.AddUser:
                    var addUserResponse = AddUserResponse.FromByteArray(message);
                    SoulseekClient.Waiter.Complete(new WaitKey(code, addUserResponse.Username), addUserResponse);
                    break;

                case MessageCode.Server.GetStatus:
                    var statsResponse = UserStatusResponse.FromByteArray(message);
                    SoulseekClient.Waiter.Complete(new WaitKey(code, statsResponse.Username), statsResponse);
                    UserStatusChanged?.Invoke(this, new UserStatusChangedEventArgs(statsResponse));
                    break;

                case MessageCode.Server.PrivateMessage:
                    var pm = PrivateMessage.FromByteArray(message);
                    PrivateMessageReceived?.Invoke(this, pm);

                    if (SoulseekClient.Options.AutoAcknowledgePrivateMessages)
                    {
                        await SoulseekClient.AcknowledgePrivateMessageAsync(pm.Id, CancellationToken.None).ConfigureAwait(false);
                    }

                    break;

                case MessageCode.Server.GetPeerAddress:
                    var peerAddressResponse = UserAddressResponse.FromByteArray(message);
                    SoulseekClient.Waiter.Complete(new WaitKey(code, peerAddressResponse.Username), peerAddressResponse);
                    break;

                default:
                    Diagnostic.Debug($"Unhandled server message: {code}; {message.Length} bytes");
                    break;
                }
            }
            catch (Exception ex)
            {
                Diagnostic.Warning($"Error handling server message: {code}; {ex.Message}", ex);
            }
        }
Ejemplo n.º 34
0
	public static void SetCookies (HttpResponse Response, LoginResponse response)
	{
		Logger.Log ("Login succeeded, cookie: {0}", response.Cookie);
		Response.Cookies.Add (new HttpCookie ("cookie", response.Cookie));
		Response.Cookies ["cookie"].Expires = DateTime.Now.AddDays (10);
		Response.Cookies.Add (new HttpCookie ("user", response.User));
		/* Note that the 'roles' cookie is only used to determine the web ui to show, it's not used to authorize anything */
		Response.Cookies.Add (new HttpCookie ("roles", response.UserRoles == null ? string.Empty : string.Join (", ", response.UserRoles)));
	}
Ejemplo n.º 35
0
 public void Store(LoginResponse response)
 {
     resourceHandler.Write(response);
 }
Ejemplo n.º 36
0
        public async void LoginAttempt()
        {
            // Attempt to get the debug urls from a config file
            InitResponse initResponse = await ServiceAccessor.Init();

            if (initResponse.status == SERVICE_RESPONSE.SUCCESS)
            {
                if (Password == null || Password == "")
                {
                    Password = initResponse.Password;
                }
                if (UserName == null || UserName == "")
                {
                    UserName = initResponse.Username;
                }
            }

            // Get the username and password from the view
            string loginArgs = JsonConvert.SerializeObject(new LoginSender {
                Username = UserName, Password = Password
            });

            // Show the user a call is being made in the background
            ButtonText             = "loading";
            FormVisibility         = "Collapsed";
            ProgressRingVisibility = "Visible";

            LoginResponse response = await ServiceAccessor.Login(loginArgs);

            if (response.status == SERVICE_RESPONSE.SUCCESS)
            {
                if (AppDataAccessor.GetUsername() != userName)
                {
                    AppDataAccessor.SetUsername(UserName);
                }
                if (RememberMe)
                {
                    AppDataAccessor.SetPassword(Password);
                    AppDataAccessor.SetLoginDate(DateTime.Now.ToString());
                }
                navigationService.NavigateToViewModel <HubViewModel>();
            }
            else if (response.status == SERVICE_RESPONSE.NULL_RESPONSE)
            {
                LoginFeedback = "Connection with server failed, please try again";
            }
            else if (response.status == SERVICE_RESPONSE.CREDENTIALS)
            {
                LoginFeedback = "Invalid Username or Password";
            }
            else if (response.status == SERVICE_RESPONSE.NO_CONNECTION)
            {
                DateTime LastLogin = new DateTime();
                string   loginDate = AppDataAccessor.GetLoginDate();
                if (loginDate != null)
                {
                    await Task.Run(() => LastLogin = DateTime.Parse(AppDataAccessor.GetLoginDate()));//need an async task in order to the page to navigate

                    TimeSpan ts = DateTime.Now - LastLogin;
                    if (ts.Days <= 14)
                    {
                        navigationService.NavigateToViewModel <HubViewModel>();
                    }
                    else
                    {
                        APIExceptionDialog.ShowNoInternetConnectionLoginDialog(null, null);
                    }
                }
                else
                {
                    APIExceptionDialog.ShowNoInternetConnectionLoginDialog(null, null);
                }
            }

            // Dismiss the loading indicator
            ButtonText             = "Login";
            FormVisibility         = "Visible";
            ProgressRingVisibility = "Collapsed";
        }
Ejemplo n.º 37
0
        public LoginResponse Login(string login, string haslo)
        {
            LoginResponse response = new LoginResponse();
            Student       student  = new Student();

            ICryptoService crypto = new PBKDF2();

            using (SqlConnection con = new SqlConnection(ConString))
                using (SqlCommand com = new SqlCommand())
                {
                    com.Connection = con;

                    com.CommandText = "SELECT IndexNumber, Passwd, Salt FROM STUDENT WHERE IndexNumber=@index";
                    com.Parameters.AddWithValue("index", login);

                    string passwd, dbPasswd, dbSalt;

                    con.Open();
                    SqlDataReader loginRead = com.ExecuteReader();
                    if (loginRead.Read())
                    {
                        student.IndexNumber = loginRead["IndexNumber"].ToString();
                        passwd   = loginRead["Passwd"].ToString();
                        dbSalt   = loginRead["Salt"].ToString();
                        dbPasswd = crypto.Compute(haslo, dbSalt);
                        if (!crypto.Compare(passwd, dbPasswd))
                        {
                            return(null);
                        }
                    }
                    else
                    {
                        return(null);
                    }

                    con.Close();

                    var claims = new[] {
                        new Claim(ClaimTypes.NameIdentifier, "1"),
                        new Claim(ClaimTypes.Name, student.IndexNumber),
                        new Claim(ClaimTypes.Role, "student"),
                    };

                    var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["SecretKey"]));
                    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                    var token = new JwtSecurityToken
                                (
                        issuer: "Gakko",
                        audience: "Students",
                        claims: claims,
                        expires: DateTime.Now.AddMinutes(10),
                        signingCredentials: creds
                                );

                    response.accessToken  = new JwtSecurityTokenHandler().WriteToken(token);
                    response.refreshToken = Guid.NewGuid();

                    con.Open();

                    com.CommandText = "UPDATE Student SET refToken=@refToken WHERE IndexNumber=@login";
                    com.Parameters.AddWithValue("login", login);
                    com.Parameters.AddWithValue("refToken", response.refreshToken);
                    com.ExecuteNonQuery();

                    con.Close();
                }

            return(response);
        }
Ejemplo n.º 38
0
        public LoginResponse SignIn(int customerid)
        {
            var response = new LoginResponse();

            try
            {
                // Authenticate the customer
                var customerID = authProvider.AuthenticateCustomer(customerid);
                if (customerID == 0)
                {
                    response.Fail("Unable to authenticate");
                    return response;
                }

                // Get the customer
                var identity = GetIdentity(customerID);
                if (identity == null)
                {
                    response.Fail("Customer not found");
                    return response;
                }

                response.CustomerTypeID = identity.CustomerTypeID;

                // Get the redirect URL (for silent logins) or create the forms ticket
                response.RedirectUrl = GetSilentLoginRedirect(identity);
                if (response.RedirectUrl.IsEmpty()) CreateFormsAuthenticationTicket(customerID);

                // Mark the response as successful
                response.Success();
            }
            catch (Exception ex)
            {
                response.Fail(ex.Message);
            }

            return response;
        }
Ejemplo n.º 39
0
        /// <summary>
        /// Emulates credential authentication without requiring credentials.
        /// The Windows file system is consulted to see if a certain file was placed there
        /// during the stand-alone install process.
        /// </summary>
        /// <param name="login"></param>
        /// <returns></returns>
        public static LoginResponse AuthenticateStandalone(Login login)
        {
            int    userIdSO       = 100;
            string primaryEmailSO = "";

            // Read the file system for the LOCAL-INSTALLATION file put there at install time
            if (!IsLocalInstallation(login.Scope))
            {
                return(null);
            }


            String name = WindowsIdentity.GetCurrent().Name;

            name           = string.IsNullOrWhiteSpace(name) ? "Local" : name;
            primaryEmailSO = name + "@myorg.org";
            using (var db = new CSET_Context())
            {
                var user = db.USERS.Where(x => x.PrimaryEmail == primaryEmailSO).FirstOrDefault();
                if (user == null)
                {
                    UserManager um = new UserManager();
                    UserDetail  ud = new UserDetail()
                    {
                        Email     = primaryEmailSO,
                        FirstName = name,
                        LastName  = ""
                    };
                    UserCreateResponse userCreateResponse = um.CreateUser(ud);

                    db.SaveChanges();
                    //update the userid 1 to the new user
                    var tempu = db.USERS.Where(x => x.PrimaryEmail == primaryEmailSO).FirstOrDefault();
                    if (tempu != null)
                    {
                        userIdSO = tempu.UserId;
                    }
                    determineIfUpgradedNeededAndDoSo(userIdSO);
                }
                else
                {
                    userIdSO = user.UserId;
                }
            }

            if (string.IsNullOrEmpty(primaryEmailSO))
            {
                return(null);
            }


            // Generate a token for this user
            string token = TransactionSecurity.GenerateToken(userIdSO, login.TzOffset, -1, null, null, login.Scope);

            // Build response object
            LoginResponse resp = new LoginResponse
            {
                Token           = token,
                Email           = primaryEmailSO,
                UserFirstName   = name,
                UserLastName    = "",
                IsSuperUser     = false,
                ResetRequired   = false,
                ExportExtension = IOHelper.GetFileExtension(login.Scope)
            };


            return(resp);
        }
Ejemplo n.º 40
0
 protected override bool PrepareLoginToRegion(RegionInfo regionInfo, UserProfileData user, LoginResponse response, IPEndPoint remoteClient)
 {
     return PrepareLoginToRegion(RegionProfileData.FromRegionInfo(regionInfo), user, response, remoteClient);
 }
        protected override bool PrepareLoginToRegion(
            RegionInfo regionInfo, UserProfileData user, LoginResponse response, IPEndPoint remoteClient)
        {
            IPEndPoint endPoint = regionInfo.ExternalEndPoint;
            response.SimAddress = endPoint.Address.ToString();
            response.SimPort = (uint)endPoint.Port;
            response.RegionX = regionInfo.RegionLocX;
            response.RegionY = regionInfo.RegionLocY;

            string capsPath = CapsUtil.GetRandomCapsObjectPath();
            string capsSeedPath = CapsUtil.GetCapsSeedPath(capsPath);

            // Don't use the following!  It Fails for logging into any region not on the same port as the http server!
            // Kept here so it doesn't happen again!
            // response.SeedCapability = regionInfo.ServerURI + capsSeedPath;

            string seedcap = "http://";

            if (m_serversInfo.HttpUsesSSL)
            {
                // For NAT
                string host = NetworkUtil.GetHostFor(remoteClient.Address, m_serversInfo.HttpSSLCN);

                seedcap = "https://" + host + ":" + m_serversInfo.httpSSLPort + capsSeedPath;
            }
            else
            {
                // For NAT
                string host = NetworkUtil.GetHostFor(remoteClient.Address, regionInfo.ExternalHostName);

                seedcap = "http://" + host + ":" + m_serversInfo.HttpListenerPort + capsSeedPath;
            }

            response.SeedCapability = seedcap;

            // Notify the target of an incoming user
            m_log.InfoFormat(
                "[LOGIN]: Telling {0} @ {1},{2} ({3}) to prepare for client connection",
                regionInfo.RegionName, response.RegionX, response.RegionY, regionInfo.ServerURI);

            // Update agent with target sim
            user.CurrentAgent.Region = regionInfo.RegionID;
            user.CurrentAgent.Handle = regionInfo.RegionHandle;

            AgentCircuitData agent = new AgentCircuitData();
            agent.AgentID = user.ID;
            agent.firstname = user.FirstName;
            agent.lastname = user.SurName;
            agent.SessionID = user.CurrentAgent.SessionID;
            agent.SecureSessionID = user.CurrentAgent.SecureSessionID;
            agent.circuitcode = Convert.ToUInt32(response.CircuitCode);
            agent.BaseFolder = UUID.Zero;
            agent.InventoryFolder = UUID.Zero;
            agent.startpos = user.CurrentAgent.Position;
            agent.CapsPath = capsPath;
            agent.Appearance = m_userManager.GetUserAppearance(user.ID);
            if (agent.Appearance == null)
            {
                m_log.WarnFormat(
                    "[INTER]: Appearance not found for {0} {1}. Creating default.", agent.firstname, agent.lastname);
                agent.Appearance = new AvatarAppearance(agent.AgentID);
            }

            if (m_regionsConnector.RegionLoginsEnabled)
            {
                string reason;
                bool success = m_regionsConnector.NewUserConnection(regionInfo.RegionHandle, agent, out reason);
                if (!success)
                {
                    response.ErrorReason = "key";
                    response.ErrorMessage = reason;
                }
                return success;
                // return m_regionsConnector.NewUserConnection(regionInfo.RegionHandle, agent, out reason);
            }

            return false;
        }
Ejemplo n.º 42
0
 public LoginResponse Login(LoginRequest request)
 {
     var response = new LoginResponse();
     response.@return = request.clientId + request.user + request.pwd;
     return response;
 }
Ejemplo n.º 43
0
        private void protocol(SslStream sslStream)
        {
            var username = "******";
            var password = "******";
            object recvObj = null;
            var request = new LoginRequest() { username = username};
            LoginChallenge challenge = null;
            LoginResponse response = null;
            LoginConfirmation confirmation = null;
            SecureCalendar sc = null;

            log(Util.XmlSerializeToString(request));
            Util.writeObject(sslStream, request);
            recvObj = Util.readObject(sslStream);
            if(recvObj is LoginChallenge)
            {
                challenge = (LoginChallenge)recvObj;
                log(Util.XmlSerializeToString(challenge));
            }
            else
            {
                log("Login failed: did not receive login challenge");
                return;
            }
            // PBKDF2
            string pwhash = "";
            // password hash
            using (var db = new Rfc2898DeriveBytes(password,
                Convert.FromBase64String(challenge.passwordSalt),
                ITERATIONS))
            {
                pwhash = Convert.ToBase64String(db.GetBytes(KEY_SIZE));
            }
            response = new LoginResponse() { passwordHash = pwhash };
            Util.writeObject(sslStream,response);
            log(Util.XmlSerializeToString(response));
            recvObj = Util.readObject(sslStream);

            if (recvObj is LoginConfirmation)
            {
                confirmation = (LoginConfirmation)recvObj;
                log(Util.XmlSerializeToString(confirmation));
            }
            else
            {
                log("Login failed: did not receive login confirmation");
                return;
            }
            log("Login succesfull");

            ReadCalendarRequest read = new ReadCalendarRequest() { calendarName = "Rui's calendar" };
            Util.writeObject(sslStream,read);
            recvObj = Util.readObject(sslStream);
            if(recvObj is SecureCalendar)
            {
                sc = (SecureCalendar)recvObj;
                logF(Util.XmlSerializeToString(recvObj));
            }
            else
            {
                log("Read failed");
                return;
            }
            EncryptedFileEncryptionKey eFEK = sc.keys.Find(x => x.username == username);
            if(eFEK == null)
            {
                log("Read failed, eFEK not found");
                return;
            }
            log("Found eFEK");
            string KEK = null;
            string privateKey;
            string FEK = null;
            byte[] FEKb;

            // produce KEK
            using (var db = new Rfc2898DeriveBytes(password,
                Convert.FromBase64String(confirmation.KEKSalt),
                ITERATIONS))
            {
                KEK = Convert.ToBase64String(db.GetBytes(KEY_SIZE));
            }
            // decrypt private key
            privateKey = Util.Decrypt(KEK, confirmation.privateIV, confirmation.encryptedPrivateKey);
            // decrypt eFEK
            RSACryptoServiceProvider rsaPrivate = new RSACryptoServiceProvider();
            rsaPrivate.FromXmlString(privateKey);
            FEKb = rsaPrivate.Decrypt(Convert.FromBase64String(eFEK.eFEK), false);
            FEK = Convert.ToBase64String(FEKb);
            string events = Util.Decrypt(FEK,sc.IV,sc.encryptedEvents);
            // decrypt calendar
            logF("Events:{0}", events);
            log("Read successfull");
        }
Ejemplo n.º 44
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            var t=Task.Factory.StartNew(() =>
            {
                manager = Manager.GetInstance(new SQLitePlatformAndroid(),
                new JsvServiceClient("http://prodactive.co/api"),
                System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal),
                    "prodactive.db"));
            });
            lr = JsonSerializer.DeserializeFromString<LoginResponse>(Intent.GetStringExtra("UserData"));

            var estatura = lr.Persona.Estatura*100;
            GetStepLength(lr, estatura);
            BodyWeight = lr.Persona.Peso;

            string s = "UserData";
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Reto);

            //// Get our button from the layout resource,
            //// and attach an event to it
            Button button = FindViewById<Button>(Resource.Id.btnIniciarReto);
            //Button Cerrar = FindViewById<Button>(Resource.Id.button1);
            tv            = FindViewById<TextView>(Resource.Id.txtPasos);
            tcalorias     = FindViewById<TextView>(Resource.Id.txtCalorias);

            //verificar si ya acepte el reto....
            button.Click += delegate
            {
                if (swButton)
                {
                    OnDestroy();
                    //button.Text = "Iniciar Reto";
                    swButton = false;
                }
                else
                {
                    if (lr.Reto.IsActivo)
                    {

                        StartStepService();
                        Toast.MakeText(this, "El reto ha comenzado. La aplicación iniciará el conteo de pasos", ToastLength.Long);
                        Reporte.Start();
                        //button.Enabled = false;
                        button.Text = "Cerrar App";
                        swButton = true;

                    }
                }

            };
            //Cerrar.Click += (sender, e) =>
            //{
            //    Finish();

            //};
            handler = new Handler();
            t.Wait();

            Reporte = new System.Timers.Timer(60000);
            Reporte.Elapsed += EnviarReportePasos;
        }
Ejemplo n.º 45
0
        public static void LoginOpenId(DB db, LoginResponse response, string email, string ip4)
        {
            Logger.Log(2, "DBLogin.LoginOpenId ({0}, {1})", email, ip4);

            if (string.IsNullOrEmpty(Configuration.OpenIdProvider))
            {
                throw new Exception("No OpenId provider available");
            }

            if (string.IsNullOrEmpty(Configuration.OpenIdRoles))
            {
                throw new Exception("No OpenId roles specified");
            }

            if (string.IsNullOrEmpty(email))
            {
                throw new Exception("OpenId authentication requires an email");
            }

            string [] specs = Configuration.OpenIdRoles.Split(';');
            foreach (var spec in specs)
            {
                // email:role1,role2
                string [] split = spec.Split(':');
                if (split.Length != 2)
                {
                    Logger.Log("AuthenticateOpenId: Invalid role spec: {0}", spec);
                    continue;
                }

                if (string.IsNullOrEmpty(split [1]))
                {
                    Logger.Log("AuthenticateOpenId: No roles specified for {0}", split [0]);
                    continue;
                }

                if (!Regex.IsMatch(email, split [0]))
                {
                    continue;
                }

                // We now create an account with an empty password and the specified roles.
                // Note that it is not possible to log into an account with an empty password
                // using the normal login procedure.

                DBPerson open_person = null;

                using (IDbCommand cmd = db.CreateCommand()) {
                    cmd.CommandText = @"SELECT * FROM Person WHERE login = @login;";
                    DB.CreateParameter(cmd, "login", email);
                    using (var reader = cmd.ExecuteReader()) {
                        if (reader.Read())
                        {
                            open_person = new DBPerson(reader);
                        }
                    }
                }

                if (open_person == null)
                {
                    open_person       = new DBPerson();
                    open_person.login = email;
                    open_person.roles = split [1];
                    open_person.Save(db);
                }
                else
                {
                    // only save if something has changed
                    if (open_person.roles != split [1])
                    {
                        open_person.roles = split [1];
                        open_person.Save(db);
                    }
                }

                var result = new DBLogin();
                result.person_id = open_person.id;
                result.ip4       = ip4;
                result.cookie    = CreateCookie();
                result.expires   = DateTime.Now.AddDays(1);
                result.Save(db);

                response.User      = email;
                response.UserName  = email;
                response.UserRoles = open_person.Roles;
                response.Cookie    = result.cookie;

                return;
            }

            throw new Exception("The provided email address is not allowed to log in");
        }
Ejemplo n.º 46
0
 protected override bool PrepareLoginToRegion(RegionInfo regionInfo, UserProfileData user, LoginResponse response)
 {
     return(PrepareLoginToRegion(RegionProfileData.FromRegionInfo(regionInfo), user, response));
 }
Ejemplo n.º 47
0
        // Customer Identities
        public LoginResponse SignIn(string loginname, string password, string overrideReturnUrl = "")
        {
            var response = new LoginResponse();

            try
            {
                // Authenticate the customer
                var customerID = Exigo.WebService().AuthenticateCustomer(new AuthenticateCustomerRequest { LoginName = loginname, Password = password }).CustomerID;
                if (customerID == 0)
                {
                    response.Fail("Unable to authenticate");
                    return response;
                }

                // Get the customer
                var identity = GetIdentity(customerID);
                if (identity == null)
                {
                    response.Fail("Customer not found");
                    return response;
                }

                response.Country = identity.Country;

                // Alan C - 1 April 2015 - Added below code block from Mike's update on my local machine at the office

                // If we are authenticating during the shopping process due to auto ship rules, we want to make sure we send the user back where they came from
                var redirectUrl = GetSilentLoginRedirect(identity);

                response.RedirectUrl = (redirectUrl.IsNullOrEmpty()) ? overrideReturnUrl : redirectUrl;

                if (redirectUrl.IsNullOrEmpty()) CreateFormsAuthenticationTicket(customerID);

                // Here we check to see if the customer is a smart shopper, if so we need to redirect to their site
                if (identity.CustomerTypeID == CustomerTypes.SmartShopper)
                {
                    response.RedirectUrl = GetSmartShopperRedirect(identity.CustomerID);
                }

                // Mark the response as successful
                response.Success();
            }
            catch (Exception ex)
            {
                response.Fail(ex.Message);
            }

            return response;
        }
Ejemplo n.º 48
0
        public async Task <LoginResponse> Login([FromBody] LoginRequest request)
        {
            LoginResponse response = _authService.LoginUser(request.Email, request.Password);

            return(response);
        }
Ejemplo n.º 49
0
        public LoginResponse SignIn(string silentLoginToken)
        {
            var response = new LoginResponse();

            try
            {
                // New Method - if it works

                //// Decrypt the token
                //var decryptedToken = Security.Decrypt(silentLoginToken);

                //// Split the value and get the values
                //var splitToken = decryptedToken.Split('|');
                //var customerID = Convert.ToInt32(decryptedToken.CustomerID);
                //var tokenExpirationDate = Convert.ToDateTime(decryptedToken.ExpirationDate);

                // Split the value and get the values
                //var splitToken = decryptedToken.Split('|');
                //var customerID = Convert.ToInt32(decryptedToken.CustomerID);
                //var tokenExpirationDate = Convert.ToDateTime(decryptedToken.ExpirationDate);

                // Old School if new way doesn't work

                // Decrypt the token
                var key = GlobalSettings.Encryptions.Key;
                var iv = GlobalSettings.Encryptions.IV;
                var decryptedToken = Security.AESDecrypt(silentLoginToken, key, iv);

                // Split the value and get the values
                var splitToken = decryptedToken.Split('|');
                var customerID = Convert.ToInt32(splitToken[0]);
                var tokenExpirationDate = Convert.ToDateTime(splitToken[2]).ToUniversalTime();

                // Return the expiration status of the token and the sign in response
                if (tokenExpirationDate < DateTime.Now)
                {
                    response.Fail("Token expired");
                    return response;
                }

                // Sign the customer in with their customer ID
                response = SignIn(customerID);

                // Mark the response as successful
                response.Success();

                response.Status = true;
            }
            catch (Exception ex)
            {
                response.Fail(ex.Message);
            }

            return response;
        }
Ejemplo n.º 50
0
        private async Task HandleLogin()
        {
            IsLogining = true;
            if (ApiHelper.userBasicDatas.ContainsKey(tbx_username.Text.Trim()))
            {
                MessageBox.Show("该账号已经添加!", "提示");
                return;
            }
            ld.phone     = tbx_username.Text.Trim();
            ld.pwd       = tbx_password.Password.Trim();
            tbx_tip.Text = "正在登陆...";
            HttpMessage resp = await ApiHelper.Login(
                ld.phone, ld.pwd, tbx_valicode.Text.Trim(), ld.account_type, ld.deviceid, ld.imeiid);

            switch (resp.statusCode)
            {
            case HttpStatusCode.OK:
                tbx_tip.Text  = "";
                loginResponse = resp.data as LoginResponse;
                if (loginResponse.iRet == 0)
                {
                    var devices = await GetDevices(ld.phone);

                    if (devices == null || devices.Count == 0)
                    {
                        MessageBox.Show("请先用app绑定玩客云设备", "错误");
                        LoginSuccess = false;
                        IsLogining   = false;
                        return;
                    }
                    LoginSuccess = true;
                    MessageBox.Show("登陆成功", "恭喜");
                    Debug.WriteLine(MainWindow.settings.loginDatas == null);
                    if (MainWindow.settings.loginDatas == null)
                    {
                        MainWindow.settings.loginDatas = new List <LoginData>();
                    }
                    MainWindow.settings.loginDatas.Add(ld);
                    SettingHelper.WriteSettings(MainWindow.settings, MainWindow.password);
                    //保存登陆信息
                    ApiHelper.userBasicDatas.Add(loginResponse.data.phone, loginResponse.data);
                    //载入登陆响应信息到主窗口
                    this.Close();
                }
                else if (loginResponse.iRet == -121)
                {
                    MessageBox.Show("验证码输入错误", "错误(-121)");
                    ShowVali(true);
                    RefreshVali();
                    Debug.WriteLine(this.url_login_vali);
                    IsLogining = false;
                }
                else if (loginResponse.iRet == -122)
                {
                    MessageBox.Show("请输入验证码", "提示(-122)");
                    ShowVali(true);
                    this.url_login_vali = loginResponse.sMsg.Replace(@"\/", @"/");
                    this.url_login_vali = loginResponse.sMsg.Replace(@"http://account.onethingpcs.com/", "");
                    RefreshVali();
                    Debug.WriteLine(this.url_login_vali);
                    IsLogining = false;
                }
                else
                {
                    LoginSuccess = true;
                    MessageBox.Show(loginResponse.sMsg, $"登陆失败({loginResponse.iRet})");
                    IsLogining = false;
                }
                break;

            default:
                tbx_tip.Text = "";
                MessageBox.Show(resp.data.ToString(), "网络异常错误!");
                IsLogining = false;
                break;
            }
        }
Ejemplo n.º 51
0
        /// <summary>
        /// Prepare a login to the given region.  This involves both telling the region to expect a connection
        /// and appropriately customising the response to the user.
        /// </summary>
        /// <param name="regionInfo"></param>
        /// <param name="user"></param>
        /// <param name="response"></param>
        /// <returns>true if the region was successfully contacted, false otherwise</returns>
        private bool PrepareLoginToRegion(RegionProfileData regionInfo, UserProfileData user, LoginResponse response, IPEndPoint remoteClient)
        {
            try
            {
                response.SimAddress = Util.GetHostFromURL(regionInfo.serverURI).ToString();
                response.SimPort = uint.Parse(regionInfo.serverURI.Split(new char[] { '/', ':' })[4]);
                response.RegionX = regionInfo.regionLocX;
                response.RegionY = regionInfo.regionLocY;

                string capsPath = CapsUtil.GetRandomCapsObjectPath();

                // Adam's working code commented for now -- Diva 5/25/2009
                //// For NAT
                ////string host = NetworkUtil.GetHostFor(remoteClient.Address, regionInfo.ServerIP);
                //string host = response.SimAddress;
                //// TODO: This doesnt support SSL. -Adam
                //string serverURI = "http://" + host + ":" + regionInfo.ServerPort;

                //response.SeedCapability = serverURI + CapsUtil.GetCapsSeedPath(capsPath);

                // Take off trailing / so that the caps path isn't //CAPS/someUUID
                string uri = regionInfo.httpServerURI.Trim(new char[] { '/' });
                response.SeedCapability = uri + CapsUtil.GetCapsSeedPath(capsPath);


                // Notify the target of an incoming user
                m_log.InfoFormat(
                    "[LOGIN]: Telling {0} @ {1},{2} ({3}) to prepare for client connection",
                    regionInfo.regionName, response.RegionX, response.RegionY, regionInfo.httpServerURI);

                // Update agent with target sim
                user.CurrentAgent.Region = regionInfo.UUID;
                user.CurrentAgent.Handle = regionInfo.regionHandle;

                // Prepare notification
                Hashtable loginParams = new Hashtable();
                loginParams["session_id"] = user.CurrentAgent.SessionID.ToString();
                loginParams["secure_session_id"] = user.CurrentAgent.SecureSessionID.ToString();
                loginParams["firstname"] = user.FirstName;
                loginParams["lastname"] = user.SurName;
                loginParams["agent_id"] = user.ID.ToString();
                loginParams["circuit_code"] = (Int32)Convert.ToUInt32(response.CircuitCode);
                loginParams["startpos_x"] = user.CurrentAgent.Position.X.ToString();
                loginParams["startpos_y"] = user.CurrentAgent.Position.Y.ToString();
                loginParams["startpos_z"] = user.CurrentAgent.Position.Z.ToString();
                loginParams["regionhandle"] = user.CurrentAgent.Handle.ToString();
                loginParams["caps_path"] = capsPath;

                // Get appearance
                AvatarAppearance appearance = m_userManager.GetUserAppearance(user.ID);
                if (appearance != null)
                {
                    loginParams["appearance"] = appearance.ToHashTable();
                    m_log.DebugFormat("[LOGIN]: Found appearance for {0} {1}", user.FirstName, user.SurName);
                }
                else
                {
                    m_log.DebugFormat("[LOGIN]: Appearance not for {0} {1}. Creating default.", user.FirstName, user.SurName);
                    appearance = new AvatarAppearance(user.ID);
                    loginParams["appearance"] = appearance.ToHashTable();
                }

                ArrayList SendParams = new ArrayList();
                SendParams.Add(loginParams);

                // Send
                XmlRpcRequest GridReq = new XmlRpcRequest("expect_user", SendParams);
                XmlRpcResponse GridResp = GridReq.Send(regionInfo.httpServerURI, 6000);

                if (!GridResp.IsFault)
                {
                    bool responseSuccess = true;

                    if (GridResp.Value != null)
                    {
                        Hashtable resp = (Hashtable)GridResp.Value;
                        if (resp.ContainsKey("success"))
                        {
                            if ((string)resp["success"] == "FALSE")
                            {
                                responseSuccess = false;
                            }
                        }
                    }
                    
                    if (responseSuccess)
                    {
                        handlerUserLoggedInAtLocation = OnUserLoggedInAtLocation;
                        if (handlerUserLoggedInAtLocation != null)
                        {
                            handlerUserLoggedInAtLocation(user.ID, user.CurrentAgent.SessionID,
                                                          user.CurrentAgent.Region,
                                                          user.CurrentAgent.Handle,
                                                          user.CurrentAgent.Position.X,
                                                          user.CurrentAgent.Position.Y,
                                                          user.CurrentAgent.Position.Z,
                                                          user.FirstName, user.SurName);
                        }
                    }
                    else
                    {
                        m_log.ErrorFormat("[LOGIN]: Region responded that it is not available to receive clients");
                        return false;
                    }
                }
                else
                {
                    m_log.ErrorFormat("[LOGIN]: XmlRpc request to region failed with message {0}, code {1} ", GridResp.FaultString, GridResp.FaultCode);
                    return false;
                }
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[LOGIN]: Region not available for login, {0}", e);
                return false;
            }

            return true;
        }
Ejemplo n.º 52
0
    public async Task Start(string uri, Credential credential, Slurl slurl = null, bool getInventoryLibrary = true, bool godMode = false)
    {
        List <Task> awaitables = new List <Task>();

        IsLoggedIn      = false;
        IsLogoutPending = false;

        #region Login
        Logger.LogDebug("LOGIN------------------------------");
        EventManager.Instance.RaiseOnProgressUpdate("Login", "Logging in...", 0.2f);

        Login         login         = new Login();
        LoginResponse loginResponse = await login.Connect(uri, credential, slurl, getInventoryLibrary, godMode);

        if (loginResponse.LoginSucceeded == false)
        {
            EventManager.Instance.RaiseOnProgressUpdate("Login", "Login failed.", 0.29f, true);

            switch (loginResponse.LoginFailReason)
            {
            case "key":
                break;

            case "update":
                break;

            case "tos":
                break;
            }
            Logger.LogWarning($"Login.Connect: {loginResponse.MessageId} {loginResponse.Message}");
            return;
        }

        SessionId = loginResponse.SessionId;
        #endregion Login

        #region WorldInit
        Logger.LogDebug("WORLD_INIT-------------------------");
        EventManager.Instance.RaiseOnProgressUpdate("Login", "Initializing world...", 0.3f);

        AgentId = loginResponse.AgentId;
        Agent agent = new Agent(loginResponse.AgentId)
        {
            DisplayName = loginResponse.DisplayName,
            FirstName   = loginResponse.FirstName,
            LastName    = loginResponse.LastName
        };
        Agent.SetCurrentPlayer(agent);
        EventManager.Instance.RaiseOnAgentDataChanged(agent);

        // Before we create the first region, we need to set the agent's OriginGlobal
        // This is necessary because creating objects before this is set will result in a
        // bad PositionAgent cache.
        agent.InitOriginGlobal(loginResponse.RegionHandle.ToVector3Double());

        FirstSimHost = new Host(loginResponse.SimIp, loginResponse.SimPort);
        Region region = World.Instance.AddRegion(loginResponse.RegionHandle, FirstSimHost);

        Logger.LogInfo("Requesting capability grants...");
        EventManager.Instance.RaiseOnProgressUpdate("Login", "Requesting capability grants...", 0.32f);

        Task seedCapabilitiesTask = region.SetSeedCapability(loginResponse.SeedCapability);

        agent.Region = region;
        #endregion WorldInit

        #region MultimediaInit
        Logger.LogDebug("MULTIMEDIA_INIT--------------------");
        EventManager.Instance.RaiseOnProgressUpdate("Login", "Initializing multimedia...", 0.42f);

        #endregion MultimediaInit

        #region FontInit
        Logger.LogDebug("FONT_INIT--------------------------");
        EventManager.Instance.RaiseOnProgressUpdate("Login", "Initializing fonts...", 0.45f);

        #endregion FontInit

        #region SeedGrantedWait
        Logger.LogDebug("SEED_GRANTED_WAIT------------------");
        EventManager.Instance.RaiseOnProgressUpdate("Login", "Waiting for region capabilities...", 0.47f);

        await seedCapabilitiesTask;
        Logger.LogInfo($"Got capability grants.");

        #endregion SeedGrantedWait

        #region SeedCapabilitiesGranted
        Logger.LogDebug("SEED_CAPABILITIES_GRANTED----------");

        RegisterEventListeners();

        CircuitCode    = loginResponse.CircuitCode;
        region.Circuit = SlMessageSystem.Instance.EnableCircuit(new Host(loginResponse.SimIp, loginResponse.SimPort));

        EventManager.Instance.RaiseOnProgressUpdate("Login", "Waiting for region handshake...", 0.59f);
        await region.Circuit.SendUseCircuitCode(loginResponse.CircuitCode, SessionId, loginResponse.AgentId);

        Logger.LogInfo("UseCircuitCode was acked.");

        AvatarNameCache.Instance.Start();
        #endregion SeedCapabilitiesGranted

        #region AgentSend
        Logger.LogDebug("AGENT_SEND-------------------------");

        EventManager.Instance.RaiseOnProgressUpdate("Login", "Connecting to region...", 0.6f);
        await region.Circuit.SendCompleteAgentMovement(loginResponse.AgentId, SessionId, loginResponse.CircuitCode);

        Logger.LogInfo("CompleteAgentMovement was acked.");
        #endregion AgentSend

        #region InventorySend
        Logger.LogDebug("INVENTORY_SEND---------------------");

        //TODO: Fill in inventory skeleton and request details

        //Fill in buddy list skeleton and request names:
        AvatarTracker.Instance.AddBuddyList(loginResponse.BuddyList);

        // Set up callbacks:
        AvatarTracker.Instance.RegisterCallbacks();

        //TODO: Request mute list
        //TODO: Request money balance

        awaitables.Add(region.Circuit.SendAgentDataUpdateRequest(agent.Id, SessionId));

        #endregion InventorySend

        #region Misc
        Logger.LogDebug("MISC-------------------------------");

        //TODO: Calculate max bandwidth
        awaitables.Add(region.Circuit.SendAgentThrottle());

        //TODO: Download audio
        //TODO: Download active gestures

        awaitables.Add(region.Circuit.SendAgentHeightWidth(1080, 1920)); // TODO: This should take the title and status bars into account.

        #endregion Misc

        #region Precache
        Logger.LogDebug("PRECACHE---------------------------");
        EventManager.Instance.RaiseOnProgressUpdate("Login", "Loading world...", 0.9f);

        //TODO: Send AgentIsNowWearing

        await Task.WhenAll(awaitables.ToArray());

        awaitables.Clear();
        #endregion Precache

        #region Cleanup
        Logger.LogDebug("CLEANUP----------------------------");

        //TODO: Make map view observe inventory
        //TODO: Make map view observe friends
        //TODO: Stop Away animation
        //TODO: Clear control flag Away

        // Observe friends
        Agent.CurrentPlayer.ObserveFriends();

        //TODO: Retrieve land description
        //TODO: Send hover height to capability "AgentPreferences"

        EventManager.Instance.RaiseOnProgressUpdate("Login", "Complete", 1f);
        await Task.Delay(1000); // Wait to let player see the "Complete" message.

        EventManager.Instance.RaiseOnProgressUpdate("Login", "", 1f, true);
        #endregion Cleanup

        IsLoggedIn = true;

        await Task.Delay(3000);

        Logger.LogDebug("POST----------------");

        // TODO: This is in the application loop in Indra:
        VolumeLayerManager.UnpackLayerData();
    }
Ejemplo n.º 53
0
	protected void Page_Load (object sender, EventArgs e)
	{
		string action = Request ["action"];
		string referrer = Request ["referrer"] ?? (string) Session ["login_referrer"];
		Session.Remove ("login_referrer");
		bool noOpenIdResponse = false;

		if (!string.IsNullOrEmpty (referrer))
			txtReferrer.Value = referrer;

		if (!this.IsPostBack) {
			if (Request.UrlReferrer != null && string.IsNullOrEmpty (txtReferrer.Value))
				txtReferrer.Value = Request.UrlReferrer.AbsoluteUri;
		}

		// can't refer back to itself
		if (txtReferrer.Value.Contains ("Login.aspx"))
			txtReferrer.Value = "index.aspx";

		cmdLoginOpenId.Visible = !string.IsNullOrEmpty (Configuration.OpenIdProvider);
		cmdLoginOauth.Visible = !string.IsNullOrEmpty (Configuration.OauthClientId);

		if (!Configuration.AllowPasswordLogin) {
			cmdLogin.Visible = Configuration.AllowPasswordLogin;
			txtPassword.Visible = Configuration.AllowPasswordLogin;
			txtUser.Visible = Configuration.AllowPasswordLogin;
			lblUser.Visible = Configuration.AllowPasswordLogin;
			lblPassword.Visible = Configuration.AllowPasswordLogin;
		}

		if (cmdLoginOauth.Visible && Request.QueryString.GetValues ("state") != null) {
			var authResult = AuthenticationHelper.VerifyAuthentication ();
			if (!authResult.IsSuccessful) {
				lblMessageOpenId.Text = "Failed to get user authenication from Google";
				return;
			}

			LoginResponse loginResponse = new LoginResponse ();
			using (DB db = new DB ()) {
				try {
					DBLogin_Extensions.LoginOpenId (db, loginResponse, authResult.GetEmail (), Utilities.GetExternalIP (Request));
				} catch (Exception ex) {
					loginResponse.Exception = new WebServiceException (ex);
				}
			}
			if (loginResponse.Exception != null) {
				lblMessageOpenId.Text = loginResponse.Exception.Message;
			} else {
				Authentication.SetCookies (Response, loginResponse);
				Response.Redirect (txtReferrer.Value, false);
			}
			return;
		}

		if (cmdLoginOpenId.Visible) {
			OpenIdRelyingParty openid = new OpenIdRelyingParty ();
			var oidresponse = openid.GetResponse ();
			if (oidresponse != null) {
				switch (oidresponse.Status) {
				case AuthenticationStatus.Authenticated:
					// This is where you would look for any OpenID extension responses included
					// in the authentication assertion.
					var fetch = oidresponse.GetExtension<FetchResponse> ();
					string email;

					email = fetch.Attributes [WellKnownAttributes.Contact.Email].Values [0];

					WebServiceLogin login = new WebServiceLogin ();
					login.Password = Configuration.WebServicePassword;
					login.User = Configuration.Host;
					var response = Utils.LocalWebService.LoginOpenId (login, email, Utilities.GetExternalIP (Request));
					if (response.Exception != null) {
						lblMessageOpenId.Text = response.Exception.Message;
					} else {
						Authentication.SetCookies (Response, response);
						Response.Redirect (txtReferrer.Value, false);
						return;
					}
					break;
				default:
					lblMessageOpenId.Text = "Could not login using OpenId: " + oidresponse.Status.ToString ();
					break;
				}
			} else {
				noOpenIdResponse = true;
			}
		}

		if (!string.IsNullOrEmpty (action) && action == "logout") {
			if (Request.Cookies ["cookie"] != null) {
				Utils.LocalWebService.Logout (Master.WebServiceLogin);
				Response.Cookies.Add(new HttpCookie ("cookie", ""));
				Response.Cookies ["cookie"].Expires = DateTime.Now.AddYears (-20);
				Response.Cookies.Add (new HttpCookie ("user", ""));
				Response.Cookies ["user"].Expires = DateTime.Now.AddYears (-20);
				Response.Cookies.Add (new HttpCookie ("roles", ""));
				Response.Cookies ["roles"].Expires = DateTime.Now.AddYears (-20);
			}
			Response.Redirect (txtReferrer.Value, false);
			return;
		}
		
		var auto_openid_redirect = false;
		var auto = Request ["auto-redirect-openid"];
		if (!string.IsNullOrEmpty (auto) && auto.ToUpperInvariant () == "TRUE")
			auto_openid_redirect = true;

		if (!Configuration.AllowPasswordLogin && string.IsNullOrEmpty (action) && Configuration.AllowAnonymousAccess && noOpenIdResponse)
			auto_openid_redirect = true;

		if (auto_openid_redirect)
			cmdLoginOpenId_Click (null, null);
	}
Ejemplo n.º 54
0
 public Login(LoginResponse resp) : base(0x02, 2)
 {
     m_Stream.Write((byte)resp);
 }
Ejemplo n.º 55
0
 private void GetStepLength(LoginResponse lr, double estatura)
 {
     if (lr.Persona.Sexo == "M")
     {
         if (estatura != 0)
             StepLength = estatura*0.415;
         else
             StepLength = 78;
     }
     else
     {
         if (estatura == 0)
             StepLength = estatura*0.413;
         else
             StepLength = 70;
     }
 }
        public async Task <LoginResponse> Login([FromBody] LoginRequestModel prmLogin)
        {
            LoginResponse   respuesta      = null;
            string          codigoMensaje  = "COMUNES.ERRORSERVICIO";
            IUsuarioNegocio usuarioNegocio = FabricaNegocio.CrearUsuarioNegocio;

            try
            {
                if (String.IsNullOrEmpty(prmLogin.Username) || String.IsNullOrEmpty(prmLogin.Password))
                {
                    respuesta = new LoginResponse(HttpStatusCode.BadRequest, "LOGIN.RTA004");
                }
                else
                {
                    var usuarioExterno = await usuarioNegocio.ValidarUsuarioServicioExterno(prmLogin.Username, prmLogin.Password, false);

                    bool usuarioOk = usuarioExterno.Item1;
                    codigoMensaje = usuarioExterno.Item2;

                    if (usuarioOk)
                    {
                        var usuarioBD = usuarioNegocio.ObtenerUsuario(prmLogin.Username);

                        if (usuarioBD != null)
                        {
                            if (usuarioBD.Activo)
                            {
                                respuesta = new LoginResponse(usuarioBD, this.GenerateTokenJWT(prmLogin.Username));
                                var usrLogin = new Comun.Entidades.UsuarioPerfil.MODLoginUsuario {
                                    IdUsuario = usuarioBD.IdUsuario,
                                    UserName  = usuarioBD.UserName,
                                    IP        = prmLogin.Ip,
                                    Token     = respuesta.Token
                                };
                                if (ConfiguracionNegocio.SessionUsuario(usrLogin, Comun.Enumeradores.EnumSession._inicio))
                                {
                                    usuarioNegocio.ActualizarUltimaFechaLogin(prmLogin.Username);
                                }
                                else
                                {
                                    respuesta = new LoginResponse(HttpStatusCode.BadRequest, "LOGIN.RTA006");
                                }
                                var aud = FabricaNegocio.CrearAuditoriaNegocio;
                                var usr = new MODLoginUsuario();
                                aud.CrearRastroAuditoria(Comun.Enumeradores.EnumTipoAccionAuditoria.login, usuarioBD.IdUsuario.ToString(), "Autenticacion", usr, usrLogin, prmLogin.Username, prmLogin.Ip);
                            }
                            else
                            {
                                respuesta = new LoginResponse(HttpStatusCode.BadRequest, "LOGIN.RTA005");
                            }
                        }
                        else
                        {
                            respuesta = new LoginResponse(HttpStatusCode.BadRequest, "LOGIN.RTA003");
                        }
                    }
                    else
                    {
                        respuesta = new LoginResponse(HttpStatusCode.BadRequest, codigoMensaje);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteLog(ex, "AutenticacionController.Login", JsonSerializer.Serialize(prmLogin), ErrorType.Error);
                respuesta = new LoginResponse(HttpStatusCode.InternalServerError, codigoMensaje);
            }

            return(respuesta);
        }
Ejemplo n.º 57
0
		public Login( LoginResponse resp ) : base( 0x02, 2 )
		{
			m_Stream.Write( (byte)resp );
		}
Ejemplo n.º 58
0
        /// <summary>
        ///     Handles incoming messages.
        /// </summary>
        /// <param name="sender">The <see cref="IMessageConnection"/> instance from which the message originated.</param>
        /// <param name="message">The message.</param>
        public async void HandleMessageRead(object sender, byte[] message)
        {
            var code = new MessageReader <MessageCode.Server>(message).ReadCode();

            if (code != MessageCode.Server.SearchRequest)
            {
                Diagnostic.Debug($"Server message received: {code}");
            }

            try
            {
                switch (code)
                {
                case MessageCode.Server.ParentMinSpeed:
                case MessageCode.Server.ParentSpeedRatio:
                case MessageCode.Server.WishlistInterval:
                case MessageCode.Server.CheckPrivileges:
                    SoulseekClient.Waiter.Complete(new WaitKey(code), IntegerResponse.FromByteArray <MessageCode.Server>(message));
                    break;

                case MessageCode.Server.NewPassword:
                    var confirmedPassword = NewPassword.FromByteArray(message).Password;
                    SoulseekClient.Waiter.Complete(new WaitKey(code), confirmedPassword);
                    break;

                case MessageCode.Server.GlobalAdminMessage:
                    var msg = GlobalMessageNotification.FromByteArray(message);
                    GlobalMessageReceived?.Invoke(this, new GlobalMessageReceivedEventArgs(msg));
                    break;

                case MessageCode.Server.Ping:
                    SoulseekClient.Waiter.Complete(new WaitKey(code));
                    break;

                case MessageCode.Server.Login:
                    SoulseekClient.Waiter.Complete(new WaitKey(code), LoginResponse.FromByteArray(message));
                    break;

                case MessageCode.Server.RoomList:
                    var roomList = RoomListResponse.FromByteArray(message);
                    SoulseekClient.Waiter.Complete(new WaitKey(code), roomList);
                    RoomListReceived?.Invoke(this, new RoomListReceivedEventArgs(roomList));
                    break;

                case MessageCode.Server.PrivilegedUsers:
                    var privilegedUserList = PrivilegedUserListNotification.FromByteArray(message);
                    SoulseekClient.Waiter.Complete(new WaitKey(code), privilegedUserList);
                    PrivilegedUserListReceived?.Invoke(this, new PrivilegedUserListReceivedEventArgs(privilegedUserList));
                    break;

                case MessageCode.Server.AddPrivilegedUser:
                    PrivilegeNotificationReceived?.Invoke(this, new PrivilegeNotificationReceivedEventArgs(PrivilegedUserNotification.FromByteArray(message)));
                    break;

                case MessageCode.Server.NotifyPrivileges:
                    var pn = PrivilegeNotification.FromByteArray(message);
                    PrivilegeNotificationReceived?.Invoke(this, new PrivilegeNotificationReceivedEventArgs(pn.Username, pn.Id));

                    if (SoulseekClient.Options.AutoAcknowledgePrivilegeNotifications)
                    {
                        await SoulseekClient.AcknowledgePrivilegeNotificationAsync(pn.Id, CancellationToken.None).ConfigureAwait(false);
                    }

                    break;

                case MessageCode.Server.UserPrivileges:
                    var privilegeResponse = UserPrivilegeResponse.FromByteArray(message);
                    SoulseekClient.Waiter.Complete(new WaitKey(code, privilegeResponse.Username), privilegeResponse.IsPrivileged);
                    break;

                case MessageCode.Server.NetInfo:
                    var netInfo = NetInfoNotification.FromByteArray(message);

                    try
                    {
                        var parents = netInfo.Parents.Select(parent => (parent.Username, new IPEndPoint(parent.IPAddress, parent.Port)));
                        await SoulseekClient.DistributedConnectionManager.AddParentConnectionAsync(parents).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        Diagnostic.Debug($"Error handling NetInfo message: {ex.Message}");
                    }

                    break;

                case MessageCode.Server.ConnectToPeer:
                    ConnectToPeerResponse connectToPeerResponse = default;

                    try
                    {
                        connectToPeerResponse = ConnectToPeerResponse.FromByteArray(message);

                        if (connectToPeerResponse.Type == Constants.ConnectionType.Transfer)
                        {
                            Diagnostic.Debug($"Received transfer ConnectToPeer request from {connectToPeerResponse.Username} ({connectToPeerResponse.IPEndPoint}) for remote token {connectToPeerResponse.Token}");

                            // ensure that we are expecting at least one file from this user before we connect. the response
                            // doesn't contain any other identifying information about the file.
                            if (!SoulseekClient.Downloads.IsEmpty && SoulseekClient.Downloads.Values.Any(d => d.Username == connectToPeerResponse.Username))
                            {
                                var(connection, remoteToken) = await SoulseekClient.PeerConnectionManager.GetTransferConnectionAsync(connectToPeerResponse).ConfigureAwait(false);

                                var download = SoulseekClient.Downloads.Values.FirstOrDefault(v => v.RemoteToken == remoteToken && v.Username == connectToPeerResponse.Username);

                                if (download != default(TransferInternal))
                                {
                                    Diagnostic.Debug($"Solicited inbound transfer connection to {download.Username} ({connection.IPEndPoint}) for token {download.Token} (remote: {download.RemoteToken}) established. (id: {connection.Id})");
                                    SoulseekClient.Waiter.Complete(new WaitKey(Constants.WaitKey.IndirectTransfer, download.Username, download.Filename, download.RemoteToken), connection);
                                }
                                else
                                {
                                    Diagnostic.Debug($"Transfer ConnectToPeer request from {connectToPeerResponse.Username} ({connectToPeerResponse.IPEndPoint}) for remote token {connectToPeerResponse.Token} does not match any waiting downloads, discarding.");
                                    connection.Disconnect($"Unknown transfer");
                                }
                            }
                            else
                            {
                                throw new SoulseekClientException($"Unexpected transfer request from {connectToPeerResponse.Username} ({connectToPeerResponse.IPEndPoint}); Ignored");
                            }
                        }
                        else if (connectToPeerResponse.Type == Constants.ConnectionType.Peer)
                        {
                            Diagnostic.Debug($"Received message ConnectToPeer request from {connectToPeerResponse.Username} ({connectToPeerResponse.IPEndPoint})");
                            await SoulseekClient.PeerConnectionManager.GetOrAddMessageConnectionAsync(connectToPeerResponse).ConfigureAwait(false);
                        }
                        else if (connectToPeerResponse.Type == Constants.ConnectionType.Distributed)
                        {
                            Diagnostic.Debug($"Received distributed ConnectToPeer request from {connectToPeerResponse.Username} ({connectToPeerResponse.IPEndPoint})");
                            await SoulseekClient.DistributedConnectionManager.AddChildConnectionAsync(connectToPeerResponse).ConfigureAwait(false);
                        }
                        else
                        {
                            throw new MessageException($"Unknown Connect To Peer connection type '{connectToPeerResponse.Type}'");
                        }
                    }
                    catch (Exception ex)
                    {
                        Diagnostic.Debug($"Error handling ConnectToPeer response from {connectToPeerResponse?.Username} ({connectToPeerResponse?.IPEndPoint}): {ex.Message}");
                    }

                    break;

                case MessageCode.Server.AddUser:
                    var addUserResponse = AddUserResponse.FromByteArray(message);
                    SoulseekClient.Waiter.Complete(new WaitKey(code, addUserResponse.Username), addUserResponse);
                    break;

                case MessageCode.Server.GetStatus:
                    var statsResponse = UserStatusResponse.FromByteArray(message);
                    SoulseekClient.Waiter.Complete(new WaitKey(code, statsResponse.Username), statsResponse);
                    UserStatusChanged?.Invoke(this, new UserStatusChangedEventArgs(statsResponse));
                    break;

                case MessageCode.Server.PrivateMessage:
                    var pm = PrivateMessageNotification.FromByteArray(message);
                    PrivateMessageReceived?.Invoke(this, new PrivateMessageReceivedEventArgs(pm));

                    if (SoulseekClient.Options.AutoAcknowledgePrivateMessages)
                    {
                        await SoulseekClient.AcknowledgePrivateMessageAsync(pm.Id, CancellationToken.None).ConfigureAwait(false);
                    }

                    break;

                case MessageCode.Server.GetPeerAddress:
                    var peerAddressResponse = UserAddressResponse.FromByteArray(message);
                    SoulseekClient.Waiter.Complete(new WaitKey(code, peerAddressResponse.Username), peerAddressResponse);
                    break;

                case MessageCode.Server.JoinRoom:
                    var roomData = RoomJoinResponse.FromByteArray(message);
                    SoulseekClient.Waiter.Complete(new WaitKey(code, roomData.Name), roomData);
                    break;

                case MessageCode.Server.LeaveRoom:
                    var leaveRoomResponse = RoomLeaveResponse.FromByteArray(message);
                    SoulseekClient.Waiter.Complete(new WaitKey(code, leaveRoomResponse.RoomName));
                    break;

                case MessageCode.Server.SayInChatRoom:
                    var roomMessage = RoomMessageNotification.FromByteArray(message);
                    RoomMessageReceived?.Invoke(this, new RoomMessageReceivedEventArgs(roomMessage));
                    break;

                case MessageCode.Server.UserJoinedRoom:
                    var joinNotification = RoomJoinedNotification.FromByteArray(message);
                    RoomJoined?.Invoke(this, new RoomJoinedEventArgs(joinNotification));
                    break;

                case MessageCode.Server.UserLeftRoom:
                    var leftNotification = RoomLeftNotification.FromByteArray(message);
                    RoomLeft?.Invoke(this, new RoomLeftEventArgs(leftNotification));
                    break;

                case MessageCode.Server.KickedFromServer:
                    KickedFromServer?.Invoke(this, EventArgs.Empty);
                    break;

                case MessageCode.Server.FileSearch:
                    var searchRequest = ServerSearchRequest.FromByteArray(message);

                    // sometimes (most of the time?) a room search will result in a request to ourselves (assuming we are
                    // joined to it)
                    if (searchRequest.Username == SoulseekClient.Username)
                    {
                        break;
                    }

                    SearchResponse searchResponse;

                    if (SoulseekClient.Options.SearchResponseResolver == default)
                    {
                        break;
                    }

                    try
                    {
                        searchResponse = await SoulseekClient.Options.SearchResponseResolver(searchRequest.Username, searchRequest.Token, SearchQuery.FromText(searchRequest.Query)).ConfigureAwait(false);

                        if (searchResponse != null && searchResponse.FileCount > 0)
                        {
                            var endpoint = await SoulseekClient.GetUserEndPointAsync(searchRequest.Username).ConfigureAwait(false);

                            var peerConnection = await SoulseekClient.PeerConnectionManager.GetOrAddMessageConnectionAsync(searchRequest.Username, endpoint, CancellationToken.None).ConfigureAwait(false);

                            await peerConnection.WriteAsync(searchResponse.ToByteArray()).ConfigureAwait(false);
                        }
                    }
                    catch (Exception ex)
                    {
                        Diagnostic.Warning($"Error resolving search response for query '{searchRequest.Query}' requested by {searchRequest.Username} with token {searchRequest.Token}: {ex.Message}", ex);
                    }

                    break;

                // if we fail to connect to a distributed parent in a timely manner, the server will begin to send us distributed search requests directly.
                // forward these to the distributed message handler.
                case MessageCode.Server.SearchRequest:
                    SoulseekClient.DistributedMessageHandler.HandleMessageRead(SoulseekClient.ServerConnection, message);
                    break;

                default:
                    Diagnostic.Debug($"Unhandled server message: {code}; {message.Length} bytes");
                    break;
                }
            }
            catch (Exception ex)
            {
                Diagnostic.Warning($"Error handling server message: {code}; {ex.Message}", ex);
            }
        }