Exemplo n.º 1
0
        private async void click_login(object sender, EventArgs e)
        {
            try
            {
                /**/
                if (string.IsNullOrEmpty(entryUsername.Text))
                {
                    await Shell.Current.DisplayAlert("", "Nhập email hoặc số điện thoại", "Đóng");

                    return;
                }
                if (string.IsNullOrEmpty(entryPassword.Text))
                {
                    await Shell.Current.DisplayAlert("", "Nhập mật khẩu", "Đóng");

                    return;
                }

                string userName = entryUsername.Text.Trim();
                string passWord = entryPassword.Text.Trim();

                ApiResponse loginResponse = await ApiHelper.Login(userName, passWord);

                if (loginResponse.IsSuccess)
                {
                    AuthResponse authResponse = JsonConvert.DeserializeObject <AuthResponse>(loginResponse.Content.ToString());
                    UserLogged.UserName = userName;
                    UserLogged.Password = passWord;
                    UserLogged.SaveLogin(authResponse);

                    Application.Current.MainPage = new AppShell();
                }
                else
                {
                    string messageError = loginResponse.GetFirstErrorMessage();
                    if (string.IsNullOrEmpty(messageError))
                    {
                        messageError = "Lỗi đăng nhập, vui lòng thử lại sau.";
                    }
                    await Shell.Current.DisplayAlert("", messageError, "Đóng");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Exemplo n.º 2
0
        private static async void OnAuthLoginCompleted(object sender, AuthenticatorCompletedEventArgs e)
        {
            var authenticator = sender as OAuth2Authenticator;

            if (authenticator != null)
            {
                authenticator.Completed -= OnAuthLoginCompleted;
                authenticator.Error     -= OnAuthLoginError;
            }
            //LoginUser = null;
            if (e.IsAuthenticated)
            {
                // If the user is authenticated, request their basic user data from Google
                // UserInfoUrl = https://www.googleapis.com/oauth2/v2/userinfo
                var request  = new OAuth2Request("GET", new Uri(UserInfoUrl), null, e.Account);
                var response = await request.GetResponseAsync();

                if (response != null)
                {
                    // Deserialize the data and store it in the account store
                    // The users email address will be used to identify data in SimpleDB
                    string userJson = await response.GetResponseTextAsync();

                    GoogleUser googleUser = JsonConvert.DeserializeObject <GoogleUser>(userJson);

                    var ggUser = new User()
                    {
                        FullName  = googleUser.Name,
                        Email     = googleUser.Email,
                        GoogleId  = googleUser.Id,
                        AvatarUrl = googleUser.Picture
                    };

                    var uri = new Uri(ApiConfig.IP + ApiRouter.USER_SOCIALLOGIN);
                    try
                    {
                        var json    = JsonConvert.SerializeObject(ggUser);
                        var content = new StringContent(json, Encoding.UTF8, "application/json");
                        HttpResponseMessage httpResponse = await _client.PostAsync(uri, content);

                        if (httpResponse.IsSuccessStatusCode)
                        {
                            var loginResponseJson = await httpResponse.Content.ReadAsStringAsync();

                            var loginResponse = JsonConvert.DeserializeObject <AuthenticateReponse>(loginResponseJson);

                            //save user
                            UserLogged.SaveLogin(loginResponse);

                            Application.Current.MainPage = new AppShell();
                        }
                        else
                        {
                            var message = JsonConvert.DeserializeObject <string>(await httpResponse.Content.ReadAsStringAsync());
                            if (message == "Email đã tồn tại!")
                            {
                                throw new Exception(Language.email_da_ton_tai);
                            }
                            else
                            {
                                await Application.Current.MainPage.Navigation.PushAsync(new AddAuthInfoPage(ggUser), false);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        await Application.Current.MainPage.DisplayAlert("Thông báo", ex.Message, Language.dong);
                    }
                }
            }
        }
Exemplo n.º 3
0
        public async void SocialLogin <T>(T user) where T : class
        {
            object       data         = null;
            FacebookUser facebookUser = null;
            GoogleUser   googleUser   = null;
            ZaloUser     zaloUser     = null;
            string       email        = null;

            if (user.GetType() == typeof(FacebookUser))
            {
                facebookUser = user as FacebookUser;
                data         = new
                {
                    FullName   = facebookUser.FullName,
                    Email      = facebookUser.Email,
                    FacebookId = facebookUser.Id,
                    PictureUrl = facebookUser.Picture
                };

                if (!string.IsNullOrEmpty(facebookUser.Email))
                {
                    email = facebookUser.Email;
                }

                if (email == null)
                {
                    await Shell.Current.DisplayAlert("", "Vui lòng cung cấp địa chỉ Email để đăng nhập ", "Đóng");

                    //customTabbed_Login.ShowLoading(false);
                    return;
                }
            }
            else if (user.GetType() == typeof(GoogleUser))
            {
                googleUser = user as GoogleUser;
                data       = new
                {
                    FullName   = googleUser.Name,
                    Email      = googleUser.Email,
                    GoogleId   = googleUser.Id,
                    PictureUrl = googleUser.Picture
                };
                if (!string.IsNullOrEmpty(googleUser.Email))
                {
                    email = googleUser.Email;
                }


                if (email == null)
                {
                    await Shell.Current.DisplayAlert("", "Vui lòng cung cấp địa chỉ Email để đăng nhập ", "Đóng");

                    //customTabbed_Login.ShowLoading(false);
                    return;
                }
            }
            if (user.GetType() == typeof(ZaloUser))
            {
                zaloUser = user as ZaloUser;
                data     = new
                {
                    FullName   = zaloUser.name,
                    ZaloId     = zaloUser.id,
                    PictureUrl = zaloUser?.picture?.data?.url ?? "",
                    Birthday   = zaloUser.birthday,
                    Sex        = zaloUser.gender
                };
            }

            ApiResponse loginResponse = await ApiHelper.Post("api/auth/facebooklogin", data);

            if (loginResponse.IsSuccess)
            {
                AuthResponse authResponse = JsonConvert.DeserializeObject <AuthResponse>(loginResponse.Content.ToString());
                UserLogged.UserName = authResponse.Email;
                UserLogged.Password = UserLogged.UserName;
                if (googleUser != null)
                {
                    UserLogged.GoogleId = googleUser.Id;
                }
                else if (facebookUser != null)
                {
                    UserLogged.FacebookId = facebookUser.Id;
                }
                if (zaloUser != null)
                {
                    UserLogged.ZaloId = zaloUser.id;
                }

                UserLogged.SaveLogin(authResponse);
                Application.Current.MainPage = new AppShell();
            }
            else
            {
                string ErrorMessage = loginResponse.GetFirstErrorMessage();
                if (string.IsNullOrEmpty(ErrorMessage))
                {
                    ErrorMessage = "Lỗi đăng nhập vui lòng thử lại";
                }
                await Shell.Current.DisplayAlert("", ErrorMessage, "Đóng");
            }
        }
Exemplo n.º 4
0
        public async static Task <ApiResponse> Get <T>(string Path, bool Authenticate = false, bool RefreshToken = true) where T : class
        {
            var network = Connectivity.NetworkAccess;

            if (network != NetworkAccess.Internet)
            {
                return(new ApiResponse(false, null, "Không có kết nối Internet"));
            }

            try
            {
                var         client = BsdHttpClient.Instance();
                ApiResponse res    = new ApiResponse();
                if (Authenticate)
                {
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", UserLogged.AccessToken);
                }
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response = await client.GetAsync(Path);

                if (response.IsSuccessStatusCode)
                {
                    string body = await response.Content.ReadAsStringAsync();

                    res.IsSuccess = true;
                    res.Content   = JsonConvert.DeserializeObject <T>(body);
                }
                else if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
                {
                    res.IsSuccess = true;
                    var body = await response.Content.ReadAsStringAsync();

                    res.Content = JsonConvert.DeserializeObject <T>(body);
                }
                else if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                {
                    if (response.Headers.Contains("Token-Expired"))
                    {
                    }
                    if (UserLogged.IsLogged && Authenticate && RefreshToken)
                    {
                        ApiResponse loginResponse;
                        if (UserLogged.FacebookId != string.Empty)
                        {
                            loginResponse = await LoginFacebook(UserLogged.Email, UserLogged.FacebookId);
                        }
                        else if (UserLogged.GoogleId != string.Empty)
                        {
                            loginResponse = await LoginGoogle(UserLogged.Email, UserLogged.GoogleId);
                        }
                        else if (UserLogged.ZaloId != string.Empty)
                        {
                            loginResponse = await LoginZalo(UserLogged.ZaloId);
                        }
                        else
                        {
                            loginResponse = await Login(UserLogged.UserName, UserLogged.Password);
                        }

                        if (loginResponse.IsSuccess)
                        {
                            AuthResponse authResponse = JsonConvert.DeserializeObject <AuthResponse>(loginResponse.Content.ToString());
                            UserLogged.SaveLogin(authResponse);
                            res = await Get <T>(Path, true, false);
                        }
                        else
                        {
                            res.Message   = "Vui long dang nhap lai";
                            res.IsSuccess = false;
                        }
                    }
                    else
                    {
                        // loi dang nhap, co token user pass nhung ko dang nhap duoc.
                        res.Message   = "Vui long dang nhap lai";
                        res.IsSuccess = false;
                    }
                }
                else
                {
                    var body = await response.Content.ReadAsStringAsync();

                    res.Message   = body;
                    res.IsSuccess = false;
                }
                return(res);
            }
            catch (Exception ex)
            {
                return(new ApiResponse()
                {
                    IsSuccess = false,
                    Message = ex.Message
                });
            }
        }
Exemplo n.º 5
0
        public async static Task <ApiResponse> Put(string Path, object formContent, bool Authenticate = false, bool RefreshToken = true)
        {
            var network = Connectivity.NetworkAccess;

            if (network != NetworkAccess.Internet)
            {
                return(new ApiResponse(false, null, "Không có kết nối Internet"));
            }
            try
            {
                var         client = BsdHttpClient.Instance();
                ApiResponse res    = new ApiResponse();
                //client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                if (Authenticate)
                {
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", UserLogged.AccessToken);
                }
                HttpResponseMessage response;

                if (formContent == null)
                {
                    var request = new HttpRequestMessage(HttpMethod.Put, Path);
                    response = await client.SendAsync(request);
                }
                else
                {
                    string      objContent = JsonConvert.SerializeObject(formContent);
                    HttpContent content    = new StringContent(objContent, Encoding.UTF8, "application/json");
                    response = await client.PutAsync(Path, content);
                }

                if (response.IsSuccessStatusCode)
                {
                    var body = await response.Content.ReadAsStringAsync();

                    return(JsonConvert.DeserializeObject <ApiResponse>(body));
                }
                else if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
                {
                    var body = await response.Content.ReadAsStringAsync();

                    return(JsonConvert.DeserializeObject <ApiResponse>(body));
                }
                else if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                {
                    if (UserLogged.IsLogged && Authenticate && RefreshToken)
                    {
                        ApiResponse loginResponse;
                        if (UserLogged.FacebookId != string.Empty)
                        {
                            loginResponse = await LoginFacebook(UserLogged.Email, UserLogged.FacebookId);
                        }
                        else if (UserLogged.GoogleId != string.Empty)
                        {
                            loginResponse = await LoginGoogle(UserLogged.Email, UserLogged.GoogleId);
                        }
                        else if (UserLogged.ZaloId != string.Empty)
                        {
                            loginResponse = await LoginZalo(UserLogged.ZaloId);
                        }
                        else
                        {
                            loginResponse = await Login(UserLogged.UserName, UserLogged.Password);
                        }

                        if (loginResponse.IsSuccess)
                        {
                            AuthResponse authResponse = JsonConvert.DeserializeObject <AuthResponse>(loginResponse.Content.ToString());
                            UserLogged.SaveLogin(authResponse);
                            res = await Put(Path, formContent, true, false);
                        }
                        else
                        {
                            res.Message   = "Vui long dang nhap lai";
                            res.IsSuccess = false;
                        }
                    }
                    else
                    {
                        // loi dang nhap, co token user pass nhung ko dang nhap duoc.
                        res.Message   = "Vui long dang nhap lai";
                        res.IsSuccess = false;
                    }
                }
                else
                {
                    var body = await response.Content.ReadAsStringAsync();

                    res.Message   = "Lỗi";
                    res.IsSuccess = false;
                }
                return(res);
            }
            catch (Exception ex)
            {
                return(new ApiResponse()
                {
                    IsSuccess = false,
                    Message = ex.Message
                });
            }
        }
        private async void WebView_Navigating(object sender, WebNavigatedEventArgs e)
        {
            //gridLoading.IsVisible = false;
            if (e.Url.StartsWith("https://bsdinsight.net", StringComparison.Ordinal))
            {
                try
                {
                    string queryString = e.Url.Replace(CallBackUrl, "");
                    Dictionary <string, string> keyValues = ParseQueryString(queryString);
                    if (keyValues.ContainsKey("code") == false)
                    {
                        return;
                    }

                    string code = keyValues["code"];
                    using (HttpClient client = new HttpClient())
                    {
                        HttpResponseMessage response = await client.GetAsync($"https://oauth.zaloapp.com/v3/access_token?app_id={ZALOAPPID}&app_secret={AppScret}&code={code}");

                        if (response.IsSuccessStatusCode)
                        {
                            HttpContent auContent = response.Content;
                            string      authBody  = await auContent.ReadAsStringAsync();

                            ZaloAuthReponse zaloAuthReponse = JsonConvert.DeserializeObject <ZaloAuthReponse>(authBody);


                            var profileResponse = await client.GetAsync($"https://graph.zalo.me/v2.0/me?access_token={zaloAuthReponse.access_token}&fields=id,birthday,name,gender,picture");

                            var profileBody = await profileResponse.Content.ReadAsStringAsync();

                            ZaloUser zaloUser = JsonConvert.DeserializeObject <ZaloUser>(profileBody);

                            var zlUser = new User()
                            {
                                ZaloId    = long.Parse(zaloUser.id),
                                FullName  = zaloUser.name,
                                Sex       = zaloUser.gender == "male" ? (short)0 : zaloUser.gender == "female" ? (short)1 : (short)-1,
                                Birthday  = DateTime.ParseExact(zaloUser.birthday, "dd/MM/yyyy", null),
                                AvatarUrl = zaloUser.picture.data.url
                            };

                            try
                            {
                                var apiResponse = await ApiHelper.Post(ApiRouter.USER_SOCIALLOGIN, zlUser);

                                if (apiResponse.IsSuccess)
                                {
                                    var loginResponse = JsonConvert.DeserializeObject <AuthenticateReponse>(apiResponse.Content.ToString());

                                    //save user
                                    await UserLogged.SaveLogin(loginResponse);

                                    Application.Current.MainPage = new AppShell();
                                }
                                else
                                {
                                    await Application.Current.MainPage.Navigation.PushAsync(new AddAuthInfoPage(zlUser));
                                }
                            }
                            catch (Exception ex)
                            {
                                await Application.Current.MainPage.DisplayAlert("", Language.loi_he_thong_vui_long_thu_lai, Language.dong);

                                await Navigation.PopAsync();
                            }
                        }
                        else
                        {
                            await DisplayAlert("", Language.loi_he_thong_vui_long_thu_lai, Language.dong);

                            await this.Navigation.PopToRootAsync();
                        }
                    }
                }
                catch (Exception ex)
                {
                    await DisplayAlert("", Language.loi_he_thong_vui_long_thu_lai, Language.dong);

                    await this.Navigation.PopToRootAsync();
                }
            }
        }