I am authenticating XenForo user via php.
My code:
public function Auth($username, $password)
{
$userIDA = $this->getarray("SELECT * FROM xf_user WHERE username='".$username."'");
if($userIDA)
{
define('SESSION_BYPASS', false); // if true: logged in user info and sessions are not needed
require_once('library/XenForo/Autoloader.php');
$AutoLoader = XenForo_Autoloader::getInstance();
$AutoLoader->setupAutoloader('library');
XenForo_Application::initialize('library', '');
XenForo_Application::set('page_start_time', microtime(true));
XenForo_Application::disablePhpErrorHandler(); //
XenForo_Session::startPublicSession(); //
error_reporting(E_ALL & ~E_NOTICE); // Turn off the strict error reporting.
$db = XenForo_Application::get('db');
$result = $db->fetchCol('SELECT user_id FROM xf_user WHERE username='.$db->quote($username));
$user_id = $result[0];
$result = $db->fetchCol('SELECT data FROM xf_user_authenticate WHERE user_id='.$db->quote($user_id));
$data = $result[0];
$auth = NULL;
if(class_exists('XenForo_Authentication_Core12'))
$auth = new XenForo_Authentication_Core12;
else if(class_exists('XenForo_Authentication_Core'))
$auth = new XenForo_Authentication_Core;
$auth->setData($data);
if ($auth->authenticate($user_id, $password))
{
switch (intval($user_id))
{
default:
return 1;
break;
case 1:
return -1;
case 3:
return -1;
break;
}
}
return 2;
}
else return 3;
}
error log:
[12-Aug-2017 20:08:45 UTC] PHP Fatal error: Cannot redeclare class XenForo_Autoloader in /home/*******/*******/library/XenForo/Autoloader.php on line 16
So, please help me, what is wrong
Try using the following code instead,
XenForo_Autoloader::getInstance()->setupAutoloader($forum_directory . '/library');
Related
I want to get and echo a users permission level.
I have a function where the users email is passed, the function then needs to get the users permission level and return it, so it can be echoed on another page.
I imagine the function will look though the database for the passed email, it then finds the users permission and returns with that.
In the 'User.class.php'
public static function permGetter($email)
{
try
{
$db = Database::getInstance();
$stmt = $db->prepare('SELECT permission FROM users WHERE email = :email LIMIT 1');
$stmt->execute([':permission'=>$permission]);
$user = $stmt->fetchObject('User');
if($user !== false)
{
return $permission;
}
}
catch (PDOException $exception)
{
error_log($exception->getMessage());
return false;
}
}
In the 'permRequest.php'
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once("../includes/init.php");
//Get passed from an external program
$email = $_GET['email'];
$pass = $_GET['pass'];
if($email && $pass !== null)
{
// Checks if the user's entered credential matches with those in database
if(Auth::getInstance()->login($email, $pass))
{
//Uses the passed email to get permission level in 'User.class.php'
if(User::permGetter($email))
{
echo 'Permission ' + (int) $permission;
}
}
else
{
//I use level 5 as a debug so i can see when it fails
echo 'Permission 5';
}
}
?>
Database
Here's an example on what my database looks like.
Edit 1
Okay messing about, I think i got closer to the solution.
First, #Lawrence Cherone, thanks for pointing out my mistake in my execute.
Okay I have changed my code in
User.class.php
public static function permGetter($email, $permission)
{
try
{
$db = Database::getInstance();
$stmt = $db->prepare('SELECT permission FROM users WHERE email = :email');
$stmt->execute([':email'=>$email]);
$row = $stmt->fetch(PDO::FETCH_NUM);
$permission = $row['permission'];
}
catch (PDOException $exception)
{
error_log($exception->getMessage());
return false;
}
}
I have made small changes to
permRequest.php
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once("../includes/init.php");
//Get passed from an external program
$email = $_GET['email'];
$pass = $_GET['pass'];
$permission = '';
if($email && $pass !== null)
{
// Checks if the user's entered credential matches with those in database
if(Auth::getInstance()->login($email, $pass))
{
//Uses the passed email to get permission level in 'User.class.php'
if(User::permGetter($email, $permission))
{
echo 'Permission ', $permission;
}
}
}
?>
But now i get an error. The error is this Notice: Undefined index: permission in /classes/User.class.php on line 56
So, I read up on it and it seemed like it should be emptied first, so I empty it in permRequest.php that's why I'm passing it too, but I still get this error after i emptied it?
However if i change
$row = $stmt->fetch(PDO::FETCH_NUM);
to
$row = $stmt->fetch(PDO::FETCH_ASSOC);
/* OR */
$row = $stmt->fetch(PDO::FETCH_BOTH);
I get no error but it simply says my email or password is incorrect, which it isn't I have double and triple checked it.
So I'm confused to which PDO::FETCH_ I should use. I have read this (Click here) and I would say that both ASSOC, BOTH and NUM would fit the purpose.
So why is one giving an error while the two other's simply fails the login?
Edit 2
Found the solution and i have written it as a Answer. Can't accept it for the next two days however.
I moved everything out of the User.class.php and moved it into permRequest.php. This solved my problem for some reason. So my code looks like this now
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL ^ E_NOTICE);
require_once("../includes/init.php");
$email = $_GET['email'];
$pass = $_GET['pass'];
if($email && $pass !== null)
{
if(Auth::getInstance()->login($email, $pass))
{
try
{
$db = Database::getInstance();
$stmt = $db->prepare("SELECT * FROM users WHERE email = :email");
$stmt->execute([':email' => $email]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$sub = $row['permission'];
echo 'Permission ', $sub;
}
catch (PDOException $exception)
{
error_log($exception->getMessage());
return false;
}
}
}
And I don't use the User.class.php for this function.
So my guess is something went wrong when returning $sub when it was in User.class.php
This is more like a debugging problem than an actual question. I have a login script in PHP which should check for user information from a local database and if present, then display them. Or else, redirect them to the Google OAuth2 Login process. The following php files concern the login flow :
google_login.php
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
require('http.php');
require('oauth_client.php');
require('../config.php');
require('StructuredQuery.php');
define("SCOPE", 'https://www.googleapis.com/auth/userinfo.email '.
'https://www.googleapis.com/auth/userinfo.profile' );
$client = new oauth_client_class;
$sq= new StructuredQuery();
// set the offline access only if you need to call an API
// when the user is not present and the token may expire
$client->offline = FALSE;
$client->debug = false;
$client->debug_http = true;
$client->redirect_uri = GOOGLE_REDIRECT_URL;
$client->client_id = GOOGLE_CLIENT_ID;
$application_line = __LINE__;
$client->client_secret = GOOGLE_CLIENT_SECRET;
if (strlen($client->client_id) == 0 || strlen($client->client_secret) == 0)
die('Please go to Google APIs console page ' .
'http://code.google.com/apis/console in the API access tab, ' .
'create a new client ID, and in the line ' . $application_line .
' set the client_id to Client ID and client_secret with Client Secret. ' .
'The callback URL must be ' . $client->redirect_uri . ' but make sure ' .
'the domain is valid and can be resolved by a public DNS.');
/* API permissions
*/
$client->scope = SCOPE;
if (($success = $client->Initialize())) {
if (($success = $client->Process())) {
if (strlen($client->authorization_error)) {
$client->error = $client->authorization_error;
$success = false;
} elseif (strlen($client->access_token)) {
$success = $client->CallAPI(
'https://www.googleapis.com/oauth2/v1/userinfo', 'GET', array(), array('FailOnAccessError' => true), $user);
}
}
$success = $client->Finalize($success);
}
if ($client->exit)
exit;
if ($success) {
// Now check if user exist with same email ID
try {
$result = $sq->getUserInfo($user->id);
if ($result["count"] > 0) {
// User Exist
$_SESSION["name"] = $result["name"];
$_SESSION["email"] = $result["email"];
$_SESSION["clevel"]=$result["clevel"];
$_SESSION["new_user"] = "no";
} else {
// New user, Insert in database
$result = $sq->putNewUserInfo($user->id,$user->name,$user->email);
if ($result===true) {
$_SESSION["name"] = $user->name;
$_SESSION["email"] = $user->email;
$_SESSION["new_user"] = "yes";
$_SESSION["e_msg"] = "";
}
}
$_SESSION["login_type"]="Google";
} catch (Exception $ex) {
$_SESSION["e_msg"] = $ex->getMessage();
}>
$_SESSION["user_id"] = $user->id;
} else {
$_SESSION["e_msg"] = $client->error;
}
header("Location: ".ROOT_DIR."homepage.php");
exit;
?>
StructuredQuery.php
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
require_once 'config.php';
class StructuredQuery{
var $opt;
var $pdo;
function __construct(){
$opt = [
PDO::ATTR_PERSISTENT => FALSE,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$this->pdo = new PDO(DB_DRIVER.":host=".DB_SERVER.";dbname=".DB_NAME, DB_SERVER_USERNAME, DB_SERVER_PASSWORD, $opt);
}
// Cross Site Script & Code Injection Sanitization
function xss_cleaner($input_str) {
$return_str = str_replace( array('<',';','|','&','>',"'",'"',')','('), array('<',':','|','&','>',''','"',')','('), $input_str );
$return_str = str_ireplace( '%3Cscript', '', $return_str );
return $return_str;
}
//SQLInjection detect
function sql_injection_detect($input_query){
try{
$blacklist=array('SELECT','WHERE','UPDATE','DELETE','INSERT','FROM','DROP','MERGE','SET','INSERT','REMOVE','REPLACE','QUERY');
$err_level=0;
foreach($blacklist as $blacklist_item){
if(stripos($input_query,$blacklist_item)!==false){
$err_level++; //Counter for number of blacklist words used. 2 means dangerous. Terminate immediately.
if($err_level==2){
die('Was that an IT joke? Cause I am a 12th grader, not an IT Pro.');
}
}
}
return true;
}catch(Exception $e){
echo 'Exception Occured:',$e->getMessage(),"\n";
die('You\'ve been Terminated');
}
}
function getUserInfo($user_id){
$user_id=xss_cleaner($user_id);
if(sql_injection_detect($user_id)){
$query=$pdo->prepare("select statement");
$query->bindParam(":user_id",$user_id,PDO::PARAM_STR);
$query->execute();
$result=$query->fetch();
$result["count"]=$query->rowCount();
return $result;
}
}
function putNewUserInfo($user_id,$name,$email){
$user_id=$this->xss_cleaner($user_id);
$name=xss_cleaner($name);
$email=xss_cleaner($email);
if(sql_injection_detect($user_id) && sql_injection_detect($name) && sql_injection_detect($email)){
$query=$pdo->prepare("insert statement");
$query->bindParam(":user_id",$user_id,PDO::PARAM_STR);
$query->bindParam(":name",$name,PDO::PARAM_STR);
$query->bindParam(":email",$email,PDO::PARAM_STR);
$query->execute();
return true;
}else{
return false;
}
}
function modifyUserInfo($user_id,$name,$email,$clevel){
$user_id=xss_cleaner($user_id);
$name=xss_cleaner($name);
$email=xss_cleaner($email);
$clevel=xss_cleaner($clevel);
if(sql_injection_detect($user_id) && sql_injection_detect($name) && sql_injection_detect($email) && sql_injection_detect($clevel)){
$query=$pdo->prepare("update statement");
$query->bindParam(":user_id",$user_id,PDO::PARAM_STR);
$query->bindParam(":name",$name,PDO::PARAM_STR);
$query->bindParam(":email",$email,PDO::PARAM_STR);
$query->bindParam(":clevel",$clevel,PDO::PARAM_INT);
$query->execute();
return true;
}else{
return false;
}
}
}
Now the issue that bothers me is this- whenever i press Login With Google, it redirects to google_login.php, well and fine. And then, directly to the homepage as if I am already logged in even though I am not. Even weirder is that it displays my e-mail and my username as blank, even though it says that I am an existing user.
P.S. No, the database does not contain any blank entries and it works fine, I double-checked.
I have build a small website with some php. It works perfectly on my localhost (even without database information it loads the html and css).
However when I put it online I just get a blankpage, no errors, nothing. However when I manually type a page it redirects to the login page (which is good).
Anyone experienced this before?
Thanks
EDIT2: After some debugging advice I got this error
Warning: include_once(classes/users.class.php): failed to open stream:
No such file or directory in
/customers/c/2/9/nicolasdecroos.be/httpd.www/eindwerk/login.php on
line 8 Warning: include_once(): Failed opening
'classes/users.class.php' for inclusion
(include_path='.:/usr/share/php') in
/customers/c/2/9/nicolasdecroos.be/httpd.www/eindwerk/login.php on
line 8 Fatal error: Class 'user' not found in
/customers/c/2/9/nicolasdecroos.be/httpd.www/eindwerk/login.php on
line 9
Edit: Here is the PHP code on the login page
<?php
session_start();
include_once("classes/users.class.php");
$user = new user();
if(isset($_SESSION['loggedin']))
{
header('location: index.php');
}
else
{
if(!empty($_POST))
{
try
{
$user->login($_POST['studentennummer'],$_POST['password']);
}
catch (Exception $error)
{
$message = $error->getMessage();
}
}
}
?>
This is users.class
*Sorry if it's to much code, I'm not sure which part would be the most interesting.
<?php
include_once("classes/db.class.php");
class user
{
private $m_sStudentennummer;
private $m_sPassword;
private $m_sStatus;
public function __get($p_sProperty)
{
switch ($p_sProperty)
{
case 'Studentennummer':
return $this->m_sStudentennummer;
break;
case 'Password':
return $this->m_sPassword;
break;
case 'Status':
return $this->m_sStatus;
break;
}
}
public function __set($p_sProperty, $p_vValue)
{
switch ($p_sProperty)
{
case 'Studentennummer':
$this->m_sStudentennummer = $p_vValue;
break;
case 'Password':
$this->m_sPassword = $p_vValue;
break;
case 'Status':
$this->m_sStatus = $p_vValue;
break;
}
}
public function userCheck($p_sInput)
{
$db = new db();
$sql = "SELECT * FROM users WHERE u_id = '". $p_sInput . "'";
$result = $db->conn->query($sql);
if ($result->num_rows == 0)
{
return "true";
}
else
{
return "false";
}
}
public function login($p_sStudentennummer, $p_sPassword)
{
$db = new db();
$sql = "SELECT * FROM users WHERE u_nr = '".$db->conn->real_escape_string($p_sStudentennummer)."' AND u_pass = '".$db->conn->real_escape_string($p_sPassword)."';";
$result = $db->conn->query($sql);
$rows = $result->fetch_assoc();
$status = "SELECT * FROM users WHERE u_nr = '".$db->conn->real_escape_string($p_sStudentennummer)."' AND u_pass = '".$db->conn->real_escape_string($p_sPassword)."' AND u_group = 'student'";
$statusRes = $db->conn->query($status);
if ($result->num_rows == 1)
{
if ($statusRes->num_rows == 1)
{
$_SESSION['u_id'] = $rows['u_id'];
$_SESSION['loggedin'] = 1;
header('Location: index.php');
}
else
{
$_SESSION['u_id'] = $rows['u_id'];
$_SESSION['loggedin'] = 1;
header('Location: my_events.php');
}
}
else
{
throw new Exception("Username and/or password are invalid.");
}
}
}
?>
Change the error level for the online hosting if you can.
It will display every errors on the screen, but is very useful (for me at least).
<? error_reporting(E_ALL); ?>
Alright,
It was something dumb but I'll post it incase someone has troubles with this.
The map was called "Classes". in the code it was written as "classes".
On localhost it wasn't a problem, but when you put it online it is.
Im trying to create a login script to connect with my myBB forum Database and echo true or false whether the username and password is correct, but I keep getting this error:
Fatal error: Call to a member function escape_string() on a non-object in /home2/tronic/public_html/forum/inc/tronic_login.php on line 76
function validate_password_from_username()
{
$username = $_GET['username'];
$password = $_GET['password'];
global $db, $mybb;
$username = $db->escape_string(my_strtolower($username));
switch($mybb->settings['username_method'])
{
case 0:
$query = $db->simple_select("users", "uid,username,password,salt,loginkey,coppauser,usergroup", "LOWER(username)='".$username."'", array('limit' => 1));
break;
case 1:
$query = $db->simple_select("users", "uid,username,password,salt,loginkey,coppauser,usergroup", "LOWER(email)='".$username."'", array('limit' => 1));
break;
case 2:
$query = $db->simple_select("users", "uid,username,password,salt,loginkey,coppauser,usergroup", "LOWER(username)='".$username."' OR LOWER(email)='".$username."'", array('limit' => 1));
break;
default:
$query = $db->simple_select("users", "uid,username,password,salt,loginkey,coppauser,usergroup", "LOWER(username)='".$username."'", array('limit' => 1));
break;
}
$user = $db->fetch_array($query);
if(!$user['uid'])
{
echo("false");
}
else
{
echo("true");
}
}
http://pastebin.com/KU130cZE
In line 8, you're calling $db->escape_string(my_strtolower($username));. Problem is: $db isn't defined yet, or not an object.
I cannot tell you what it is, as it'S a global variable (bad thing, one should avoid those!), so I cannot tell where it is set and what value it has - but it's clearly not an object, so my best bet is it's either unset/null, or false because some function that is supposed to set it had an error and returned false.
I try to load a session as I want with me into my handler. But the line 8 says that "during the find index" what is the error in my controller? It is a user name that I want to use a database to retrieve the id of the person.
Controller:
<?php
require_once ("View/PersonInfoView.php");
require_once ("Handler/UserHandler.php");
class PersonInfoController{
public function DoPersonInfo(){
$Personinfoview = new PersonInfoView();
$UserHandler = new UserHandler();
$PK = $UserHandler->GetUserID($_SESSION['Person']);
$Person_array = $UserHandler->ListPerson($PK);
$Personinfoview->Personbox($Person_array);
}
}
I set Session :
<?php
require_once ("Handler/Userhandler.php");
require_once ("Controller/LoginController.php");
class DologinHandler{
public function Login(){
if(isset($_REQUEST['is_ajax']))
{
$LoginController = new LoginController();
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$_SESSION['Person'] = $username;
$UserHandler = new UserHandler();
$sign = $UserHandler -> controllDB($username,$password);
if($sign == true)
{
echo 'success';
return true;
}
else
{
echo 'error';
return false;
}
}
}
}
$loginclass = new DologinHandler();
$loginclass->Login();
I'm guessing your $_REQUEST doesn't contain the key Person. Try doing a var_dump() on $_REQUEST to see what it contains.
Other than that, I suggest you implement some kind of error handeling when calling $UserHandler->GetUserID()
For instance.
try {
$PK = $UserHandler->GetUserID($_SESSION['Person']);
} catch(Exception $e) {
echo($e->getMessage());
}
Read about exceptions.