Integrating Single sign on of codoforum in yii framework 1 - php

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.

Related

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

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?

MethodNotAllowedHttpException generated using return back()->withInput() in Laravel 5.4

I've searched the forums and have seen many similar issues but none that seem to address my concern. I believe this is different because:
Form validation is not being used at this point
The form method does not seem to be related (just 1 post action)
The routes are not wrapped in web middleware
Here's what the application is supposed to be doing:
A user (with or without Authentication) views a public page with form (display_event)
The user selects a specific ticket for ordering and is directed to a 2nd form (register_step1)
The user then fills out demographic info for as many tickets as are being ordered
The processing step, if the email address used is of a valid user (in DB) should return to the form in step 2 & 3, populate the fields and flash a message. Otherwise it would perform the save() actions required. (register_step2)
The relevant routes from web.php are here:
Route::get('/events/{event}', 'EventController#show')->name('display_event');
Route::post('/register/{event}', 'RegistrationController#showRegForm')->name('register_step1');
Route::post('/register/{event}/create', 'RegistrationController#store')->name('register_step2');
The relevant portions of the RegistrationController.php are here:
public function showRegForm (Request $request, $id) {
// Registering for an event from /event/{id}
$ticket = Ticket::find(request()->input('ticketID'));
$quantity = request()->input('quantity');
$discount_code = request()->input('discount_code');
$event = Event::find($ticket->eventID);
return view('v1.public_pages.register', compact('ticket', 'event', 'quantity', 'discount_code'));
}
And:
public function store (Request $request) {
$event = Event::find(request()->input('eventID'));
if(Auth::check()) {
$this->currentPerson = Person::find(auth()->user()->id);
}
// set up a bunch of easy-reference variables from request()->input()
$email = Email::where('emailADDR', $checkEmail)->first();
if(!Auth::check() && $email === null) {
// Not logged in and email is not in database; must create
$person = new Person;
// add person demographics from form
} elseif(!Auth::check() && $email !== null) {
// Not logged in and email is in the database;
// Should force a login -- return to form with input saved.
flash("You have an account that we've created for you.
Please attempt to login and we'll send you a password to your email address.", 'warning');
return back()->withInput();
} elseif(Auth::check() && ($email->personID == $this->currentPerson->personID)) {
// the email entered belongs to the person logged in; ergo in DB
$person = $this->currentPerson;
// add person demographics from form
} elseif(Auth::check() && ($email->personID != $this->currentPerson->personID)) {
// someone logged in is registering for someone else in the DB
$person = Person::find($email->personID);
// add person demographics from form
} else {
// someone logged in is registering for someone else NOT in the DB
$person = new Person;
// add person demographics from form
}
// do more stuff...
$reg = new Registration; (set up a registration record)
}
I took the advice indicated in #apokryfos's comment and changed the form parsing-then-display script from a POST to a get.
redirect()->back() is, apparently, always a method=get and that was the cause of the MethodNotAllowedHttpException. In my ~2 weeks using Laravel, I hadn't yet come across that fact.

Codeigniter Auth system based on device

I am kind of newbie around here so hope i am doing fine what am i doing.
I started working with Codeignter recently and trying to build a secured login to restrict access from three devices only.
On login
I am trying to add a never-expiring "device_id" cookie upon successful authentication. That cookie would be a a unique string and store it into database
And if the user has aleady three devices stored to be rejected.
If the user has available devices slots, this to be recorded and added to its stack.
Basicly i want to allow access if the user has avail slots or the cookie arleady exists.
Have any ideea where should i start or there is a Codeigniter library ?
The code from my control that alows and valides login is:
function login()
{
if ($this->session->userdata('logged_in'))
{
$logged_in_user = $this->session->userdata('logged_in');
if ($logged_in_user['is_admin'])
{
redirect('admin');
}
else
{
redirect(base_url());
}
}
// set form validation rules
$this->form_validation->set_error_delimiters($this->config->item('error_delimeter_left'), $this->config->item('error_delimeter_right'));
$this->form_validation->set_rules('username', lang('users input username_email'), 'required|trim');
$this->form_validation->set_rules('password', lang('users input password'), 'required|trim|callback__check_login');
if ($this->form_validation->run() == TRUE)
{
if ($this->session->userdata('redirect'))
{
$redirect = $this->session->userdata('redirect');
$this->session->unset_userdata('redirect');
redirect($redirect);
}
else
{
$logged_in_user = $this->session->userdata('logged_in');
if ($logged_in_user['is_admin'])
{
redirect('admin');
}
else
{
redirect(base_url());
}
}
}
// setup page header data
$this->add_css_theme( 'login.css' );
$this->set_title( lang('users title login') );
$data = $this->includes;
// load views
$data['content'] = $this->load->view('user/login', NULL, TRUE);
$this->load->view($this->template, $data);
}
it's not a good idea to write your system ....you can not secure your auth system from session hijacking (when session_id not change in long period) , dos attack , ddos attack , etc very easliy .... it's better to use early written system like auth_ion ....
you can find authentication library for code igniter in :
https://github.com/bcit-ci/CodeIgniter/wiki/Contributions#libraries
i preffer ion_auth in that list ...

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!

Redirect to referer url in codeigniter

In messaging system of my project when you get a message from a user you a email alert saying that the another user has sent a message to view the message click here (i.e the url of message) So if the user is not logged in to system he gets redirect to login page and after login it should get back to the referer url. I have made a basecontoller in core folder and extending the CI_controller the authenticating code is as follows.
function authenticate($type = 'user')
{
if($type == 'user')
{
if($this->user_id)
{
// user is logged in. check for permissions now
}
else
{
// user isnt logged in. store the referrer URL in a var.
if(isset($_SERVER['HTTP_REFERER']))
{
$redirect_to = str_replace(base_url(),'',$_SERVER['HTTP_REFERER']);
}
else
{
$redirect_to = $this->uri->uri_string();
}
redirect('user/login?redirect='.$redirect_to);
exit;
}
}
if($type == 'admin')
{
if($this->session->userdata('admin_id') && $this->session->userdata('user_type') ==5)
{
// Admin is logged in
}
else
{
redirect('admin/login');
exit;
}
}
}
The referer url is "http://example.com/project/pm/view_conversation?id=11"
now the problem is I am getting referer url till view_conversation and not able to get the id part.
Any suggestion ?
Thank you.
This can help:
CI 2+
https://www.codeigniter.com/userguide2/libraries/user_agent.html
CI 3+
http://www.codeigniter.com/userguide3/libraries/user_agent.html
Below solution is for Codeigniter version 3
$this->load->library('user_agent');
if ($this->agent->is_referral())
{
echo $this->agent->referrer();
}
UPDATE: interesting and useful information on how to obtain referrer information with the same user_agent library
https://www.tutorialandexample.com/user-agent-class/
How about just
redirect($_SERVER['HTTP_REFERER']);
Using php's $_SERVER global variable.
This worked for me!
Put that code in your Login Controler
function index() {
$this->load->library('user_agent'); // load user agent library
//Set session for the referrer url
$this->session->set_userdata('referrer_url', $this->agent->referrer() );
}
After Login Redirection Code
// user is authenticated if referrer is there
if( $this->session->userdata('referrer_url') ) {
//Store in a variable so that can unset the session
$redirect_back = $this->session->userdata('referrer_url');
$this->session->unset_userdata('referrer_url');
redirect( $redirect_back );
}
Because you have double question mark in the url, the browser ignores the url part after the second one. Use urlencode for you redirect part, like so:
redirect('user/login?redirect='.urlencode($redirect_to));
I've tested it out and it works this way.
By default CI is configured to ignore the query part of the URL (the part after the '?').
See: http://codeigniter.com/user_guide/general/urls.html

Categories