Facebook API - fql_query, Invalid session - session

I'm trying to query Facebook with the PHP Library and what I've read it shouldn't required a session key, or rather it shouldn't require one for my case, but my code below gives me the following error: "Session key invalid or no longer valid".
http://wiki.developers.facebook.com/index.php/Fql.query
"For example, querying the user table is like calling users.getInfo without a session key -- you can query only on a few fields."
$fb = new Facebook(FACEBOOK_KEY, FACEBOOK_SECRET);
$query = "SELECT uid,
name,
sex,
pic_square,
profile_url
FROM user WHERE name = 'some name' OR username = 'some name'";
$result = $fb->api_client->fql_query($query);
Any ideas?
/Thanks

I think that policy has changed and you cannot query user table without session.
You can try to query standard_user_info table. Think it doesn't need session.

Related

Customize Passport Queries time of authenticating

For every request I found that 4 queries are fired to validate the user and the token. Among them one is to fetch the user (select * from user) based on the user id. This queries are fired by Passport/Laravel But what I want is to modify this query to add one status field check also to check if any user become invalid during the token validity period. If we only check with the id then if any user become inactive(By changing status then also we will not be able to stop the user as deleting the token for the user is not a good solution for me).
Queries Fired on every request by Passport Laravel:
select * from oauth_access_tokens where id = ?
select * from user where id = ? limit 1 ["2"]
select * from oauth_access_tokens where id = ?
select * from oauth_clients where id = ?
So, can anyone tell me how to change the 'select * from user where id' query in passport at time of Token validation.
You can add this method on your User model (or any model you're authenticating with passport)
...
public function findForPassport($username)
{
return $user = (new self)->where('email', $username)->where('is_active', 1)->first();
}
...
of course you can modify is_active by whichever column you are using (and/or any query constraint for that matter), as long as it returns Illuminate\Contracts\Auth\Authenticatable contract.
I wouldn't try and modify passports default behaviour as I have no idea what else it might impact both now and in future upgrades.
Your best bet might be to hook into the passport events and apply you business logic to a listener that is called when the events are fired

Select Md5 combination of 2 rows from mysql

I have md5 some of the user information (lets say id and email for simplicity) and would like to use those information to find that user in my database.
The code in it's simplest form looks something like this
return $this->db->get_where('table', array('MD5(id,email)='=>$token ) ,1);
Not sure why but its returning false;
Update: trying to do this in sql
Just found out in when i try to do this in mysql I get an error
#1582 - Incorrect parameter count in the call to native function 'md5'
Is this mean you cant md5 multiple rows ? if so how do I do this!
Update: Again it returns false
$this->db->select('md5(id,email) as token');
$this->db->where('token', $token);
$this->db->limit(1);
$result = $this->db->get('table->customers');
Try concat in the where clause.
$this->db->where("md5(CONCAT(id,email)) = '".$token."'");

writing basic Ruby code to register user in SQLite database

I need some help writing basic Ruby code to register a user in a SQLite database. I'm very new to Ruby, I checked lots of good examples online but my code still doesn't work.
This is my 1st test project using Ruby, so appreciate any help and apologise for making any bad mistakes.
require 'sqlite3'
def register_user(l)
user = l[1]
pass = l[2]
db = SQLite3::Database.new "database.db"
db.execute("INSERT INTO users (user, pass)
VALUES (#{user}, #{pass})")
end
def cmd_register(l)
if register_user(#{#nick}, l[1])
sv_send 'NOTICE', 'REGISTER', ':*** User created'
else
sv_send 'NOTICE', 'REGISTER', ':*** User not created'
end
end
There are a few problems with your code. First, here:
db.execute("INSERT INTO users (user, pass)
VALUES (#{user}, #{pass})")
You're trying to generate a query that looks like this (supposing the variable user contains "Jordan" and pass contains "xyz"):
INSERT INTO users (user, pass) VALUES('Jordan', 'xyz')
...but your code generates a query that looks like this:
INSERT INTO users (user, pass) VALUES(Jordan, xyz)
Do you see the difference? Values in SQL queries need to be surrounded by quotation marks. Your query will fail because SQLite doesn't know what Jordan is; it only knows what 'Jordan' is.
You could just add quotation marks to your query, but then you would have another problem: SQL injection attacks. Because you're just blindly putting the values of user and pass into your query, an attacker could manipulate those values to perform a different query than you intended. Never use string interpolation (#{var}) or concatenation (+ or <<) when creating an SQL query. (For a brief description of how SQL injection attacks work, read the "How to get hacked" section on this page: http://ruby.bastardsbook.com/chapters/sql/.)
The correct way to use variables in a query is with prepared statements and parameter binding. It looks like this:
statement = db.prepare("INSERT INTO users (user, pass) VALUES (?, ?)")
statement.bind_params(user, pass)
result = statement.execute
What this does is automatically escapes the values of user and pass to make sure they don't do anything you don't expect, wraps them in quotation marks, and substitutes them for the question marks in the query. Another way to do the same thing is this:
result = db.execute("INSERT INTO users (user, pass) VALUES (?, ?)", user, pass)
The other obvious problem with your code is this:
if register_user(#{#nick}, l[1])
This is a syntax error. You can only use the #{var} syntax in a string, like "hello #{var}". In this case you just want to do this:
if register_user(#nick, l[1])
require "sqlite3"
my_db = SQLite3::Database.new "my_db1.db"
my_db.execute <<END_OF_CREATE #The <<END_OF_CREATE .... END_OF_CREATE thing is called HEREDOC syntax, which is one way to create a String that spans multiple lines
CREATE TABLE IF NOT EXISTS users( #A useful SQL command to be aware of.
name varchar(30),
password varchar(30)
);
END_OF_CREATE
def register_user(target_db, user_info)
user_name, user_pass = user_info #A neat trick for "unpacking" an Array
target_db.execute(
"INSERT INTO users (name, password)
VALUES (?, ?)", user_name, user_pass #For security reasons, inserts into a db should use this "question mark" format.
)
end
register_user(my_db, ['John', 'abc123'])
register_user(my_db, ['Jane', 'xyz456'])
my_db.execute("SELECT * FROM users") do |row|
p row #Use the 'p' method instead of puts to print an Array or Hash.
end
--output:--
["John", "abc123"]
["Jane", "xyz456"]
Also, don't ever name a variable l. You absolutely, no exceptions, have to use descriptive variable names. See the code above for an example.
Even though the code above unpacks the user_info array into separate variables, that is actually not required because execute() will take an
Array as an argument:
target_db.execute(
"INSERT INTO users (name, password)
VALUES (?, ?)", user_info
)
In other words, all the values for the question marks can be gathered into an Array and provided as the last argument for execute().
One problem you can run into when writing and testing database programs is when you change one of the column names in your table. The code above will cause an error: the table will not be re-created because the table already exists, but your new code will use the new column name, which won't exist in the table.
So, you might consider using this combination of sql statements:
my_db.execute <<END_OF_DROP
DROP TABLE IF EXISTS users
END_OF_DROP
my_db.execute <<END_OF_CREATE
CREATE TABLE users(
name varchar(30),
password varchar(30)
);
END_OF_CREATE
With those sql statements, if you change one of the column names (or add a column), then your new code won't throw an error because the table is destroyed and recreated with the new column names every time you run your program.

Get permission data from Database

I'm having problems to do a simple permission system on my Webapp. My DB has a table called "usuario" that has informations about the users of the system. One of these columns is called "privilegio" that has value '0' for administrators and 1 for regular users. An administrator has the power to Add and edit users on the system. Im trying to take this behavior querying my database with the cod of the logged user and getting its permission. If the user is not on the administrator group (privilegio=1) then the add/edit/delete buttons will be unset.
public function usuario() {
if($this->session->userdata('logged')){
$crud = new grocery_CRUD();
$crud->set_subject("Usuário");
$crud->set_theme('datatables');
$crud->set_table("usuario");
(...)
$crud->field_type('privilegio','dropdown',array('0'=>'Administrador','1'=>'Usuario'));
(...)
$this->db->select('privilegio');
$this->db->get('usuario');
$result = $this->db->where('cod_func',$this->session->userdata('cod_func'));
if(!$result){
$crud->unset_add();
$crud->unset_edit();
$crud->unset_delete();
}
(...)
The problem (and the question) is that this code only list the user that is logged on, not the others already registered on the system and stored on "usuario" table. I wonder that the list is been made by my query (what is not the behavior I would like) I hope you could undestand my doubt. Sorry for my bad english.
Thank you!
you're having trouble with the active record functions...
When you use the function
$this->db->get('usuario');
This translates to the query:
SELECT * FROM usuario
So try changing your code to something like this:
$this->db->select('privilegio');
$this->db->from('usuario');
$this->db->where('cod_func',$this->session->userdata('cod_func'));
$this->db->limit(1); //You're only expecting one result
$result = $this->db->get(); // Save the result to the variable result
//Edited for the comment, something like
$result = $result->first_row('array'); //Here I'm fetching only the first row into an array
$privilegio = $result['privilegio']; //Im saving the result from the query in the variable $privilegio
This translates to:
SELECT priviliegio FROM usuario WHERE cod_func = 'some_value' LIMIT 1;
Then you can do whatever you want with the $result variable, please refer to documentation to see what you can do...
Generating Query Results

CodeIgniter: storing sessions in DB, how to know who session came from?

I'm thinking of storing CI sessions in the database so I can display how many users are currently online, who specifically is online, etc.
Looking at http://codeigniter.com/user_guide/libraries/sessions.html, am I right in my understanding that information would be stored in the user_data column of the ci_session table? Meaning, maybe I just store the user's id in there?
CodeIgniter will store the data in the table you specify in your config file. By default, it's ci_session. The session information, what is accessible through $_SESSION for instance, is serialized and saved in a column named user_data. That field will not be able to tell you whether or not the session has expired (or in other words, how many people are online).
What you could do instead is use the last_activity column, which is a timestamp of the last time that session was active. You could run a SQL query that selects the count of session_id where the last_activity is less than 2 minutes ago.
SELECT COUNT(`session_id`) AS `active_user_count` FROM `ci_session` WHERE `last_activity` >= DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 2 MINUTE)
With that said, an existing session doesn't necessarily mean that the user is "signed in". If you need to check that they're signed in, you can use a LIKE operator to add a condition to the WHERE statement that checks if a user is signed in. This will depend on what variable name you're using so have a look at your data and see if you can figure it out.
For example:
SELECT COUNT(`session_id`) AS `active_user_count` FROM `ci_session` WHERE `last_activity` >= DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 2 MINUTE) AND `user_data` LIKE '%s:9:"logged_in";b:1;%'
This works! use it
$session = $this->db->get('ci_sessions')->result_array();
foreach ($session as $sessions) {
$sessio = $sessions['last_activity'] + 7200;
echo $sessio . "time";
echo now();
echo "||";
$custom_data = $this->session->_unserialize($sessions['user_data']);
if (is_array($custom_data)) {
foreach ($custom_data as $key => $val) {
$user[$key] = $val;
}
}
}
print_r($user);
exit();`

Resources