Facebook php Oauth is not working - facebook-oauth

I'm new to facebook apps and php in general, and I have a bit of a problem. I cannot get OAuth to work correctly with my application. When you go the application itself, it does not redirect to the oAuth dialog. It merely displays a blank page that does nothing. If anyone can help me with this, I really need it haha. Thanks!
So far, my code is as follows:
<?php
include_once ('santatree/facebook.php');
$app_id = '276853929000834';
$application_secret = 'e3a12b11221f3fef1e06952e15fdc8e4';
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $application_secret,
'cookie' => true, // enable optional cookie support
));
?><?
if ($facebook->getSession())
{
$user = $facebook->getUser();
}
else
{
$loginUrl = "https://www.facebook.com/dialog/oauth? type=user_agent&display=page&client_id=276853929000834
&redirect_uri=http://apps.facebook.com/digitalsanta/&scope=user_photos";
header("Location: https://www.facebook.com/dialog/oauth? type=user_agent&display=page&client_id=276853929000834 &redirect_uri=http://apps.facebook.com/digitalsanta/ &scope=user_photos");
echo '';
}

I do my redirects based on the session token.
This assumes that you will be using the most recent php-sdk 3.1.1 and have Oauth2 enabled in your app settings.
SAMPLE HERE: login / out url is in footer of plugin. http://apps.facebook.com/anotherfeed/TimeLineFeed.php?ref=facebook-stackoverflow
<?php
require './src/facebook.php';
$facebook = new Facebook(array(
'appId' => '',
'secret' => '',
));
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
$access_token = $_SESSION['fb_135669679827333_access_token'];
if (!$access_token) {
echo '<script>';
echo 'top.location.href = "'.loginUrl.'";';
echo '</script>';
} else {
echo 'Logout';
}
?>
https://developers.facebook.com/apps to edit your app.
If you do not have an app you will need to create one.
You will also need to set up the canvas and secure canvas urls to avoid errors.

You only defined the variable $loginUrl, but you haven't redirect user to go to the URL. Consider using
header("Location: $loginUrl");
to forward your user if you haven't sent your header yet.

Related

Redirect restfull api codeigniter

I want to ask how to redirect the results from the input code form post like this
how do i redirect resfull api I want after input_post () page will be redirected
public function loginsi_post(){
$username = $this->post('username');
$password = $this->post('password');
$data = [];
$data['username'] = $username;
$data['password'] = $password;
if ($this->model_app->insert('jajal', $data) > 0) {
$this->response([
'message' => 'data berhasil disimpan',
'data' => $data
], REST_Controller::HTTP_CREATED);
}else{
$this->response([
'message' => 'data gagal disimpan'
], REST_Controller::HTTP_CREATED);
}
redirect('main/home'); ---------> is not working
}
Please setup your route like as below.
public function index() {
/*Load the URL helper*/
$this->load->helper('url');
/*Redirect the user to some site*/
redirect('http://www.example.com');
}
Best Regards.
Note: One can not access any controller that is in other folder and script access is not allowed this way. So there must be route set in route.php then you can access the function using route path. It can be defined as below:-
Like for example:- In route.php, the route is defined as:-
$route['your uri']='your uri';
then to access controller :-
$captcha_url = "http://your_api_url/index.php/nlpgen/nlpimg/"
Now you can use CURL to access the external URL.

How to create simply REST API Login?

I've trying to create login code in REST Server and while I use POSTMAN to check it, the output always show HTTP_BAD_REQUEST(Login Failed). The code is ignoring security.
I use REST from https://github.com/chriskacerguis/codeigniter-restserver
This is My Controller
public function index_post(){
$data_memb = array(
'id_member'=>$this->post('id_member'),
'password'=>$this->post('password')
);
$result = $this->Member_model_api->loginMember($data_memb);
if ($result == TRUE) {
$this->response([
'status' => true,
'message' => 'Login Successfull'
], REST_Controller::HTTP_OK);
} else {
$this->response([
'status' => false,
'message' => 'Login Failed'
], REST_Controller::HTTP_BAD_REQUEST);
}
}
}
This is My Model
public function loginMember($data_memb)
{
$sql = 'SELECT * FROM member WHERE id_member = ?';
$binds = array($data_memb['id_member']);
$query = $this->db->query($sql, $binds);
if ($query->num_rows()>0) {
$rw_password = $query->result();
if (password_verify($data_memb['password'],
$rw_password[0]->password)) {
return true;
} else {
return false;
}
} else {
return false;
}
}
I expect the output is HTTP_OK(Login Successfull), or if you have more reference code, please tell me. Thanks for your help.
Since you are using POST method, you should use form-data while sending request.
I assume there may be some re-formatting issue on the server-side which might be preventing your login functionality to get verified.
Try printing both variables on the server-side and view the output.
var_dump($data_memb)
Nothing needs to send urlencoded in POST request.
Try changing the request type and see, this will work.

yii2 retrieve passwordHash for AccessTokenByUser

for use in Mobile App, I am trying to use Yii2 built in RestApi.
Now what I understand by the reading that we should disable session and set loginUrl property to false.
Now what I want is, I want a login screen for my app and want to authenticate against API.
how I can achieve the same.
Note:
I can authenticate with username and password for different controllers including users controller as well as bearer token.
also I read an example in" yii2 by example"
public function actionAccessTokenByUser($username, $passwordHash)
{
$accessToken = null;
$user = \app\models\User::findOne(['username' => $username, 'password_hash' => $passwordHash]);
//var_dump($passwordHash1);exit;
if($user!=null)
{
$user->access_token = Yii::$app->security->generateRandomString();
$user->save();
$accessToken = $user->access_token;
}
return [ 'access-token' => $accessToken ];
}
my question is how I get the `$passwordHash to supply here. I tried to look back and forth, but couldn't find any solution.
my main purpose is how I can implement a application login for mobile and thereon supply the accesstoken in the background wherever needed.
I believe I have refactored the code to achieve what I am looking. Open to suggestion or any flaw in my implementation.
here is what I have done.
public function actionAccessTokenByUser($username, $password)
{
$accessToken = null;
$username = \app\models\User::findByUsername($username);
if ($username!=null)
{
if($username->validatePassword($password)) $user = $username;
}
// $user = \app\models\User::findOne(['username' => $username, 'password_hash' => $passwordHash]);
if($user!=null)
{
$user->access_token = Yii::$app->security->generateRandomString();
$user->save();
$accessToken = $user->access_token;
}
return [ 'access-token' => $accessToken ];
}

vimeo direct upload form

According to Vimeo it is possible to send the upload directly to their server, without having to use the hosting server of the site.
https://help.vimeo.com/hc/en-us/articles/224970068-Can-I-upload-directly-to-Vimeo-and-skip-my-server-entirely-
With documentation:
https://developer.vimeo.com/api/upload/videos#http-post-uploading
But, I did not find any examples or I could understand how to do this
Resolved
Download API Vimeo: API Vimeo
Load API: File: vimeo_init.php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
// Load the autoloader
if (file_exists('/vimeo/autoload.php')) {
// Composer
require_once('/vimeo/autoload.php');
} else {
// Custom
require_once(__DIR__ . '/vimeo/autoload.php');
}
// Load the configuration file.
if (!function_exists('json_decode')) {
throw new Exception(
'We could not find `json_decode`. `json_decode` is found in PHP 5.2 and up, but not found on many Linux ' .
'systems due to licensing conflicts. If you are running Ubuntu try `sudo apt-get install php5-json`.'
);
}
$config = json_decode(file_get_contents(__DIR__ . '/vimeo_config.json'), true);
if (empty($config['client_id']) || empty($config['client_secret'])) {
throw new Exception(
'We could not locate your client id or client secret in "' . __DIR__ . '/vimeo_config.json". Please create one, ' .
'and reference config.json.example'
);
}
return $config;
Config API KEY: File vimeo_config.json
{
"client_id" : "",
"client_secret" : "",
"access_token" : ""
}
File POST PHP: File Upload Video
use Vimeo\Vimeo;
use Vimeo\Exceptions\VimeoUploadException;
$config = require(__DIR__ . '/vimeo_init.php');
$files = array($_FILES['video_arquivo']['tmp_name']); //array_shift($files);
if (empty($config['access_token'])) {
throw new Exception(
'You can not upload a file without an access token. You can find this token on your app page, or generate ' .
'one using `auth.php`.'
);
}
$lib = new Vimeo($config['client_id'], $config['client_secret'], $config['access_token']);
$uploaded = array();
foreach ($files as $file_name) {
try {
$uri = $lib->upload($file_name, array(
'name' => 'titulo',
'description' => 'descricao'
));
$video_data = $lib->request($uri);
if ($video_data['status'] == 200) {
$video_vimeo = $video_data['body']['link'];
}
$uploaded[] = array('file' => $file_name, 'api_video_uri' => $uri, 'link' => $link);
} catch (VimeoUploadException $e) {
$result["is_valid"] = false;
$result["message"] = $e->getMessage();
}
}

not responding while login

I am new to CodeIgniter, and am trying to write code to log in after registering using a username and password in registration form using a PHPMyAdmin database. I am not getting anything when I try to log in, and it doesn't display an error or any message.
public function login() {
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password' , 'Password');
if($this->form_validation->run() == TRUE){
//check user in database
$this->db->select('username' , 'password');
$this->db->from('user_register');
$this->db->where(array('username' => $username, 'password' => $password));
$query = $this->db->get();
$user = $query->row();
if($user->email){
$this->session->set_flashdata("Successful login");
$_SESSION['user_logged'] = TRUE;
$_SESSION['username'] = $user->username;
} else {
$this->session->set_flashdata("Error No such record found");
}
}
// load view and showing login form
$this->load->view('login');
}
First, you should read the documentation, looks like you skip that part, but it's very important!
Let's code a little bit and fix the bugs!
User data
Well, users will enter their data and we will check, if evertyhing is correct, we can redirect user to the protected page. You call for variables (see Query:) but you I'm not seeing on your code. You should put like that, before your query job
$username = $this->input->post("username");
$password = $this->input->post("password");
Now, you will be able to use the where to get the user data. =)
Query:
If read about OOP with PHP, you know that when you pass parameters to a method, each parameter have their own "action". In case of the select method, you should keep the data you want to select, on the same quote, because you the way you do, it's like you passing multiple parameters to the method.
$this->db->select('username, password');
$this->db->from('user_register');
$this->db->where(array('username' => $username, 'password' => $password));
First, to decide if the record exist or not, I prefer this way:
if($query->num_rows() > 0) {
$user_data = $query->row();
// We should verify if the user entered the password that correspond to the account.
// If not, we tell them that the password is incorrect.
if($password != $user_data->password) {
$this->session->set_flashdata("error", "Wrong password!");
return redirect(site_url());
}
// You can use the CI built in methods to work with sessions
$this->session->set_userdata(array(
'username' => $user_data->username,
));
$this->session->set_flashdata("success", "You are logged in!");
return redirect(site_url());
} else {
$this->session->set_flashdata("Error: No such record found");
redirect(site_url());
}
Flash data
Yeah, we use flashdata to show a message for the user. But, you should pass an item and the value of this item. Like that:
$this->session->set_flashdata('success', 'Successfully logged in!");
And, to retrieve the data on your views, you can do like...
<?php
$success = $this->session->flashdata("success");
$error = $this->session->flashdata("error");
if(!empty($success)) {
echo $success;
}
if(!empty($success)) {
echo $error;
}
?>
Recommendations
Sessions: https://codeigniter.com/userguide3/libraries/sessions.html
Database: https://www.codeigniter.com/userguide3/database/query_builder.html
Also, I recommed you, to take a minute on YouTube, to understand CodeIgniter.
If I forgot something, let me know! =)
Great Suggestion by webmasterdro's Answer.
I would like to extend it a little bit.
Looking at your code it looks like you have added the query to the controller.
And as a suggestion, if you are using an MVC framework then try to follow some basic MVC flow. because if you are not following that then it will be useless to use a framework.
User Controller to handle the post data and validations.
Use model to do the database query.
Use __construct for loading the common model or libraries.
Do not save plane password use md5 or other encryption technique.
Store User detail to the session which you can use further in after login.
Codeigniter has a great user guide. Try to follow that.
So, your code Should be your like this below.
Controller:
public function __construct() {
parent::__construct();
// Load model
$this->load->model('login_database');
}
public function your_controller_function_name() {
// Check validation for user input in SignUp form
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
$this->load->view('login_form_view');
} else {
$username = $this->input->post("username");
$password = $this->input->post("password");
$result = $this->login_database->registration_insert($username, $password);
//You can do this also if($result != FALSE)
if (!empty($result)) {
// You can set other data to the session also form here
$session_data = array(
'username' => $result['user_name']
);
// Add user data in session
$this->session->set_userdata('logged_in', $session_data);
// You can set flash data here
$this->load->view('your_view');
} else {
$data = array(
'error_message' => 'Invalid Username or Password'
);
$this->load->view('your_login_form_view', $data);
}
}
}
Model:
// Read data using username and password
public function login($username, $password) {
$this->db->select('username');
$this->db->from('user_register');
$this->db->where(array('username' => $username, 'password' => $password));
$query = $this->db->get();
$user_data = $query->row_array();
if ($query->num_rows() == 1) {
return user_data;
} else {
return false;
}
}
I have not added detail related to flash data because the previous answer has explained it properly.