Exemple #1
0
        public static GoogleUserOutputData GetGoogleOauth(string code)
        {
            var data         = $"code={code}&client_id={googleClientId}&client_secret={googleClientSecret}&redirect_uri={googleRedirectUrl}&grant_type=authorization_code";
            var getTokenCode = HttpHelper.CreateHttpGetRequest(getTokenUrl, data);

            GoogleUserOutputData result    = null;
            GoogleAccessToken    tokenInfo = JsonConvert.DeserializeObject <GoogleAccessToken>(getTokenCode);

            if (tokenInfo != null)
            {
                string accessToken = tokenInfo.access_token;
                if (!string.IsNullOrWhiteSpace(accessToken))
                {
                    WebClient client = new WebClient();
                    client.Encoding = Encoding.UTF8;

                    var    url            = urlProfile + accessToken;
                    string downloadString = client.DownloadString(url);

                    result = JsonConvert.DeserializeObject <GoogleUserOutputData>(downloadString);

                    result.token = accessToken;
                }
            }

            return(result);
        }
Exemple #2
0
        private async void getgoogleplususerdataSer(string access_token)
        {
            try
            {
                HttpClient client     = new HttpClient();
                var        urlProfile = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + access_token;

                client.CancelPendingRequests();
                HttpResponseMessage output = await client.GetAsync(urlProfile);

                if (output.IsSuccessStatusCode)
                {
                    string outputData = await output.Content.ReadAsStringAsync();

                    GoogleUserOutputData serStatus = JsonConvert.DeserializeObject <GoogleUserOutputData>(outputData);

                    if (serStatus != null)
                    {
                        nome             = serStatus.name;
                        email            = serStatus.email;
                        this.label5.Text = email;
                        this.label7.Text = nome;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                //catching the exception
            }
        }
        public async Task <string> GetUserDetailsAsync(string accessToken)
        {
            // Lay thông tin user

            HttpClient client = new HttpClient();

            client.BaseAddress = new Uri("https://oauth2.googleapis.com");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            GoogleUserOutputData serStatus = new GoogleUserOutputData();

            try
            {
                var url = "https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=" + accessToken;
                HttpResponseMessage output = client.GetAsync(url).Result;


                if (output.IsSuccessStatusCode)

                {
                    string outputData = output.Content.ReadAsStringAsync().Result;

                    serStatus = JsonConvert.DeserializeObject <GoogleUserOutputData>(outputData);
                    //name = serStatus.email;
                }
            }

            catch (Exception ex)
            {
            }
            return(serStatus.email);
        }
        private async void getgoogleplususerdataSer(string access_token)
        {
            try
            {
                HttpClient client     = new HttpClient();
                var        urlProfile = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + access_token;

                client.CancelPendingRequests();
                HttpResponseMessage output = await client.GetAsync(urlProfile);

                if (output.IsSuccessStatusCode)
                {
                    string outputData = await output.Content.ReadAsStringAsync();

                    GoogleUserOutputData serStatus = JsonConvert.DeserializeObject <GoogleUserOutputData>(outputData);



                    if (serStatus != null)
                    {
                        // You will get the user information here.
                        Cache["id"]         = serStatus.id;
                        Cache["name"]       = serStatus.name;
                        Cache["given_name"] = serStatus.given_name;
                        Cache["picture"]    = serStatus.picture;
                    }
                }
            }
            catch (Exception ex)
            {
                //catching the exception
            }
        }
Exemple #5
0
        /// <summary>
        /// Metodo que se encarga de obtener la informacion basica de la cuenta de Google con la que se accedio a la aplicacion
        /// </summary>
        /// <param name="accessToken">Token de acceso proporcionado por Google para porder obtener la informacion</param>
        /// <returns>Objeto de la clase GoogleOutputData que alamacena la informacion obtenidoa de la API de Google</returns>
        public GoogleUserOutputData obtenerInformacionGoogle(string accessToken)
        {
            GoogleUserOutputData usuario = null;
            HttpClient           client  = new HttpClient();
            string urlProfile;
            HttpResponseMessage output;

            try
            {
                urlProfile = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + accessToken;

                client.CancelPendingRequests();
                output = client.GetAsync(urlProfile).Result;
            }
            catch (Exception)
            {
                throw new TokenInvalidoException("\n" + "No se pudo establecer conexión con Google" + "\n");
            }

            if (output.IsSuccessStatusCode)
            {
                string outputData = output.Content.ReadAsStringAsync().Result;
                usuario = JsonConvert.DeserializeObject <GoogleUserOutputData>(outputData);
            }
            else
            {
                throw new TokenInvalidoException("\n" + "El token ingresado es invalido" + "\n");
            }

            return(usuario);
        }
Exemple #6
0
        private async Task <User> GetGooglePlusUserData(string access_token)
        {
            try
            {
                var    urlProfile  = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + access_token;
                User   user        = null;
                string serStatusId = null;
                using (HttpClient client = new HttpClient())
                {
                    client.CancelPendingRequests();
                    HttpResponseMessage output = await client.GetAsync(urlProfile);

                    if (output.IsSuccessStatusCode)
                    {
                        string outputData = await output.Content.ReadAsStringAsync();

                        GoogleUserOutputData serStatus = JsonConvert.DeserializeObject <GoogleUserOutputData>(outputData);

                        if (serStatus != null)
                        {
                            user = new User()
                            {
                                GoogleId  = serStatus.id,
                                Name      = serStatus.name,
                                GivenName = serStatus.given_name,
                                Email     = serStatus.email,
                                Picture   = serStatus.picture
                            };
                            serStatusId = serStatus.id;
                        }
                    }
                }

                if (user != null)
                {
                    var users = _userService.GetAll();
                    if (users.Any(x => x.Name == user.Name))
                    {
                        var auth = Authenticate(user.Name, serStatusId);
                        return(auth);
                    }
                    else
                    {
                        var create = _userService.Create(user);
                        return(create);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new AppException(ex.Message);
            }
            return(null);
        }
        public ActionResult GoogleCallBack(string code)
        {
            var    id                = "*****@*****.**";
            string AccessToken       = string.Empty;
            string RefreshToken      = ExchangeAuthorizationCode(id, code, out AccessToken);
            GoogleUserOutputData Obj = FetchEmailId(AccessToken);

            ViewBag.Email = Obj.Email;
            ViewBag.Token = Obj.Access_token;
            return(View(Obj));
        }
Exemple #8
0
        /// <summary>
        /// Metodo que permite la autenticacion de los usuarios, donde se obtiene la informacion de la cuenta de Google y se comprara
        /// con la infomracion de la base de datos local para saber si el usuario esta registrado o no.
        /// </summary>
        /// <param name="accessToken">TOken de acceso proporcionado por la API de Google</param>
        /// <returns></returns>
        public bool autenticarUsuario(String accessToken)
        {
            GoogleUserOutputData usuario = obtenerInformacionGoogle(accessToken);

            Usuario usuarioBuscado = buscarUsuario(usuario.id);

            if (usuarioBuscado == null)
            {
                return(false);
            }

            return(true);
        }
        public ActionResult LogOut(string token)
        {
            HttpClient client = new HttpClient();
            var        url    = "https://accounts.google.com/o/oauth2/revoke?token=" + token;

            client.CancelPendingRequests();
            GoogleUserOutputData obj    = new GoogleUserOutputData();
            HttpResponseMessage  output = client.GetAsync(url).Result;

            if (output.IsSuccessStatusCode)
            {
                string outputData = output.Content.ReadAsStringAsync().Result;
            }
            return(View());
        }
     public static GoogleUserOutputData Googlemethod(string code)
     {
         GoogleUserOutputData serStatus1 = new GoogleUserOutputData();
         string json_data = string.Empty;
         if (code != null)
         {
             //get the access token 
             HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
             webRequest.Method = "POST";
             Parameters = "code=" + code + "&client_id=" + ConfigurationManager.AppSettings["googleplus_client_id"] +
                 "&client_secret=" + ConfigurationManager.AppSettings["googleplus_client_secret"] +
                 "&redirect_uri=" + ConfigurationManager.AppSettings["googleplus_redirect_url"] + "&grant_type=authorization_code";
             byte[] byteArray = Encoding.UTF8.GetBytes(Parameters);
             webRequest.ContentType = "application/x-www-form-urlencoded";
             webRequest.ContentLength = byteArray.Length;
             Stream postStream = webRequest.GetRequestStream();
             // Add the post data to the web request
             postStream.Write(byteArray, 0, byteArray.Length);
             postStream.Close();

             WebResponse response = webRequest.GetResponse(); 
             postStream = response.GetResponseStream();
             StreamReader reader = new StreamReader(postStream);
             string responseFromServer = reader.ReadToEnd();

             GooglePlusAccessToken serStatus = JsonConvert.DeserializeObject<GooglePlusAccessToken>(responseFromServer);//JsonConvert.DeserializeObject<GooglePlusAccessToken>(responseFromServer);
             //GooglePlusAccessToken serStatus = new GooglePlusAccessToken();
             if (serStatus != null)
             {
                 string accessToken = string.Empty;
                 accessToken = serStatus.access_token;

                 if (!string.IsNullOrEmpty(accessToken))
                 {
                     using (var w = new WebClient())
                     {
                         json_data = w.DownloadString("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + accessToken);
                         serStatus1 = JsonConvert.DeserializeObject<GoogleUserOutputData>(json_data);
                     }
                 }
                 else
                 { }
             }
             else
             { }
         }
         return serStatus1;
     }
        private async Task <GoogleUserOutputData> GetGoogleUserInfo(string access_token)
        {
            string path     = "";
            bool   writeLog = false;

            if (System.Configuration.ConfigurationManager.AppSettings["DebugLogFile"] != null)
            {
                if (string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["DebugLogFile"].ToString()) == false)
                {
                    path     = System.Configuration.ConfigurationManager.AppSettings["DebugLogFile"].ToString();
                    writeLog = true;
                }
            }

            try
            {
                if (writeLog)
                {
                    System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " start in GetGoogleUserInfo..");
                }

                var       urlProfile = "https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=" + access_token;
                WebClient webClient  = new WebClient();
                string    response   = webClient.DownloadString(urlProfile);
                if (writeLog)
                {
                    System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " GetGoogleUserInfo.." + response);
                }
                if (!string.IsNullOrEmpty(response))
                {
                    GoogleUserOutputData userData = JsonConvert.DeserializeObject <GoogleUserOutputData>(response);
                    return(userData);
                }
                return(null);
            }
            catch (Exception ex)
            {
                if (writeLog)
                {
                    System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " Error in GetGoogleUserInfo.." + ex.ToString());
                }
                return(null);
            }
        }
Exemple #12
0
        /// <summary>
        /// Metodo que le permite a un usuario registrar sus datos personales la primera vez que ingresa al sistema
        /// </summary>
        /// <param name="accessToken">Token generado por el API de Google</param>
        /// <param name="nombre">nombre del usuario</param>
        /// <param name="apellido">apellido del usuario</param>
        /// <param name="fechaNacimiento">fecha de nacimiento del usuario</param>
        /// <param name="fotoPerfiL">foto de perfil del usuario</param>
        /// <param name="sexo">sexo del usuario</param>
        /// <param name="ciudad">ciudad de origen del usuario</param>
        /// <param name="pais">pais del usuario</param>
        /// <param name="rol">rol del nuevo usuario</param>
        /// <returns>True si se registro correctamente</returns>
        public bool registrarDatosUsuario(String accessToken, String nombre, String apellido, DateTime fechaNacimiento, Multimedia fotoPerfiL, TipoSexo sexo, String ciudad, String pais, TipoRol rol)
        {
            GoogleUserOutputData usuario = obtenerInformacionGoogle(accessToken);

            Usuario usuarioBuscado = buscarUsuario(usuario.id);

            if (usuarioBuscado != null)
            {
                throw new UsuarioException("El usuario ya existe");
            }

            Usuario nuevoUsuario = new Usuario(usuario.id, nombre, apellido, fechaNacimiento, fotoPerfiL, sexo, usuario.email, ciudad, pais, rol);

            IRepositorioUsuario repositorioUsuarios = FabricaRepositoriosUsuarios.CrearRepositorioUsuarios("json");

            repositorioUsuarios.guardarUsuario(nuevoUsuario);

            return(true);
        }
        //private void SaveRefreshToken(int userId, string refreshToken)
        //{
        //    SqlConnection Con = new SqlConnection(ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString);
        //    string Query = "insert into Member (UserId,RefreshToken) values(" + userId + ",'" + refreshToken + "')";
        //    SqlCommand Cmd = new SqlCommand(Query, Con);
        //    Con.Open();
        //    int Result = Cmd.ExecuteNonQuery();
        //    Con.Close();
        //}

        private GoogleUserOutputData FetchEmailId(string accessToken)
        {
            HttpClient client = new HttpClient();

            var urlProfile = "https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + accessToken;

            //var profile = "https://www.googleapis.com/auth/userinfo.profile?access_token=" + accessToken;
            client.CancelPendingRequests();
            GoogleUserOutputData obj    = new GoogleUserOutputData();
            HttpResponseMessage  output = client.GetAsync(urlProfile).Result;

            if (output.IsSuccessStatusCode)

            {
                string outputData = output.Content.ReadAsStringAsync().Result;

                obj = JsonConvert.DeserializeObject <GoogleUserOutputData>(outputData);
                obj.Access_token = accessToken;
                return(obj);
            }
            return(obj);
        }
Exemple #14
0
        private void getgoogleplususerdataSer(string access_token)
        {
            using (var client = new HttpClient())
            {
                var urlProfile = "https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=" + access_token;
                var response   = client.GetAsync(urlProfile).Result;

                if (response.IsSuccessStatusCode)
                {
                    // by calling .Result you are performing a synchronous call
                    var responseContent = response.Content;

                    // by calling .Result you are synchronously reading the result
                    string responseString          = responseContent.ReadAsStringAsync().Result;
                    GoogleUserOutputData serStatus = JsonConvert.DeserializeObject <GoogleUserOutputData>(responseString);
                    if (site_islem.BireyselKayitOlKontrol(serStatus.email))
                    {
                        FormsAuthentication.SetAuthCookie(serStatus.email, true);
                        Session["giris_yapan"] = serStatus.email;
                        if (Session["oturum_sonrasi_sayfa"] != null)
                        {
                            Response.Redirect(Session["oturum_sonrasi_sayfa"].ToString());
                        }
                        else
                        {
                            Response.RedirectToRoute("Home");
                        }
                        return;
                    }
                    string resimadi = "Eduadvisor-uye-" + DateTime.Now.ToString("ddMMyyyyHHmmssffff");
                    try
                    {
                        WebClient            wc        = new WebClient();
                        byte[]               bytes     = wc.DownloadData(serStatus.picture);
                        MemoryStream         ms        = new MemoryStream(bytes);
                        System.Drawing.Image img       = System.Drawing.Image.FromStream(ms);
                        string               extension = "";
                        if (ImageFormat.Jpeg.Equals(img.RawFormat))
                        {
                            extension = ".jpg";
                        }
                        else if (ImageFormat.Png.Equals(img.RawFormat))
                        {
                            extension = ".png";
                        }
                        resimadi += extension;
                        if (!extension.Equals(""))
                        {
                            img.Save("C:/Inetpub/vhosts/eduadvisor.co.uk/httpdocs/Content/img/kul_profil/" + resimadi);
                        }
                        else
                        {
                            resimadi = "profil.png";
                        }
                    }
                    catch (Exception)
                    {
                        resimadi = "profil.png";
                    }
                    string sonuc = site_islem.BireyselKayitOl(serStatus.given_name, serStatus.family_name, resimadi, serStatus.email, islem.randomSifreUret(), true, 1);
                    if (sonuc.Equals("1") || sonuc.Equals("-9"))
                    {
                        FormsAuthentication.SetAuthCookie(serStatus.email, true);
                        Session["giris_yapan"] = serStatus.email;
                    }
                }
            }
            if (Session["oturum_sonrasi_sayfa"] != null)
            {
                Response.Redirect(Session["oturum_sonrasi_sayfa"].ToString());
            }
            else
            {
                Response.RedirectToRoute("Home");
            }
        }
        // Lay ma truy cap
        public string CreateOauthTokenForGmail(string code, string GoogleWebAppClientID, string GoogleWebAppClientSecret, string RedirectUrl)
        {
            RequestParameters requestParameters = new RequestParameters()
            {
                code          = code,
                client_id     = WebConfigurationManager.AppSettings["GoogleWebAppClientID"],
                client_secret = WebConfigurationManager.AppSettings["GoogleWebAppClientSecret"],
                redirect_uri  = RedirectUrl,
                grant_type    = "authorization_code"
            };
            string inputJson      = JsonConvert.SerializeObject(requestParameters);
            string requestURI     = "token";
            string ResponseString = "";
            HttpResponseMessage respone;

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://oauth2.googleapis.com");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


                StringContent content = new StringContent(inputJson, Encoding.UTF8, "application/json");
                respone = client.PostAsync(requestURI, content).Result;

                if (respone.IsSuccessStatusCode)
                {
                    // chuyen doi chuoi tra ve
                    ResponseString = JsonConvert.DeserializeObject(respone.Content.ReadAsStringAsync().Result).ToString();
                    var result = JsonConvert.DeserializeObject <OAuthTokenViewModel>(ResponseString); // gan cho OAuthTokenViewModel
                    ResponseString = result.Access_token.ToString();                                  // access Token
                    // Lay thông tin user
                    try
                    {
                        //HttpClient client2 = new HttpClient();

                        var url = "https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=" + ResponseString;

                        HttpResponseMessage  output    = client.GetAsync(url).Result;
                        GoogleUserOutputData serStatus = new GoogleUserOutputData();

                        if (output.IsSuccessStatusCode)

                        {
                            string outputData = output.Content.ReadAsStringAsync().Result;

                            serStatus = JsonConvert.DeserializeObject <GoogleUserOutputData>(outputData);
                            name      = serStatus.email;
                        }
                        else
                        {
                            ViewBag.test = "no";
                        }
                    }

                    catch (Exception ex)
                    {
                    }
                }
                return(ResponseString);
            }
        }
        public async Task <HttpResponseMessage> RegisterExternal(RegisterExternalBindingModel model)
        {
            HttpResponseMessage response;
            string  name     = "";
            string  birthday = "";
            string  gender   = "";
            string  email    = "";
            string  picture  = "";
            dynamic myInfo   = "";
            var     token    = "";

            if (!ModelState.IsValid)
            {
                response = Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            var verifiedAccessToken = await VerifyExternalAccessToken(model.Provider, model.ExternalAccessToken);

            if (verifiedAccessToken == null)
            {
                response = Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid Provider or External Access Token");
            }
            EXTERNALACCOUNT user = db.EXTERNALACCOUNTs.FirstOrDefault
                                       (x => x.PROVIDERKEY == verifiedAccessToken.user_id & x.LOGINPROVIDER == model.Provider);
            bool   hasRegistered = user != null;
            object dbUser;

            if (hasRegistered)
            {
                ACCOUNT account1 = db.ACCOUNTs.FirstOrDefault(x => x.ID == user.IDUSER);
                token    = CreateTokenLogin(account1, out dbUser);
                response = Request.CreateResponse(new { dbUser, token });
                return(response);
            }
            if (model.Provider == "Facebook")
            {
                var fb = new FacebookClient(model.ExternalAccessToken);
                myInfo = fb.Get("/me?fields=name,id,gender,birthday,email,picture");
                if (myInfo["email"] != "")
                {
                    email = myInfo["email"];
                }
                if ((myInfo["name"] != ""))
                {
                    name = myInfo["name"];
                }
                try
                { picture = picture = String.Format("https://graph.facebook.com/{0}/picture?width=200&height=200", verifiedAccessToken.user_id); }
                catch (Exception ex)
                { }
            }

            if (model.Provider == "Google")
            {
                HttpClient client     = new HttpClient();
                var        urlProfile = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + model.ExternalAccessToken;
                client.CancelPendingRequests();
                HttpResponseMessage output = await client.GetAsync(urlProfile);

                if (output.IsSuccessStatusCode)
                {
                    string outputData = await output.Content.ReadAsStringAsync();

                    GoogleUserOutputData serStatus = JsonConvert.DeserializeObject <GoogleUserOutputData>(outputData);

                    if (serStatus != null)
                    {
                        if (!string.IsNullOrEmpty(serStatus.email))
                        {
                            email = serStatus.email;
                        }
                        if (!string.IsNullOrEmpty(serStatus.name))
                        {
                            name = serStatus.name;
                        }
                        if (!string.IsNullOrEmpty(serStatus.picture))
                        {
                            picture = serStatus.picture;
                        }
                    }
                }
            }

            EXTERNALACCOUNT external = new EXTERNALACCOUNT();
            ACCOUNT         usermain = new ACCOUNT();
            ACCOUNT         acc      = new ACCOUNT();

            acc = db.ACCOUNTs.FirstOrDefault(x => x.EMAIL == email);
            if (acc != null)
            {
                external.PROVIDERKEY   = verifiedAccessToken.user_id;
                external.IDUSER        = acc.ID;
                external.LOGINPROVIDER = model.Provider;
                db.EXTERNALACCOUNTs.Add(external);
                db.SaveChanges();
            }
            else
            {
                external.PROVIDERKEY   = verifiedAccessToken.user_id;
                external.IDUSER        = db.ACCOUNTs.Count() + 1;
                external.LOGINPROVIDER = model.Provider;
                if (!string.IsNullOrEmpty(email))
                {
                    usermain.EMAIL = email;
                }
                if (!string.IsNullOrEmpty(name))
                {
                    usermain.NAME = name;
                }
                usermain.ID = external.IDUSER;
                ACCOUNT_ROLE role = new ACCOUNT_ROLE();
                role.IDUSER = external.IDUSER;
                role.IDROLE = 2;
                if (!string.IsNullOrEmpty(picture))
                {
                    Account account = new Account("dqabuxewl", "198449299438919", "SRASj3YoFcfLsetrHFNNwGVF4qQ");
                    CloudinaryDotNet.Cloudinary cloudinary = new CloudinaryDotNet.Cloudinary(account);

                    var uploadParams = new ImageUploadParams()
                    {
                        File = new FileDescription(picture)
                    };

                    var uploadResult = cloudinary.Upload(uploadParams);
                    usermain.IMAGEACC = uploadResult.Uri.OriginalString;
                }
                else
                {
                    usermain.IMAGEACC = imgnormal;
                }
                DbContextTransaction dt = db.Database.BeginTransaction();
                try
                {
                    db.EXTERNALACCOUNTs.Add(external);
                    db.SaveChanges();
                    db.ACCOUNTs.Add(usermain);
                    db.SaveChanges();
                    db.ACCOUNT_ROLE.Add(role);
                    db.SaveChanges();
                    dt.Commit();
                }
                catch (Exception ex)
                {
                    dt.Rollback();
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Error"));
                }
            }

            //Create token
            usermain = new ACCOUNT();
            usermain = db.ACCOUNTs.FirstOrDefault(x => x.EMAIL == email);
            token    = CreateTokenLogin(usermain, out dbUser);
            response = Request.CreateResponse(new { dbUser, token });
            return(response);
        }
        public async Task <IHttpActionResult> RegisterExternal(ExternalUserBinding model)
        {
            string path     = "";
            bool   writeLog = false;

            if (System.Configuration.ConfigurationManager.AppSettings["DebugLogFile"] != null)
            {
                if (string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["DebugLogFile"].ToString()) == false)
                {
                    path     = System.Configuration.ConfigurationManager.AppSettings["DebugLogFile"].ToString();
                    writeLog = true;
                }
            }

            if (writeLog)
            {
                System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " called..RegisterExternal...");
            }

            if (ModelState.IsValid == false)
            {
                if (writeLog)
                {
                    System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " modelstate is invalid...");
                }
                return(BadRequest(ModelState));
            }

            if (model.Provider.ToLower() == "google")
            {
                ParsedExternalAccessToken googleVerifiedAccessToken = await VerifyGoogleExternalAccessToken(model.ExternalAccessToken);

                if (googleVerifiedAccessToken == null)
                {
                    if (writeLog)
                    {
                        System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " google provider or external access token is not valid...");
                    }
                    return(BadRequest("Invalid Provider or External Access Token"));
                }
            }

            var    providerId = string.Empty;
            string email      = string.Empty;
            string firstName  = string.Empty;
            string lastName   = string.Empty;

            if (model.Provider.ToLower() == "facebook")
            {
                if (writeLog)
                {
                    System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " provider is facebook checking to get client info...");
                }
                FacebookClient facebookClient   = new FacebookClient(model.ExternalAccessToken);
                dynamic        facebookUserInfo = facebookClient.Get("/me?fields=email,first_name,last_name,id");

                if (String.IsNullOrEmpty(facebookUserInfo.email) == true)
                {
                    if (writeLog)
                    {
                        System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " email is not configured in fb so not proceed...");
                    }
                    return(BadRequest("The user has not configured an email address in Facebook."));
                }
                providerId = facebookUserInfo.id;
                email      = facebookUserInfo.email;
                firstName  = String.IsNullOrEmpty(facebookUserInfo.first_name) ? null : facebookUserInfo.first_name;
                lastName   = String.IsNullOrEmpty(facebookUserInfo.last_name) ? null : facebookUserInfo.last_name;
            }

            if (model.Provider.ToLower() == "google")
            {
                GoogleUserOutputData userData = await GetGoogleUserInfo(model.ExternalAccessToken);

                if (userData != null)
                {
                    providerId = userData.id;
                    email      = userData.email;
                    firstName  = userData.given_name;
                    lastName   = userData.family_name;
                }
            }

            if (model.Provider.ToLower() == "linkedin")
            {
                LinkedProfile profileInfo = await GetProfileInfo(model.ExternalAccessToken, path, writeLog);

                if (profileInfo != null)
                {
                    providerId = profileInfo.id;
                    firstName  = profileInfo.firstName;
                    lastName   = profileInfo.lastName;
                    email      = model.UserName;
                }
            }

            if (writeLog)
            {
                System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " provider id is.." + providerId + " - " + model.Provider);
            }

            User user = await this._authenticationRepository.FindAsync(new UserLoginInfo(model.Provider, providerId));

            bool    hasRegistered       = user != null;
            JObject accessTokenResponse = null;

            if (hasRegistered == true)
            {
                if (writeLog)
                {
                    System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " has registered already...generate local access token...");
                }
                accessTokenResponse = this.GenerateLocalAccessTokenResponse(user);
                return(Ok(accessTokenResponse));
            }

            IdentityResult    result;
            ExternalLoginInfo externalLoginInfo = new ExternalLoginInfo()
            {
                DefaultUserName = email,
                Login           = new UserLoginInfo(model.Provider, providerId)
            };

            if (writeLog)
            {
                System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " find by email... " + email + " - " + model.Provider);
            }

            user = this._authenticationRepository.FindUserByUserName(email);

            bool hasRegisteredLocally = user != null;

            if (hasRegisteredLocally == true)
            {
                if (writeLog)
                {
                    System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " registered locaslly so... adding login ..." + email + "-" + model.Provider);
                }
                if (model.Provider.ToLower() == "linkedin")
                {
                    if (writeLog)
                    {
                        System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " email already exist error..." + email + "-" + model.Provider);
                    }
                    return(BadRequest("User already exist with given email address."));
                }

                result = await this._authenticationRepository.AddLoginAsync(user.Id, externalLoginInfo.Login);

                if (!result.Succeeded)
                {
                    return(this.GetErrorResult(result));
                }
                if (writeLog)
                {
                    System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " adding login222222 success 3333 so generating access token LOCAL....." + email);
                }

                accessTokenResponse = this.GenerateLocalAccessTokenResponse(user);

                return(Ok(accessTokenResponse));
            }


            RegisterExternalUserDTO registerExternalUserDTO = new RegisterExternalUserDTO()
            {
                Email     = email,
                FirstName = firstName,
                LastName  = lastName
            };

            if (writeLog)
            {
                System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " registered new external user..." + email);
            }

            result = await this._authenticationRepository.RegisterNewExternalUser(registerExternalUserDTO);

            if (!result.Succeeded)
            {
                return(this.GetErrorResult(result));
            }

            if (writeLog)
            {
                System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " registered success so getting user again...by FindUserByUserName-" + email);
            }

            user = this._authenticationRepository.FindUserByUserName(email);

            result = await this._authenticationRepository.AddLoginAsync(user.Id, externalLoginInfo.Login);

            if (!result.Succeeded)
            {
                return(this.GetErrorResult(result));
            }
            if (writeLog)
            {
                System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " generating..local access token user..." + email);
            }
            //generate access token response
            accessTokenResponse = this.GenerateLocalAccessTokenResponse(email);

            /*
             * string apiKey = SENDGRID_API_KEY;
             * SendGridClient sendGridClient = new SendGridClient(apiKey, "https://api.sendgrid.com");
             * EmailAddress emailSender = new EmailAddress("*****@*****.**", "Carlito");
             * String subject = "Welcome to Carlito.";
             * EmailAddress emailRecipient = new EmailAddress(user.Email);
             * Content content = new Content("text/html", "Hello world!");
             * SendGridMessage mail = MailHelper.CreateSingleEmail(emailSender, emailRecipient, subject, "", "");
             *
             * mail.TemplateId = "e69e88c0-facf-4512-9e23-d1214e4765a3";
             *
             * dynamic response = sendGridClient.SendEmailAsync(mail);
             */
            return(Ok(accessTokenResponse));
        }
Exemple #18
0
        public async Task <TokenDto> CreateOauthTokenForGmailAsync(string code)
        {
            string GoogleWebAppClientID     = WebConfigurationManager.AppSettings["GoogleWebAppClientID"];
            string GoogleWebAppClientSecret = WebConfigurationManager.AppSettings["GoogleWebAppClientSecret"];
            string RedirectUrl = WebConfigurationManager.AppSettings["GoogleRedirectUrl"];
            // AccessToken:
            RequestParameters requestParameters = new RequestParameters()
            {
                scope         = "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email",
                code          = code,
                client_id     = GoogleWebAppClientID,
                client_secret = GoogleWebAppClientSecret,
                redirect_uri  = RedirectUrl,
                grant_type    = "authorization_code"
            };
            string inputJson      = JsonConvert.SerializeObject(requestParameters);
            string requestURI     = "token";
            string ResponseString = "";
            HttpResponseMessage respone;
            var token = new TokenDto();

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://oauth2.googleapis.com");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


                StringContent content = new StringContent(inputJson, Encoding.UTF8, "application/json");
                respone = client.PostAsync(requestURI, content).Result;

                if (respone.IsSuccessStatusCode)
                {
                    // chuyen doi chuoi tra ve
                    ResponseString = JsonConvert.DeserializeObject(respone.Content.ReadAsStringAsync().Result).ToString();
                    var result = JsonConvert.DeserializeObject <OAuthTokenViewModel>(ResponseString); // gan cho OAuthTokenViewModel
                    //ResponseString = result.Access_token.ToString(); // access Token
                    token.access_token = result.Access_token.ToString();
                    //token.refresh_token = result.Refresh_token;
                    token.type = 1;
                    try
                    {
                        var url = "https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=" + token.access_token;
                        HttpResponseMessage  output    = client.GetAsync(url).Result;
                        GoogleUserOutputData serStatus = new GoogleUserOutputData();

                        if (output.IsSuccessStatusCode)

                        {
                            string outputData = output.Content.ReadAsStringAsync().Result;

                            serStatus   = JsonConvert.DeserializeObject <GoogleUserOutputData>(outputData);
                            token.gmail = serStatus.email;
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }
                return(token);
            }
        }
        public ActionResult Login()
        {
            var url     = Request.Url.Query;
            int id_user = 0;
            int id_rol  = 0;

            List <AliasUsuario>   aliasDB      = new List <AliasUsuario>();
            List <Usuario>        userDB       = new List <Usuario>();
            List <UsuarioRol>     userRol      = new List <UsuarioRol>();
            List <TransaccionRol> tranRol      = new List <TransaccionRol>();
            List <int>            permisosMenu = new List <int>();
            List <String>         premiosFe    = new List <String>();

            if (url != "")
            {
                userLogin = googleParameters.ObtenerCorreo(true, url);

                if (userLogin.email != null)
                {
                    querys = "SELECT *"
                             + "FROM Usuario "
                             + "WHERE us_correoElectronico=@email "
                             + "AND us_estado = 'V'";

                    userDB = db.Usuarios.SqlQuery(querys, new SqlParameter("@email", userLogin.email)).ToList();

                    if (userDB.Count == 1)
                    {
                        id_user = userDB.ElementAt(0).us_id;

                        querys = "SELECT *"
                                 + "FROM UsuarioRol "
                                 + "WHERE ur_idUsuario=@id " +
                                 "AND ur_estado = 'V'";

                        userRol = db.UsuarioRol.SqlQuery(querys, new SqlParameter("@id", id_user)).ToList();

                        if (userRol.Count == 0)
                        {
                            return(Redirect(urlLogout));
                        }
                        else
                        {
                            id_rol = userRol.ElementAt(0).ur_idRol;

                            DatosLogin.email    = userLogin.email;
                            DatosLogin.picture  = userLogin.picture;
                            DatosLogin.id_login = id_user;
                            DatosLogin.login    = true;
                            DatosLogin.id_menu  = 1;
                            DatosLogin.id_rol   = id_rol;
                            DatosLogin.nombre   = userDB.ElementAt(0).us_primerNombre;


                            if (id_user > 0)
                            {
                                Session["UserInfo"] = DatosLogin;

                                querys = "select * "
                                         + "from TransaccionRol "
                                         + "where tr_id_rol = @idrol";

                                tranRol = db.TransaccionRol.SqlQuery(querys, new SqlParameter("idrol", id_rol)).ToList();

                                foreach (TransaccionRol trn in tranRol)
                                {
                                    permisosMenu.Add(trn.tr_id_transaccion);
                                }

                                DatosLogin.permisos = permisosMenu;

                                querys = "select convert(varchar(20), convert(decimal(6,2), (count(1) * 50) * 0.5))  primerLugar, convert(varchar(20), convert(decimal(6,2),(count(1) * 50) * 0.3))  segundoLugar, convert(varchar(20), convert(decimal(6,2), (count(1) * 50) * 0.2)) tercerLugar "
                                         + "from AliasUsuario, Usuario "
                                         + "where al_estado = 'V' "
                                         + "and al_idUsuario = us_id "
                                         + "and us_estado = 'V' ";

                                List <Premios> premios = db.Database.SqlQuery <Premios>(querys).ToList <Premios>();

                                foreach (Premios prem in premios)
                                {
                                    premiosFe.Add(prem.primerLugar);
                                    premiosFe.Add(prem.segundoLugar);
                                    premiosFe.Add(prem.tercerLugar);
                                }

                                DatosLogin.premios = premiosFe;

                                querys = "SELECT *"
                                         + "FROM AliasUsuario "
                                         + "WHERE al_idUsuario=@iduser "
                                         + "AND  al_codigoDeposito is not null "
                                         + "AND al_estado = 'V'";

                                aliasDB = db.AliasUsuario.SqlQuery(querys, new SqlParameter("@iduser", id_user)).ToList();

                                if (aliasDB.Count == 1)
                                {
                                    AliasUsuario alias = aliasDB.First();
                                    ViewBag.DatosLogin = DatosLogin;
                                    return(Redirect("/Quiniela/Posiciones/" + alias.al_id.ToString()));
                                }
                                else
                                {
                                    if (aliasDB.Count == 0)
                                    {
                                        return(Redirect(urlLogout));
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        return(Redirect(urlLogout));
                    }

                    ViewBag.DatosLogin = DatosLogin;

                    return(View(aliasDB));
                }
                else
                {
                    return(Redirect(urlLogout));
                }
            }
            else
            {
                return(Redirect(urlLogout));
            }
        }