Пример #1
0
        public ActionResult FacebookLoginResult()
        {
            string code = Request["code"];

            Facebook.FacebookClient fb = new Facebook.FacebookClient();
            fb.AppId     = "958753294515704";
            fb.AppSecret = "a77614a903afbf8f773c0f06295f08c8";

            fb.AccessToken = code;

            dynamic result = fb.Post("/oauth/access_token", new
            {
                client_id     = "958753294515704",
                client_secret = "a77614a903afbf8f773c0f06295f08c8",
                code          = code,
                redirect_uri  = "http://localhost:50903/Account/FacebookLoginResult"
            });

            fb.AccessToken = result.access_token;
            dynamic userdata = fb.Get("me");

            string name = userdata.name;

            string[] fullname = name.Split(' ');
            userdata.firstname = fullname[0];
            userdata.lastname  = fullname[1];
            bool serviceresult = _socialUserService.SocialUserOperation((int)Common.SystemConstants.SystemConstannts.SOCIAL_TYPE.FACEBOOK, userdata.id, userdata.email, userdata.name, userdata.firstname, userdata.lastname, null);

            if (serviceresult)
            {
                return(RedirectToAction("Index", "Home", new { }));
            }

            return(null);
        }
Пример #2
0
        public ActionResult FacebookCallback(string code)
        {
            var     fb     = new FacebookClient();
            dynamic result = fb.Post("oauth/access_token", new
            {
                client_id     = "520025764710565",
                client_secret = "0d7ea70fb467f9f5a5c9444b63f2f8a6",
                redirect_uri  = RedirectUri.AbsoluteUri,
                code          = code
            });
            var accessToken = result.access_token;

            // Store the access token in the session
            Session["AccessToken"] = accessToken;

            // update the facebook client with the access token so
            // we can make requests on behalf of the user
            fb.AccessToken = accessToken;

            // Get the user's information
            dynamic me    = fb.Get("me/home?type=newsfeed");
            string  email = me.email;

            // Set the auth cookie
            FormsAuthentication.SetAuthCookie(email, false);

            return(RedirectToAction("Index", "Home"));
        }
Пример #3
0
        public ActionResult FacebookCallBack(string code)
        {
            var     fb     = new Facebook.FacebookClient();
            dynamic result = fb.Post("oauth/access_token", new {
                client_id     = ConfigurationManager.AppSettings["FBAppId"],
                client_secret = ConfigurationManager.AppSettings["FBSecret"],
                redirect_uri  = RedirectUri.AbsoluteUri,
                code          = code,
            });

            var accessToken = result.access_token;

            if (!string.IsNullOrEmpty(accessToken))
            {
                fb.AccessToken = accessToken;
                dynamic      me    = fb.Get("me?fields=id,first_name,last_name,email");
                UserFacebook users = new UserFacebook();
                users.user_id      = me.id;
                users.access_token = accessToken;
                users.email        = me.email;
                users.first_name   = me.first_name;
                users.last_name    = me.last_name;

                Session.Add("infoUser", users);
            }
            else
            {
            }

            return(Redirect("/Login/Page"));
        }
Пример #4
0
        public ActionResult FacebookCallback(string code)
        {
            var fb = new FacebookClient();
            dynamic result = fb.Post("oauth/access_token", new
            {
                client_id = "520025764710565",
                client_secret = "0d7ea70fb467f9f5a5c9444b63f2f8a6",
                redirect_uri = RedirectUri.AbsoluteUri,
                code = code
            });
            var accessToken = result.access_token;

            // Store the access token in the session
            Session["AccessToken"] = accessToken;

            // update the facebook client with the access token so
            // we can make requests on behalf of the user
            fb.AccessToken = accessToken;

            // Get the user's information
            dynamic me = fb.Get("me/home?type=newsfeed");
            string email = me.email;

            // Set the auth cookie
            FormsAuthentication.SetAuthCookie(email, false);

            return RedirectToAction("Index", "Home");
        }
Пример #5
0
        public ActionResult FacebookCallBack(string code)
        {
            var     fb     = new Facebook.FacebookClient();
            dynamic result = fb.Post("oauth/access_token", new {
                client_id     = ConfigurationManager.AppSettings["FBAppId"],
                client_secret = ConfigurationManager.AppSettings["FBSecret"],
                redirect_uri  = RedirectUri.AbsoluteUri,
                code          = code,
            });

            var accessToken = result.access_token;

            if (!string.IsNullOrEmpty(accessToken))
            {
                fb.AccessToken = accessToken;
                dynamic       me      = fb.Get("me?fields=id,first_name,last_name,email,picture");
                dynamic       dataPic = me.picture;
                dynamic       datasss = dataPic.data;
                UserLoginInfo users   = new UserLoginInfo();
                users.user_id      = me.id;
                users.access_token = accessToken;
                users.email        = me.email;
                users.first_name   = me.first_name;
                users.last_name    = me.last_name;
                users.url_image    = datasss.url;
                Session[CommonConstants.USER_LOGIN] = users;
            }
            else
            {
            }

            return(Redirect("/Login/Page"));
        }
Пример #6
0
        public ActionResult Reactions(ReactionModel model)
        {
            var fb = new Facebook.FacebookClient();

            fb.AccessToken = model.Token;
            fb.Post()
            return(View());
        }
 private static string PostFacebookWall(string accessToken, string message)
 {
     var responsePost = "";
     try
     {
         //create the facebook account object
         var objFacebookClient = new Facebook.FacebookClient(accessToken);
         var parameters = new Dictionary<string, object>();
         parameters["message"] = message;
         responsePost = objFacebookClient.Post("feed", parameters).ToString();
     }
     catch (Exception ex)
     {
         responsePost = "Facebook Posting Error Message: " + ex.Message;
     }
     return responsePost;
 }
Пример #8
0
        //Lấy thông tin fb gửi về //chưa fix thông tin credential
        public ActionResult FacebookCallback(string code)
        {
            var     fb     = new Facebook.FacebookClient();
            dynamic result = fb.Post("oauth/access_token", new
            {
                client_id     = System.Configuration.ConfigurationManager.AppSettings["FbAppId"],
                client_secret = System.Configuration.ConfigurationManager.AppSettings["FbAppSecret"],
                redirect_uri  = RedirectUri.AbsoluteUri,
                code          = code,
            });
            var accessToken = result.access_token;

            if (!string.IsNullOrEmpty(accessToken))
            {
                fb.AccessToken = accessToken;
                //Lấy thông tin được gửi về
                dynamic me         = fb.Get("me?fields=first_name,middle_name,last_name,id,email");
                string  email      = me.email;
                string  userName   = me.email;
                string  firstname  = me.first_name;
                string  middlename = me.middle_name;
                string  lastname   = me.last_name;
                //Tạo mới 1 User và gán thông tin vào user
                var user = new User();
                user.Email       = email;
                user.UserName    = userName;
                user.Status      = true;
                user.Name        = firstname + " " + middlename + " " + lastname;
                user.CreatedDate = DateTime.Now;
                var id = new UserDao().InsertForFacebook(user);
                //Ghi vào database
                if (id > 0)
                {
                    var userSession = new UserLogin();
                    userSession.UserName = user.UserName;
                    userSession.UserID   = user.ID;

                    Session.Add(CommonConstants.USER_SESSION, userSession);
                    //Session[CommonConstants.isAuthorized] = true;
                }
            }
            return(Redirect("/"));
        }
Пример #9
0
        private void ProcessScanner()
        {
            INSPECTPROCESS latestProcess = default(INSPECTPROCESS);

            while (true)
            {
                if (GoingOn)
                {
                    var            dataset        = fileReader($@"{Path.Combine(Path.GetTempPath(), Properties.Settings.Default.SettngsFilePath)}"); //reloading the settings file
                    INSPECTPROCESS currentProcess = default(INSPECTPROCESS);
                    var            shouldShowing  = false;
                    foreach (var proc in Process.GetProcesses())
                    {
                        currentProcess = dataset.Find(process => process.real_process == $"{proc.ProcessName}.exe");
                        if (dataset.Contains(currentProcess))
                        {
                            shouldShowing = true;
                            if (!latestProcess.Equals(currentProcess))
                            {
                                DeletePreviousPost();
                                dynamic param = new ExpandoObject();
                                param.message = $"Currently playing {currentProcess.process_name} on {Environment.MachineName}, started from {DateTime.Now.ToString("hh:mm tt")}!";
                                facebookClient.Post("me/feed", param);
                                //facebookService.PostOnWallAsync(accessToken, $"Currently playing {currentProcess.process_name} on {Environment.MachineName}, started from {DateTime.Now.ToString("hh:mm tt")}!");
                                latestProcess = currentProcess;
                            }
                            break;
                        }
                    }
                    fuckTheseObject(label1, Color.Green, $"Currently on {currentProcess.process_name ?? "Desktop"}");
                    ProcessFlag = currentProcess.real_process;
                    ControlInvokeRequired(button3, () => button3.Visible = shouldShowing);
                }
                else
                {
                    fuckTheseObject(label1, Color.Red, "inspecthelper is not running");
                }
                Thread.Sleep(1000);
            }
        }
Пример #10
0
        public LoginResponse FacebookLogin(FacebookRequest facebookRequest)
        {
            LoginResponse loginResponse = new LoginResponse();

            try
            {
                Facebook.FacebookClient fb = new Facebook.FacebookClient();
                dynamic result             = fb.Post("oauth/access_token", new
                {
                    client_id     = facebookRequest.AppID,
                    client_secret = facebookRequest.AppSecret,
                    redirect_uri  = facebookRequest.FacebookUri,
                    //Test ederken kendi mvc projenin localhost kısmını yaz.
                    code = facebookRequest.FacebookCode
                });

                var accessToken = result.access_token;
                fb.AccessToken = accessToken;
                dynamic userinfo = fb.Get("me?fields=first_name,middle_name,last_name,id,email");

                string email     = userinfo.email,
                       firstName = userinfo.first_name,
                       lastName  = userinfo.last_name,
                       socialId  = userinfo.id;

                User user = _userRepository.Get(t => t.Email == email).FirstOrDefault();

                if (user != null)
                {
                    try
                    {
                        Token token = CreateToken();
                        user.Tokens.Add(token);

                        if (_unitOfWork.SaveChanges() > 0)
                        {
                            _cacheManager.AddUserToCache(token.TokenText, user);

                            loginResponse.Username   = user.FullName();
                            loginResponse.Token      = token.TokenText;
                            loginResponse.ExpireDate = token.EndDate;
                            loginResponse.IsVerify   = true;
                            loginResponse.Email      = user.Email;
                            loginResponse.SetStatus(Constants.ResponseCode.SUCCESS);
                            return(loginResponse);
                        }
                    }
                    catch (Exception)
                    {
                        loginResponse.SetStatus(Constants.ResponseCode.SYSTEM_ERROR);
                        return(loginResponse);
                    }
                    return(loginResponse);
                }
                user            = new User();//newlemezsek patlıyor.
                user.Email      = email;
                user.Name       = firstName;
                user.Surname    = lastName;
                user.Password   = firstName;
                user.Username   = firstName + lastName;
                user.IsVerified = true;

                user.SocialInfos.Add(new SocialInfo
                {
                    SocialID     = socialId,
                    AccessToken  = accessToken,
                    SocialTypeID = (int)Constants.SocialType.Facebook
                });

                if (UserRegistry(user).Code == 0) // Başarılı register
                {
                    Token token = CreateToken();
                    user.Tokens.Add(token);
                    if (_unitOfWork.SaveChanges() > 0)
                    {
                        _cacheManager.AddUserToCache(token.TokenText, user);
                        loginResponse.Username = user.FullName();
                        loginResponse.Token    = token.TokenText;
                        loginResponse.IsVerify = true;
                        loginResponse.SetStatus(Constants.ResponseCode.SUCCESS);
                        return(loginResponse);
                    }
                }
                loginResponse.SetStatus(Constants.ResponseCode.SYSTEM_ERROR);
            }
            catch (Exception ex)
            {
                loginResponse.SetStatus(Constants.ResponseCode.SYSTEM_ERROR);
            }
            return(loginResponse);
        }
Пример #11
0
        /// <summary>
        /// Facebook the callback.
        /// </summary>
        /// <param name="code">The code.</param>
        /// <returns>Facebook Call back</returns>
        public ActionResult FacebookCallback(string code)
        {
            var     fb     = new Facebook.FacebookClient();
            dynamic result = fb.Post("oauth/access_token", new { client_id = Util.GetConfigValue("AppFaceBookID", string.Empty), client_secret = Util.GetConfigValue("AppFacebookSecret", string.Empty), redirect_uri = this.RedirectUri.AbsoluteUri, code = code });

            var accessToken = result.access_token;

            //// Store the access token in the session for farther use
            this.Session["AccessToken"] = accessToken;

            //// update the facebook client with the access token so
            //// we can make requests on behalf of the user
            fb.AccessToken = accessToken;

            //// Get the user's information
            dynamic me         = fb.Get("me?fields=first_name,middle_name,last_name,id,email");
            string  email      = me.email;
            string  firstname  = me.first_name;
            string  middlename = me.middle_name;
            string  lastname   = me.last_name;
            string  ids        = me.id;

            //// Set the auth cookie
            ////FormsAuthentication.SetAuthCookie(email, false);

            UserModels sv  = new UserModels();
            C_User     it  = new C_User();
            C_UserInfo iit = new C_UserInfo();

            it = sv.GetUserbyUserName(email);
            if (it == null)
            {
                it = new C_User();
                string rt     = string.Empty;
                bool   infors = false;
                it.Username  = email;
                it.Role      = 2;
                it.Password  = MD5Extend.EncodePassword("123456");
                it.Online    = true;
                it.IP        = HttpContext.Request.ServerVariables["REMOTE_ADDR"].ToString();
                it.LastLogin = DateTime.Now;
                rt           = sv.Add_User(it);

                iit.FName        = firstname;
                iit.Email        = email;
                iit.LName        = middlename;
                iit.DateRegister = DateTime.Now;
                iit.EventId      = string.IsNullOrEmpty(ids) != false?int.Parse(ids) : 0;

                iit.Note = "Facebook login";
                infors   = sv.Add_User_Infor(iit);

                if (rt.Length > 0 && infors == true)
                {
                    ////register_view.message = Lang.strMessageLogin;
                    this.Session["acc"]  = iit.FName;
                    this.Session["mem"]  = rt;
                    this.Session["role"] = it.Role.ToString();
                    this.SetAccountCookies(iit.FName, rt, it.Role.ToString(), 6);
                }
            }
            else
            {
                iit = sv.GetUserInforByEmail(email);
                this.Session["acc"]  = iit.FName;
                this.Session["mem"]  = it.Username;
                this.Session["role"] = it.Role.ToString();
                this.SetAccountCookies(iit.FName, it.Username, it.Role.ToString(), 6);
                it.Online    = true;
                it.IP        = HttpContext.Request.ServerVariables["REMOTE_ADDR"].ToString();
                it.LastLogin = DateTime.Now;
                sv.Update_User(it);
            }

            if (this.Session["FaceBook_return"] != null && Url.IsLocalUrl(this.Session["FaceBook_return"].ToString()))
            {
                return(this.Redirect(Session["FaceBook_return"].ToString()));
            }
            else
            {
                return(this.RedirectToAction("index", "home"));
            }
        }
Пример #12
0
        public async Task <HttpResponseMessage> Token(string code)
        {
            string domainWeb = "https://chanh.win/";

            try
            {
                var     fb     = new Facebook.FacebookClient();
                dynamic result = fb.Post("oauth/access_token", new
                {
                    client_id     = "1792549730783013",
                    client_secret = "5fd8d1fe75779972717e0881fc121882",
                    redirect_uri  = "https://api.buscity.xyz/Account/Token",
                    code          = code
                });

                var accessToken = result.access_token;

                List <IDs_Business> fb1 = await Utilities.FB.Facebook.GetIDsForBusiness(accessToken);

                if (fb1 == null)
                {
                    throw new Exception();
                }

                string accountIds = fb1.Select(x => x.id).Aggregate((i, j) => i + ";" + j);
                long   accountId  = AccountDAO.CheckBussinessAccount(accountIds);//request the minium user_id
                var    account    = new Models.Account();
                if (accountId > 0)
                {
                    account = AccountDAO.GetAccountInfo(accountId);
                }
                if (account == null || account.AccountID == 0)
                {
                    account = new Models.Account();
                }
                else
                {
                    if (account.IsBlocked)
                    {
                        throw new Exception();
                    }

                    LogDAO.Login(0, IPAddressHelper.GetClientIP(), account.AccountID, 2);
                    SetAuthCookie(account.AccountID, account.DisplayName, 0, 2);
                }
                int response1 = account.RegisterFacebookAccount($"FB_{fb1.FirstOrDefault().id}");
                if (response1 < 0)
                {
                    throw new Exception();
                }
                AccountDAO.CheckBussinessAccount(accountIds);
                LogDAO.Login(0, IPAddressHelper.GetClientIP(), account.AccountID, 2, true);
                SetAuthCookie(account.AccountID, "U." + account.AccountID, 0, 2);
            }
            catch (Exception ex)
            {
                NLogManager.PublishException(ex);
            }

            var response = Request.CreateResponse(HttpStatusCode.Moved);

            response.Headers.Location = new Uri(domainWeb);
            return(response);
        }
Пример #13
0
        public ActionResult Success(string transaction_type, string trans_id, string amount)
        {
            dynamic trans_info = Helper.Data.Get("transactions", Query.EQ("_id", trans_id));
            if (trans_info.status != "CASHIN")
            {
                ViewBag.Result = "đã được xử lý. Vui lòng liên hệ với chúng tôi để được hỗ trợ";
                return View("Result");
            }
            string confirmBankNet = ConfirmOrder(trans_info.trans_id, trans_info.partner_trans_id);
            trans_info.status = "PROCESSING";
            Helper.Data.Save("transactions", trans_info);

            var fb = new Facebook.FacebookClient(Session["access_token"].ToString());
            foreach (dynamic receiver in trans_info.receiver)
            {
                dynamic result = fb.Post("me/feed", new
                {
                    message = trans_info.message + ". Click để nhận tiền",
                    link = "http://moneynow.me/receiver/" + trans_info._id,
                    caption = "Gửi tới bạn "                     + trans_info.per_amount.ToString("N0"),
                    tags = receiver.id,
                    privacy= new {value="SELF"}
                });
            }
            //"/me/feed",
            //            "POST",
            //            {
            //    "message": message + '. Click để nhận tiền',
            //                "link": 'http://moneynow.me/receive/' + code,
            //                "caption": userFullName + ' gửi tới bạn ' + amount + 'đ',
            //                "tags": selectedFriends,
            //                "privacy": { 'value': 'SELF' }
            //},
            //var newPostId = result.id;
            //client.Get("/me")
            ViewBag.Result = "thành công";
            return View("Result");
        }
Пример #14
0
        public ActionResult FacebookCallbackLogin(string code)
        {
            try
            {
                var fb = new Facebook.FacebookClient();
                dynamic result = fb.Post("oauth/access_token", new
                {
                    client_id = Config.FacebookClientId,
                    client_secret = Config.FacebookClientSecret,
                    redirect_uri = RedirectUri.AbsoluteUri,
                    code = code
                });

                var accessToken = result.access_token;

                // Store the access token in the session
                Session["AccessToken"] = accessToken;

                // update the facebook client with the access token so
                // we can make requests on behalf of the user
                fb.AccessToken = accessToken;

                // Get the user's information
                dynamic me = fb.Get("me?fields=first_name,last_name,id,email,gender,username,birthday");

                MemberResponseModel model = MemberRepository.GetSingleByFacebookId(me.id);

                if (model.Code == "-1" && model.Message.Contains("No member"))
                {
                    MemberEditResponseModel data = MemberRepository.CreateMemberSimple(me.first_name, me.last_name, me.username, me.birthday, me.email, me.id, Contrib.CommonLib.MD5Hasher(me.first_name), me.gender == "male");

                    //Create member error
                    if (data.Code == "-1")
                    {
                        var returnModel = new RegisterModel()
                        {
                            Email = me.email,
                            FirstName = me.first_name,
                            Gender = me.gender == "male",
                            LastName = me.last_name,
                            Birthday = Convert.ToDateTime(me.birthday)
                        };
                        return View(@"~/Views/Account/SignUp.cshtml", returnModel);
                    }

                    //Create member success and then get avatar from facebook
                    if (data.Code == "1")
                    {
                        //Get avatar from facebook api
                        byte[] dataImg;
                        using (var client = new WebClient()){
                            dataImg = client.DownloadData(string.Format(Config.FacebookGraphImage,me.username));
                        }
                        var member = MemberRepository.ChangeAvatar(data.Message, "img.jpg", Convert.ToBase64String(dataImg), null);
                    }

                    model = MemberRepository.GetSingleByFacebookId(me.id);

                }

                SessionManager.IsLoggedIn = true;
                SessionManager.UserLogged = new UserProfile
                {
                    FacebookId = model.Member.MemberFacebookId,
                    FirstName = model.Member.MemberFirstName,
                    LastName = model.Member.MemberLastName,
                    UserName = model.Member.MemberUserName,
                    UserId = model.Member.MemberId,
                    Avatar = model.Member.MemberAvatar,
                    AvatarMedium = model.Member.MemberAvatarMedium,
                    Gender = model.Member.MemberGender
                };

                return RedirectToAction("Index", "Home");
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return RedirectToAction("Index", "Home");
            }
        }
Пример #15
0
        public static ResponseData PublishArticle(FBInstantArticleModel articleInfo, string style, bool developmentMode = false)
        {
            ResponseData responseData = new ResponseData();

            if (articleInfo == null || articleInfo.Id <= 0)
            {
                responseData.Message = "Can not found this news";
                return(responseData);
            }

            if (string.IsNullOrEmpty(articleInfo.Avatar))
            {
                responseData.Message = "This news has not avatar";
                return(responseData);
            }

            try
            {
                if (string.IsNullOrEmpty(style))
                {
                    style = FbInstantArticleStyle;
                }

                var fbClient = new Facebook.FacebookClient(FbToken);
                fbClient.AppId     = FbAppId;
                fbClient.AppSecret = FbAppSecret;

                Dictionary <string, object> fbParams = new Dictionary <string, object>();

                string newsContent = GenerateHtmlSource(articleInfo, style);

                responseData.Content = newsContent;

                if (!string.IsNullOrEmpty(responseData.Content))
                {
                    fbParams["access_token"]     = FbToken;
                    fbParams["html_source"]      = responseData.Content;
                    fbParams["published"]        = FbPublished;
                    fbParams["development_mode"] = developmentMode;


                    var articleId = fbClient.Post(string.Format("/{0}/{1}/instant_articles", FbAPIVersion, FbPageId), fbParams);

                    if (articleId != null)
                    {
                        responseData.Data    = articleId;
                        responseData.Success = true;
                        responseData.Message = "Update thành công: articleId = " + articleId;
                    }
                }
                else
                {
                    responseData.Message = "News content not allow null";
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLog(Logger.LogType.Error, ex.ToString());
                responseData.Message = ex.ToString();
            }

            return(responseData);
        }
Пример #16
0
        public ActionResult FacebookCallback(string code)
        {
            var     fb          = new Facebook.FacebookClient();
            dynamic accessToken = "";

            try
            {
                dynamic result = fb.Post("oauth/access_token", new
                {
                    client_id     = ConfigurationManager.AppSettings["AppId"],
                    client_secret = ConfigurationManager.AppSettings["AppSecret"],
                    redirect_uri  = RedirectUri.AbsoluteUri.Replace("http", "https"),
                    code          = code
                });
                accessToken = result.access_token;
            }
            catch (Exception) { }

            // Store the access token in the session for farther use
            Session["AccessToken"] = accessToken;

            // update the facebook client with the access token so
            // we can make requests on behalf of the user
            fb.AccessToken = accessToken;

            // Get the user's information
            dynamic me         = fb.Get("me?fields=first_name,middle_name,last_name,id,email");
            string  email      = me.email;
            string  firstname  = me.first_name;
            string  middlename = me.middle_name;
            string  lastname   = me.last_name;

            SocialLogin socialLogin = new SocialLogin();

            socialLogin.EmailAddress           = email;
            socialLogin.FullName               = firstname + (string.IsNullOrEmpty(lastname) ? "" : " " + lastname);
            socialLogin.IsGoogleLogin          = false;
            socialLogin.FacebookProviderUserId = Convert.ToString(me.id);

            UserDomainLogic userDomainLogic = new UserDomainLogic();
            Message         message         = userDomainLogic.RegisterUserthroughSociallogin(socialLogin);

            if (message.MessageType == Domain.Enums.MessageType.Success)
            {
                return(RedirectToAction("Dashboard", "User"));
            }
            else if (message.MessageType == Domain.Enums.MessageType.NewUser)
            {
                TempData["isFromSocialMedia"] = true;
                return(RedirectToAction("NewRegistrationfromSocialPage", "User", new { sm = true }));
            }
            else
            {
                ErrorBlock(message.MessageText);
                return(View("Login"));
            }

            //// Set the auth cookie
            //FormsAuthentication.SetAuthCookie(email, false);
            //return RedirectToAction("Dashboard", "User");
        }
Пример #17
0
        public async Task <ActionResult> CallBack(string code)
        {
            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..fb callback");
                System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " code is : " + Environment.NewLine + code);
            }

            KaribouAlpha.Models.FaceBookClient client = db.FaceBookClients.SingleOrDefault(_fb => _fb.Active);
            if (client == null)
            {
                ViewBag.EmailError = true;
                return(View("CallBack"));
            }

            //verifyTokenEndPoint = string.Format("https://graph.facebook.com/debug_token?input_token={0}&access_token={1}", code, appToken);
            //HttpResponseMessage response;
            //Uri uri = new Uri(verifyTokenEndPoint);

            //using (HttpClient httpClient = new HttpClient())
            //{
            //    response = await httpClient.GetAsync(uri);
            //}

            //if (response.IsSuccessStatusCode)
            //{
            //    System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " graph api status code ok..");
            //    string content = await response.Content.ReadAsStringAsync();
            //    System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() +  content);
            //}
            //else
            //{
            //    System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " graph api status code failed..");
            //}

            var     fb     = new Facebook.FacebookClient();
            dynamic result = fb.Post("oauth/access_token", new
            {
                client_id     = client.AppId,
                client_secret = client.AppSecret,
                redirect_uri  = RedirectUri.AbsoluteUri,
                code          = code
            });


            var accessToken = result.access_token;

            if (writeLog)
            {
                System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + accessToken);
            }
            fb.AccessToken = accessToken;
            dynamic me = fb.Get("me?fields=first_name,last_name,id,email");

            ViewBag.EmailError = false;
            if (string.IsNullOrEmpty(me.email) == true)
            {
                if (writeLog)
                {
                    System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " fb email not found...");
                }

                ViewBag.EmailError = true;
                return(View("CallBack"));
            }

            var    email     = me.email;
            string firstname = me.first_name;
            string lastname  = me.last_name;
            var    id        = me.id;

            if (writeLog)
            {
                System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + "found email and names...");
            }

            User user = await this._authenticationRepository.FindAsync(new Microsoft.AspNet.Identity.UserLoginInfo("Facebook", id));

            bool hasRegistered = user != null;

            if (writeLog)
            {
                System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " has registered.." + hasRegistered.ToString());
            }
            ViewBag.haslocalaccount = hasRegistered.ToString();

            bool hasCervitUser        = false;
            long existingCervitUserId = this._authenticationRepository.FindUserExists(email);

            hasCervitUser = (existingCervitUserId > 0);
            if (hasRegistered)
            {
                hasCervitUser = false;
            }

            if (writeLog)
            {
                System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " has hasCervitUser.." + hasCervitUser.ToString());
            }
            ViewBag.hascervituser         = hasCervitUser.ToString();
            ViewBag.provider              = "Facebook";
            ViewBag.external_user_name    = id;
            ViewBag.external_access_token = accessToken;
            ViewBag.email = email;
            return(View("CallBack"));
        }
Пример #18
0
        public ActionResult FacebookCallbackLogin(string code)
        {
            try
            {
                var fb = new Facebook.FacebookClient();
                dynamic result = fb.Post("oauth/access_token", new
                {
                    client_id = "510735142346763",
                    client_secret = "c4df6a6934bc013daa1560bd063921b0",
                    redirect_uri = RedirectUri.AbsoluteUri,
                    code = code
                });

                var accessToken = result.access_token;

                // Store the access token in the session
                Session["AccessToken"] = accessToken;

                // update the facebook client with the access token so 
                // we can make requests on behalf of the user
                fb.AccessToken = accessToken;

                // Get the user's information
                dynamic me = fb.Get("me?fields=first_name,last_name,id,email,gender,username");

                GetSingleMemberResponse model = _member.GetSingleByFacebookId(me.id);

                if (model.Code == "-1" && model.Code.Contains("No member"))
                {
                    MemberEditResponse data = _member.CreateMember(me.first_name, me.last_name, me.email, me.username, me.username, null,
                                                me.gender == "male", null, null, null, me.locale, me.id);

                    if (data.Code == "-1" && data.Message.Contains("Username"))
                        data = _member.CreateMember(me.first_name, me.last_name, me.email, me.username, null, null,
                                                   me.gender == "male", null, null, null, me.locale, me.id);
                    else if (data.Code == "-1")
                    {
                        return RedirectToAction("SignUp");
                    }
                    if (data.Code == "-1")
                    {
                        return RedirectToAction("SignUp");
                    }
                }

                SessionManager.IsLoggedIn = true;
                SessionManager.UserLogged = new UserProfile
                {
                    FacebookId = model.Member.MemberFacebookId,
                    FirstName = model.Member.MemberFirstName,
                    LastName = model.Member.MemberLastName,
                    UserName = model.Member.MemberUserName,
                    UserId = model.Member.MemberId
                };

                return RedirectToAction("Index", "Home");
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return RedirectToAction("Index", "Home");
            }
        }