CodeIgniter Facebook API getuser always 0 - php

I know this is a duplicate, however, I've tried pretty much everything suggested in the other questions.
I'm currently getting a redirect loop because getUser is always returning 0, even after approving the app.
Code:
public function auth() {
$user = $this->facebook->getUser();
if ($user) {
$user = $this->facebook->api('/me');
if (!$this->Users->getByID($user["id"])) {
$this->data->needsRegister = true;
} else {
$toSetInSessions = new stdClass();
$toSetInSessions->authed = 1;
$dbUser = $this->Users->getByID($user["id"]);
foreach ($dbUser as $key => $value) {
$toSetInSessions->user->$key = $value;
}
$this->session->set_userdata($toSetInSessions);
redirect("/");
}
} else {
$params = array('scope' => 'email,read_friendlists');
if ($_SERVER['HTTP_USER_AGENT'] != "facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)") {
redirect($this->facebook->getLoginUrl($params));
}
}
$this->load->view('header', $this->data);
$this->load->view('auth', $this->data);
$this->load->view('footer', $this->data);
}
Here is the screenshot of my settings page for this App.
https://dl.dropbox.com/u/6647629/facebookapp.png
Sometimes it does work, but most of the time it doesn't.

Found the solution here: http://www.galalaly.me/index.php/2012/04/using-facebook-php-sdk-3-with-codeigniter-2-1/
Had to add:
parse_str($_SERVER['QUERY_STRING'], $_REQUEST);

Related

Session Dying Right After Calling Auth::login()

Stackoverflow community! We've been struggling with this issue for a while now. We're attempting to upgrade our Laravel v4 site to Laravel v7. So far, it's been fine. When we use our login function, it properly authorizes the user, but upon redirect, the session gets killed. We've checked it over and over again, but we simply cannot find anything that could be the cause of the issue. Here is the suspect function:
public function loginv2()
{
if (Auth::check()) {
return Redirect::action('FrontController#showWelcome')->withMessage("Already logged in.");
}
if (!Auth::check() && !isset($_GET['token']))
{
$_SESSION['redirect'] = "https://zjxartcc.org";
header("Location: https://login.vatusa.net/uls/v2/login?fac=ZJX");
exit;
}
$token = $_GET['token'];
$parts = explode('.', $token);
$token = $this->base64url_decode($parts[1]);
$jwk = json_decode('{"alg":"HS256","use":"sig","kty":"oct","k":"..."}', true);
$algorithms = ['HS256' => 'sha256', 'HS384' => 'sha384', 'HS512' => 'sha512'];
if (!isset($algorithms[$jwk['alg']])) {
return Redirect::action('FrontController#showWelcome')->withMessage("Invalid Operation");
}
$sig = $this->base64url_encode(hash_hmac($algorithms[$jwk['alg']], "$parts[0].$parts[1]", $this->base64url_decode($jwk['k']), true));
if($sig == $parts[2]) {
$token = json_decode($token, true);
if($token['iss'] != 'VATUSA') {
return Redirect::action('FrontController#showWelcome')->withMessage("Not issued from VATUSA");
}
if($token['aud'] != 'ZJX') {
return Redirect::action('FrontController#showWelcome')->withMessage("Not issued for ZJX");
}
$client = new GuzzleHttp\Client();
$url = "https://login.vatusa.net/uls/v2/info?token={$parts[1]}";
$result = $client->get($url);
$res = json_decode($result->getBody()->__toString(), true);
$userstatuscheck = User::find($res['cid']);
if($userstatuscheck) {
if($userstatuscheck->status == 1) {
return Redirect::action('FrontController#showWelcome')->withMessage("You are not an active controller, and cannot login.");
} else {
Auth::login($userstatuscheck, true);
require("/home2/zjxartcc/public_html/forum/smf_2_api.php");
smfapi_login($userstatuscheck->id);
setcookie("ids_loggedin", $res['cid'], 0, "", ".zjxartcc.org");
$_SESSION['loggedin'] = $res['cid'];
}
} else {
return Redirect::action('FrontController#showWelcome')->withMessage("No user matching your information on the roster.");
}
//update email records and rating
$forum = SMFMember::find($res['cid']);
$forum->email_address = $res['email'];
$forum->save();
$member = User::find($res['cid']);
$member->rating_id = $res['intRating'];
$member->email = $res['email'];
$member->save();
return Redirect::action('FrontController#showWelcome')->withMessage('You have been logged in!');
} else {
return Redirect::action('FrontController#showWelcome')->withMessage("Bad Signature");
}
}
All help and suggestions are greatly appreciated! Thank you!

Codeigniter throws 520 error CloudFlare while using session

I am using Codeigniter with cloudflare and getting 520 error while storing user value in session during login.
Here is login function:
function check_login_submit($post_data) {
if ($post_data) {
$mob = trim($post_data['mob']);
$password = trim($post_data['password']);
$sql = "Select * from table where phone='$mob' and password='$password'";
$query = $this->db->query($sql);
$user = $query->row();
if ($query->num_rows() == 1) {
if ($user->status == 1)
{
$this->session->set_userdata('mem_id', $user->id);
$this->session->set_userdata('mem_last_login_date', $user->last_login_date);
$this->session->set_userdata('mem_created_on', $user->created_on);
//-- Update last login of successfull Login
$sql = "update table set last_login_date = NOW() where id=$user->id";
$query = $this->db->query($sql);
return TRUE;
}
}
else {
return FALSE;
}
}
}
If i will stop the storing value into session user data than it will working fine however with session cloudflare give me 502 error page.
Please advise
Thanks in advance for your time and support.
If anyone else runs into this problem, I came up with a solution that involves extending the core Session library that ultimately reduces the number of calls to sess_write() and by extension, _set_cookie().
MY_Session.php:
class MY_Session extends CI_Session {
function set_userdata($newdata = array(), $newval = '', $write_session = true)
{
if (is_string($newdata))
{
$newdata = array($newdata => $newval);
}
if (count($newdata) > 0)
{
foreach ($newdata as $key => $val)
{
$this->userdata[$key] = $val;
}
}
// Do not write the session (set the cookies) unless explicitly specified
if ($write_session) {
$this->sess_write();
}
}
function set_flashdata($newdata = array(), $newval = '')
{
if (is_string($newdata))
{
$newdata = array($newdata => $newval);
}
if (count($newdata) > 0)
{
foreach ($newdata as $key => $val)
{
$flashdata_key = $this->flashdata_key.':new:'.$key;
$this->set_userdata($flashdata_key, $val, false); // Do not update the cookie in the foreach
}
}
// Save the cookie now that all userdata has been set
$this->sess_write();
}
function _flashdata_mark()
{
$userdata = $this->all_userdata();
$newUserData = array();
$userDataToUnset = array();
foreach ($userdata as $name => $value)
{
$parts = explode(':new:', $name);
if (is_array($parts) && count($parts) === 2)
{
$new_name = $this->flashdata_key.':old:'.$parts[1];
$newUserData[$new_name] = $value;
$userDataToUnset[$name] = '';
// Cookies were originally set in this loop. Moved to the end of the function
}
}
// Save all changes outside of the loop
if (count($newUserData) > 0) {
$this->set_userdata($newUserData);
$this->unset_userdata($userDataToUnset);
}
}
}
A 520 error generally indicates that there are large cookies or headers being returned that hit proxy buffer limits on our end. A HAR file send to our support team will help us figure out what the issue is.

Moodle php - where does moodle check if the provided enrolment key matches the course's predefined enrollment key?

I am creating a moodle website. I already setup my courses with their specific enrolment keys, etc. But I want to know in what .php file and where in that file (in the moodle files), does Moodle check if the enrollment key entered by the user matches what I set as the enrolment key for the course...
Thanks for your help!
UPDATE--------
I did as Russell England suggested, but when I go to the page where I type my enrolment key, the page isn't loading or the page is redirected to my moodle homepage. My table that I store the enrolment keys is user_enrolment_keys.
Here is the updated validation function:
public function validation($data, $files) {
global $DB, $CFG, $USER;
$errors = parent::validation($data, $files);
$instance = $this->instance;
if ($this->toomany) {
$errors['notice'] = get_string('error');
return $errors;
}
//--------Russell's suggestion--------------
if ($instance->password) {
$params = array('user_email' => $USER->email, 'course_id' => $instance->courseid, 'enrolment_key' => $data['enrolpassword']);
if (!$DB->record_exists('user_enrolment_keys', $params)) {
$errors['enrolpassword'] = get_string('passwordinvalid', 'enrol_self');
return $errors;
}
}
//What I tried last (did not work either)...
/*$uemail = $USER->email;
$userscoursekey = 'testing';
$connecty = mysqli_connect("localhost", "...", "...", "...");
mysql_select_db('user_enrolment_keys', $connecty);
$var2 = $instance->courseid;
$resulty = mysqli_query($connecty, "SELECT * FROM user_enrolment_keys WHERE user_email='$uemail' AND course_id='$var2'");
$numrows = $resulty->num_rows;
if($numrows > 0)
{
while($row = mysqli_fetch_assoc($resulty))
{
$userscoursekey = $row['enrolment_key'];
}
}
$instance->password = $userscoursekey;
my_sqli_close($connecty); //Close the database connection.*/
if ($instance->password) {
if ($data['enrolpassword'] !== $instance->password) {
if ($instance->customint1) {
$groups = $DB->get_records('groups', array('courseid'=>$instance->courseid), 'id ASC', 'id, enrolmentkey');
$found = false;
foreach ($groups as $group) {
if (empty($group->enrolmentkey)) {
continue;
}
if ($group->enrolmentkey === $data['enrolpassword']) {
$found = true;
break;
}
}
if (!$found) {
// We can not hint because there are probably multiple passwords.
$errors['enrolpassword'] = get_string('passwordinvalid', 'enrol_self');
}
} else {
$plugin = enrol_get_plugin('self');
if ($plugin->get_config('showhint')) {
$hint = core_text::substr($instance->password, 0, 1);
$errors['enrolpassword'] = get_string('passwordinvalidhint', 'enrol_self', $hint);
} else {
$errors['enrolpassword'] = get_string('passwordinvalid', 'enrol_self');
}
}
}
}
return $errors;
// END DEFAULT BLOCK
}
Its validated in the custom self enrolment form
In the function validation() in the file /enrol/self/locallib.php it checks if the password matches and displays an error if not.
UPDATE:
I would probably do this in the validation function
Add the $USER variable at the top
global $DB, $CFG, $USER;
Then check if the user, course and password combination exists in your newly created licence table ;)
$params = array('userid' => $USER->id, 'courseid' => $instance->courseid, 'password' => $data['enrolpassword']);
if (!$DB->record_exists('local_licence_table', $params)) {
$errors['enrolpassword'] = get_string('passwordinvalid', 'enrol_self');
return $errors;
}

$facebook->getUser() returning 0 and showing exception

I am doing login and fetching albums from facebook:
1) Here, first of all the function $facebook->getUser() returning 0
2) If I commented the rest of code i.e. if/else conditions then it going into the catch block and showing exception like :
Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user.
3) I found lots of posts on stackoverflow and google regarding to this and tried almost all but still its not working. Thats why I am sharing the code here.
4) Also I created the new app facebook and tried for it but still problem persist.
Following is my code :
public function facebookapiAction() {
require 'auth/src/facebook.php';
$facebook = new Facebook(array(
'appId' => '3xxxxxxxxxxxxxxxxxxxx7',
'secret' => '6xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx5',
'cookie' => true,
));
return $facebook;
}
public function facebookalbumAction() {
$session = new Zend_Session_Namespace('user');
$facebook = $this->facebookapiAction();
$access_token = $facebook->getAccessToken();
$facebook->setAccessToken($access_token);
$user = $facebook->getUser();
$albumid = $this->_getParam('albumid');
if ($user <> '0' && $user <> '') {
if ($albumid != "") {
$photos = $this->albumlistAction($albumid, $facebook);
} else {
try {
$albumArrInfo = array();
$user_profile = $facebook->api('/me/albums');
} catch (FacebookApiException $e) {
error_log($e);
exit;
}
}
$session->fb_logout = $facebook->getLogoutUrl(array('next' => "http://{$_SERVER['HTTP_HOST']}/register/logout/id/Logout"));
$session->isfb = 1;
} else {
if (isset($_REQUEST['getfurl']) && !(isset($_REQUEST['state']))) {
$loginUrl = $facebook->getLoginUrl(array('display' => 'popup','scope' => 'manage_pages,user_events,email,read_stream,user_photos,offline_access'));
echo $loginUrl;
exit;
}
}
}
public function albumlistAction($albumid, $facebook) {
$photos = $facebook->api("/{$albumid}/photos");
$albumArr = array();
$albumArrInfo = array();
foreach ($photos['data'] as $photo) {
$albumArr['id'] = $photo['id'];
$albumArr['name'] = $photo['name'];
}
return $albumArr;
}
Whats wrong with this code.
Need help.
Sounds like a similar problem I was facing. Bug report is here: http://developers.facebook.com/bugs/238039849657148
Try updating to the latest version of the PHP-SDK (3.2.2).
Try this:
$user = $facebook->getUser();
...
$user_profile = $facebook->api('/'.$user.'/albums');

How to unenroll user from a course with php

Using Moodle 1.9, I have successfully been able to enroll a user via php with
$user = get_record("user", "id", $mqval['id']);
$course = get_record("course", "id", $cid);
if ( ! enrol_into_course($course, $user, 'manuel')) {
} else {
//echo 'success';
}
Now I want to unenroll the user the same way. I tried using unenrol_user, which didn't work. I also tried role_unassign but with no success.
//get instance that can unenrol
$enrols = enrol_get_plugins(true);
$enrolinstances = enrol_get_instances($courseid, true);
$unenrolled = false;
foreach ($enrolinstances as $instance) {
if (!$unenrolled and $enrols[$instance->enrol]->allow_unenrol($instance)) {
$unenrolinstance = $instance;
$unenrolled = true;
}
}
//unenrol the user in every course he's in
$enrolledusercourses = enrol_get_users_courses($userid);
foreach ($enrolledcourses as $course) {
//unenrol the user
$enrols[$unenrolinstance->enrol]->unenrol_user($unenrolinstance, $userid, $roleid);
}
I have modified above code and its working.
//unenrol the user in every course he's in
$enrols = enrol_get_plugins(true);
$enrolledusercourses = enrol_get_users_courses($user->id);
foreach ($enrolledusercourses as $course) {
//unenrol the user
$courseid = $course->id;
$enrolinstances = enrol_get_instances($courseid, true);
$unenrolled = false;
foreach ($enrolinstances as $instance) {
if (!$unenrolled and $enrols[$instance->enrol]->allow_unenrol($instance)) {
$unenrolinstance = $instance;
$unenrolled = true;
}
}
$enrols[$unenrolinstance->enrol]->unenrol_user($unenrolinstance, $user->id, $user->rollid);
}

Categories