Joomla PHP API check if user is activated in external authentication script - php

I have an external Joomla authenticator script, but it turns out that it ignores if the user didn't activate, and it even ignores if the user is blocked.
I've used the following script with some slight modifications, but the basics are the same:
Joomla 3 External authentication script
Here's my code:
...
if ($result)
{
$match = JUserHelper::verifyPassword($credentials['password'], $result->password, $result->id);
if ($match === true)
{
// Bring this in line with the rest of the system
$user = JUser::getInstance($result->id);
//perform the login action
$error = $app->login($credentials);
$logged_user = JFactory::getUser();
if($logged_user->block == 1 && $logged_user->activation) //some kind of check that's not working basically
{
echo $credentials['username'];
}
}
else
{
// Invalid password
die('');
}
} else {
// Invalid user
die('');
}
You can see that I tried playing around with the 'block' and 'activation' properties of the user object (as seen here) but it wasn't working properly.
What is the specific property (or properties) that I have to check, to deduct, whether a user that is trying to sign-in via this script is activated or not?

Related

Authenticating remotely validated user credentials for TYPO3 backend

I need a bit help in login in a backend user whos credentials have been verified by a remote server. The actual user and all its permissions are set in TYPO3, but the password is stored on a remote server.
So far I've created a small extension, that redirects the backend login to my Login provider:
$GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['backend']['loginProviders'][1433416747]['provider'] = \User\MyExtension\Hooks\LoginProvider::class;
where I check the username and password combination on the remote server.
class LoginProvider implements LoginProviderInterface
{
public function render(StandaloneView $view, PageRenderer $pageRenderer, LoginController $loginController)
{
$view->setTemplatePathAndFilename(GeneralUtility::getFileAbsFileName('EXT:my_extension/Resources/Private/Templates/BELogin.html'));
// Check request
if (
isset($_POST['login_status'])
&& $_POST['login_status'] == 'login'
&& !empty($_POST['username'])
&& !empty($_POST['p_field'])
&& $_POST['interface'] == 'backend'
) {
// Get EXT connection data from settings
$EXT_CONFIG = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['my_extension']);
$this->extServer = $EXT_CONFIG['extServer'];
$this->extDC = $EXT_CONFIG['extDC'];
// Assign received login data
$this->username = GeneralUtility::_GP('username');
$this->password = GeneralUtility::_GP('p_field');
// Try to authenticate
if ($this->checkCredentials()) {
// #TODO: Need to log in the verified user credentials!
}
}
}
private function checkCredentials()
{
// Check if local user exists
$local = $GLOBALS['TYPO3_DB']->exec_SELECTcountRows("uid", "be_users", "username='{$this->username}' AND disable=0") ?? 0;
// Check credentials and recieve user object if correct, or false if wrong
if ($local > 0) {
$ext = new EXT($this->extServer, $this->extDC);
$this->extUser = $ext->authorize($this->username, $this->password);
}
return $this->extUser ? true : false;
}
}
Now I would need to log in the verified user, but can't understand how.
PS: I already found BackendUserAuthentication, but that only works once the user is already authenticated (or I don't know how to use).
A LoginProvider is only for rendering a different login form (e.g. for openID, which does not need a password field).
You need to implement an authentication service: https://docs.typo3.org/typo3cms/Typo3ServicesReference/Authentication/Index.html

Integrating Single sign on of codoforum in yii framework 1

I have just installed codoforum (https://codoforum.com)
and want to use this feature https://codoforum.com/documentation/implementing-codoforum-sso
which consist of integrating Single Sign on in my website.
The website I which to integrate the forum into it is using Yii 1 Framework, I am not familiar with it unfortunately.
Following the documentation of codoforum, I filled in the configuation form and enabled the SSO plugin, what I should do now is complete the file client.php here : https://github.com/evnix/codoforum-sso.
Especially those lines :
if (USER_IS_LOGGED_IN) {
$account['uid'] = USERID; //Your logged in user's userid
$account['name'] = USERNAME; //Your logged in user's username
$account['mail'] = EMAILID; //Your logged in user's email id
$account['avatar'] = ''; //not used as of now
}
I filled in those filled manually and it worked, It detects if I am already connected to yii1 website and connect me to the forum using the email I provided.
What I want now is to get those information using the session, I put the file clien.php in the root of my website mywebsite.com/client.php
I have done some research and I found that this method in siteController is responsible for logging :
public function actionLogin() {
$model = new LoginForm;
// if it is ajax validation request
if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
echo CActiveForm::validate($model);
Yii::app()->end();
}
// collect user input data
if (isset($_POST['LoginForm'])) {
$model->attributes = $_POST['LoginForm'];
// validate user input and redirect to the previous page if valid
if ($model->validate() && $model->login()) {
if (Yii::app()->session['type'] == 1 ) {
$this->redirect(Yii::app()->homeUrl . 'administration/team');
}else if (Yii::app()->session['type'] == 2 ) {
$this->redirect(Yii::app()->homeUrl . 'agenda');
} else {
$this->redirect(Yii::app()->homeUrl);
}
}
}
// display the login form
$this->render('login', array('model' => $model));
}
I have tried to add this code :
session_start();
$_SESSION['username']=$model->username;
(after : if ($model->validate() && $model->login()))
and use $_Session in the file client.php but it didn't work.
The problem is that I have no idea how yii1 framework work, and it will take me sometime to be familiar with it, I know that there is session in Yii1, but I don't know how to use it and where to put the file client.php and how can I make it detect the Yii Session.
But if I can use the global session it would be better.
Thank you so much for your time and your answer.

How to implement wordpress login user via user id

I have being trying to implement wordpress login with just the user id.
Here is my code, but it does not work. The code does not log the user in.
// check if user has an account...
$details = get_user_by("email", $user->emailAddress);
//check user if not empty...
if ($details != null) {
// create a cookie and log user in...
wp_set_current_user($details->ID, $details->user_login);
wp_set_auth_cookie($details->ID);
do_action('wp_login', $details->ID);
//redirect to homepage...
header("Location: " . site_url());
}
Well the documentation states that the function get_user_by() returns false on failure and user object in case of success but in your code you are checking for NULL, so perhaps you can try for this:
if (is_object($details)) {
//your code
}
or
if ($details != false) {
//your code
}

When using CodeIgniter + Facebook PHP SDK: getUser() always returns 0

I am attempting to use the Facebook PHP SDK in conjunction with CodeIgniter to allow users to login to my site using Facebook Connect. No matter what I try, getUser() always returns 0, even after (apparently) successful authentication via Facebook.
CodeIgniter version: 2.1.3
Facebook PHP SDK version: 3.2.2
I have created a config file, facebook.php, in the application/config folder and I am loading the Facebook PHP SDK via CodeIgniter's $this->load->library(...) method. The library is indeed getting loaded and I can successfully call many of the get...() methods including getAccessToken(), getAppId() and getAppSecret(), all of which return their expected values.
Here is a stripped down version of my login controller: (note that I also provide an alternate method of logging in via email, hence the CodeIgniter session code sprinkled throughout)
class Login extends CI_Controller {
public function __construct()
{
//Call parent constructor
parent::__construct();
//Magic sauce - not sure if this is required but a lot of other people
//are recommending it to be included (happy to remove it if necessary)
parse_str($_SERVER['QUERY_STRING'], $_REQUEST);
//Load facebook library
$facebook_config = $this->load->config('facebook');
$this->load->library('facebook', $facebook_config);
}
public function index()
{
//Check if user is logged in
$user_id = $this->session->userdata('user_id');
$is_logged_in = $this->session->userdata('is_logged_in');
if(($is_logged_in) && ($user_id != 0)) {
//Logged in - redirect to game
redirect('game');
} else {
//Not logged in
//Get facebook login url
$facebook_data = array(
'redirect_uri' => 'hxxp://xxxxxxxx.com/facebook_login/',
'scope' => 'email'
);
$data['facebook_login_url'] = $this->facebook->getLoginUrl($facebook_data);
//Redirect to login form
$this->load->view('login/login_form', $data);
}
}
public function facebook_login()
{
//Always returns 0!! Even after authenticating via facebook!
$facebook_user_id = $this->facebook->getUser();
if ($facebook_user_id) {
try {
$user_profile = $this->facebook->api('/me');
print_r($user_profile);
} catch (FacebookApiException $e) {
echo $e->getMessage();
}
} else {
echo "Could not log in with Facebook";
}
}
}
The stripped down view (login_form.php) is as follows:
<html>
<head>
<title>Facebook Connect Test</title>
</head>
<body>
<a href='<? echo $facebook_login_url; ?>'>Login with Facebook</a>
</body>
</html>
I have a route that redirects hxxp://xxxxxxxx.com/facebook_login to the login/facebook_login method, which is working.
I am running this code on a live development server.
My current flow is as follows:
Load hxxp://xxxxxxxx.com/ (Routes to login controller, which loads login_form view)
Click "Login with Facebook" link
Facebook asks me to login (which I do)
Facebook asks me to give permission to my app (which I do)
Facebook redirects me to the url specified in the redirect_uri parameter, which is identical to the one on the app settings page
And here's where it all goes wrong. The $this->facebook->getUser() method ALWAYS returns 0, even after authentication.
I have been scouring the Facebook developer documentation and everywhere else on the internet I can think of trying to find an answer to this. I have come across many posts similar to this and have tried to apply the solutions suggested, but to no avail.
What am I doing wrong?
The getCode() method in base_facebook.php uses the $_REQUEST global to store data. PHP 5.3.0 and greater uses the "request_order" param in php.ini, and by default $_REQUEST does not contain Cookie variables.
Per php.net (http://php.net/manual/en/ini.core.php#ini.request-order):
"This directive describes the order in which PHP registers GET, POST and Cookie variables into the _REQUEST array. Registration is done from left to right, newer values override older values.
If this directive is not set, variables_order is used for $_REQUEST contents.
Note that the default distribution php.ini files does not contain the 'C' for cookies, due to security concerns."
So it looks like your options are to modify the getCode() method like Max Power did above, or update your php.ini and add the "C" value to the request_order setting.
I managed to solve my problem. The questions linked to by Qweick and Stéphane Bruckert had the solution. The problem lies in the getCode() function of the base_facebook.php file.
The getCode() function needs to be modified. The modifications I used are listed below.
Existing non-working code:
protected function getCode() {
if (isset($_REQUEST['code'])) {
if ($this->state !== null &&
isset($_REQUEST['state']) &&
$this->state === $_REQUEST['state']) {
// CSRF state has done its job, so clear it
$this->state = null;
$this->clearPersistentData('state');
return $_REQUEST['code'];
} else {
self::errorLog('CSRF state token does not match one provided.');
return false;
}
}
return false;
}
Modified working code:
protected function getCode() {
$server_info = array_merge($_GET, $_POST, $_COOKIE);
if (isset($server_info['code'])) {
if ($this->state !== null &&
isset($server_info['state']) &&
$this->state === $server_info['state']) {
// CSRF state has done its job, so clear it
$this->state = null;
$this->clearPersistentData('state');
return $server_info['code'];
} else {
self::errorLog('CSRF state token does not match one provided.');
return false;
}
}
return false;
}
The getUser() call now returns a valid user Id and the Facebook API calls now return valid data.
Thanks to everyone that helped point me in the right direction!

Codeigniter View not Loading

I have an installation of Codeigniter, IonAuth + Hybridauth which I am reworking so my users can choose their own username instead of generating one using the first and last names returned by facebook.
So in my code below I check to see if a username was posted, if not I want to load the choose_username view but for some reason the view is not loading and its completely skipping that section which is why I added die('Why no view')
Update: This first piece of code runs fine in a new controller
Checkout the code here:
if(isset($_POST['username'])){
$username = $this->input->post('username', TRUE);
die($username);
}else{
$this->data['message'] = 'Please choose a username.';
$this->data['template'] = 'guests/partials/choose_username';
$this->load->view('guests/template/standard', $this->data);
die('Why no view?');
};
Longer version:
function login_provider($provider = '')
{
if(empty($provider)) redirect();
try
{
// create an instance for Hybridauth with the configuration file
$this->load->library('HybridAuthLib');
if ($this->hybridauthlib->serviceEnabled($provider))
{
// try to authenticate the selected $provider
$service = $this->hybridauthlib->authenticate($provider);
if ($service->isUserConnected())
{
// grab the user profile
$user_profile = $service->getUserProfile();
////////////
//var_dump($user_profile);
//die();
////////////
$provider_uid = $user_profile->identifier;
if($this->ion_auth->login_by_provider($provider,$provider_uid))
{
$data['user_profile'] = $this->ion_auth->user_by_provider();
//$this->load->view('auth/user_profile',$data);
$user = $this->ion_auth->user()->row();
//Redirect to custom subdomain
$url = explode('://',site_url());
if (strpos(site_url(),$user->username) !== false) {
redirect($url[0].'://'.str_replace('www','',$url[1]).'dashboard','refresh');
}
else{
redirect($url[0].'://'.$user->username.str_replace('www','',$url[1]).'dashboard');
};
}
else
{ // if authentication does not exist and email is not in use, then we create a new user
//Check if username was posted
if(isset($_POST['username'])){
$username = $this->input->post('username', TRUE);
die($username);
}else{
$this->data['message'] = 'Please choose a username.';
$this->data['template'] = 'guests/partials/choose_username';
$this->load->view('guests/template/standard', $this->data);
die('Why no view?');
};
So when I run the above code, all i get is a blank page with: Why no view.
As above, usually when I run into this sort of issue it's from a bug in the view code.
Also, I don't know what, is actually being passed by this post in the event of there not being username data but you might want to also be checking for an empty value for username. This is probably not the issue but it would be good to confirm that the initial if is evaluating the way you expect.

Categories