Use joomla user table with cakephp - authentication

i have working joomla project (domain.kz).
and i need to build new independent project on subdomain (newapp.domain.kz)
but i want to use joomla user table. (to let user auth with joomla logins)
can i declare in user model the joomla jos_users fields
is it possible to use 2 DB (old one for auth, the new one for new app)

Create a new database config in app/config/database.php, then create your model as normal:
var $joomla_connection = array('driver' => 'mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
'password' => 'password!',
'database' => 'joomla_db',
'prefix' => 'jos_'); // I think this is correct
class User extends AppModel {
var $name = 'User';
var $useDbConfig = 'joomla_connection';
//your code here
//....
}

you will might experience problems with Auth when you login with the "security_salt" and "cipher" from cake against the user login data, that are created through joomla.
if Joomla saves md5 encrypted passwords you can modify cakestandard encryption with this:
change hash function - cake cookbook

Related

How to send user login credentials after user registers

I am using laravel's default login and registration. I have successfully set up authentication, however I would like to send user's username and password to the emails they used during registration. How can I achieve this?
You can initiate a mail to user after you validated input received and before your create functions of your register controller present in
$email = new UserRegisterData(new User(['password' => $user->password, 'name' => $user->name]));
To do this you need to rewrite
protected function validator(array $data)
function in your register controller and modify that with this mail. as
protected function validator(array $data)
{
$email = new UserRegisterData(new User(['password' => $user->password, 'name' => $user->name]));
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:customers',
'password' => 'required|min:6|confirmed',
]);
}
once you hashed your password in create function, i think it can't be read. Also check if any security issue it may generate. Also you need to create mail as 'UserRegisterData' and add necessary code in it.

Get user details in Yii framework

I am new to Yii framework and I want to get the user details of current logged in user like userid, username & his avatar and want to add that data in the head tag. I am using basic version on Yii.
How can I get this details?
Yii handles user data in the session using the IdentityInterface.
Let's go step by step.
You can create a class, call it User, which implements IdentityInterface. If connected with the database you can extend it to ActiveRecord, totally up to your architecture.
class User extends ActiveRecord implements IdentityInterface
{
...
}
Add the configuration details into the config file, main.php. I work on advance template, thus its located into fronted/config. Check it for the basic one.
'components' => [
...
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-frontend', 'httpOnly' => true],
],
....
];
This tells the app to get the user session details form the common\model\User class. Its in common as I use the same class for backend and the frontend, which is not the case in the basic template.
Make user login into the app
When you get the object of the User class, with valid username and password, use the following code to login the user.
Yii::$app->user->login($user);
To get the value of the user you have following sample
Yii::$app->user->isGuest - This tells you whether the user is logged in or not.
Yii::$app->user->id - Get the id of the user
Yii::$app->user->identity->name - Yii::$app->user->identity will give you access to the entire object of the User class. If you have any other attributes, use the identity and get those. Example, you can have 'avatar', which stores the avatar url, you can get it by Yii::$app->user->identity->avatar.
Finally to logout
Yii::$app->user->logout();
Use the setState method.
In your UserIdentity.php:
public function authenticate()
{
$user=User::model()->find('LOWER(username)=?',array(strtolower($this->username)));
if($user===null)
$this->errorCode=self::ERROR_USERNAME_INVALID;
else if(!$user->validatePassword($this->password))
$this->errorCode=self::ERROR_PASSWORD_INVALID;
else
{
$this->_id=$user->id;
$this->username=$user->username;
$this->setState("userid",$user->user_id);// set States like this
$this->setState("username",$user->username);
$this->setState("avatar",$user->avatar );
$this->errorCode=self::ERROR_NONE;
}
return $this->errorCode;
}
Now anywhere get these like:
$userid = Yii::app()->user->getState('userid');

Laravel 5 db:seed the username and password, but not authenticating on login

I have implemented Database seeder to seed in user (default) credentials.
Admin::create(['name' => 'Super Admin', 'email' => 'admin#demo.in', 'password' => bcrypt('password') ]);
After running seed, I got success message. But when I try to make login, it says your credential are not matching. Is there any particular reason for this. Can't we seed user data with bcrypt??
If we talk about the default AuthController of Laravel 5 obviously no you can't:
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
If you have a look at the create() function you can see that the data submitted as password is automatically bcrypted. So if you bcrypt the password too it is bcrypted a second time.
Alright, some key points :
If you're using the User model for seeding, make sure that you'r not
hashing the password twice that could happen if you have a mutator
set in your model for the password column.
Be aware of your saved passwords in the browser, prefer writing
explicitly your username and password (in this case).
Finally check if there is no typo in your username/email or password. (that was my case 🤦‍♂️)
I inserted the data into my user table from my seeder as so:
DB::table('users')->insert([
'Email' => 'admin#QualityBooks.co.nz',
'Name' => 'Administrator',
'PhoneNumber' => '00000',
'Password' => bcrypt('P#ssw0rd'),
'isEnabled' => true,
'isAdmin' => true
]);
This works for me and I am able to log in while using the default auth controller.

Laravel 5 multiple authentication

How can you set up multiple authentication in Laravel 5. Out of the box you can only set up 1 authentication. What if I have a customers table and an admin table and wish to set up authentication for each - each authenticated type of user should be restricted from viewing or accessing admin pages and vis versa?
* UPDATE *
I've created a users table which holds information common to both a jobseeker and recruiter i.e. name, password etc.
I've created a roles and role_user table
I've created two separate tables to hold jobseeker_profile and recruiter_profile
How can you authenticate a user with a role of type jobseeker using the following routes?
Route::get('jobseeker/login', 'Auth\AuthController#getLogin');
Route::post('jobseeker/login', 'Auth\AuthController#postLogin');
Route::get('recruiter/login', 'Auth\AuthController#getLogin');
Route::post('recruiter/login', 'Auth\AuthController#postLogin');
And how can you secure routes once authenticated - in the following how is the middleware going to know the type of user:
Route::get('jobseeker/profile', ['middleware' => 'auth', 'uses' => 'JobseekerProfileController#show']);
Route::get('jobseeker/profile/update', ['middleware' => 'auth', 'uses' => 'JobseekerProfileController#updateProfile']);
class JobseekerProfileController extends Controller {
public function updateProfile()
{
if (Auth::user())
{
// Auth::user() returns an instance of the authenticated user...
}
}
}
Laravel 5 authentication controller uses the following trait -would you edit the trait with your answer or create a new authentication controller with your answer below?
trait AuthenticatesAndRegistersUsers {
public function postLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email', 'password' => 'required',
]);
$credentials = $request->only('email', 'password');
if ($this->auth->attempt($credentials, $request->has('remember')))
{
return redirect()->intended($this->redirectPath());
}
return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors([
'email' => 'These credentials do not match our records.',
]);
}
}
You may create a roles table in your db assign role to every user accordingly and then at the time of login check what role a user have and then you can redirect/show pages accordingly. No need to create separate tables for every type of user.
Edited answer
if(Auth::attempt(['email' => $request->email, 'password' => $request->password]))
{
//using role with an expectation that you have one relation method named role defined in User model
//and roles table stores user type as name
if(Auth::user()->role->name == 'admin')
{
return redirect()->to('/administrator/dashboard');
}
elseif(Auth::user()->role->name == 'jobseeker')
{
return redirect()->to('jobseeker/dashboard');
}
}
You can achieve multiple authentication by this package
https://packagist.org/packages/sarav/laravel-multiauth
For more detailed explaination check my previously return answer here
How to use authentication for multiple tables in Laravel 5

How to do a Sign Up with OAuth (facebook, twitter, google)?

I use Laravel (5) as my php framework, it recently added a library for social authentication (facebook, google, twitter and github).
I've been wondering how would you do a Sign Up with OAuth, a login can easily be done by getting the user's email via OAuth, checking if it exists in your DB, and if it does, then log in that user. But how would you do the Sign Up?
Mathius - I've recently been working on a site doing something similar to what you've described and this is what has worked for me:
public function syncUserDetails($userData)
{
// First I check to see if there is a user in the DB
// with the oAuth email address
if ( $user = $this->user->where('email', $userData->email)->first() )
{
// If there is a user, I simply update their local info
// with what is on their oAuth account
$user->token = $userData->token;
$user->google_id = $userData->id;
$user->name = $userData->name;
$user->avatar = $userData->avatar;
$user->first_name = $userData->user['given_name'];
$user->last_name = $userData->user['family_name'];
$user->save();
return $user;
}
// Otherwise, if the user doesn't already exist,
// I create them in my local user's DB
return $this->user->firstOrCreate([
'email' => $userData->email,
'token' => $userData->token,
'google_id' => $userData->id,
'name' => $userData->name,
'avatar' => $userData->avatar,
'first_name' => $userData->user['given_name'],
'last_name' => $userData->user['family_name']
]);
}
This is what I'm using to log in a user. However, you could just as easily run this alongside your regular Laravel login method.