cakephp3.0 Authentication - authorization

Hey In authentication of cakephp3.0 I am facing some problem Hey how can i create an authentication based on patient table and patient controller like url/patient/login I have controller and model and form ready but when I go to login page it always search for query from usertable by default when I am trying to add this code in Patientcontroller :
$this->Auth->config('authenticate', [
AuthComponent::ALL => ['userModel' => 'Members'],
'Basic',
'Form']);
I am getting this error :
Error: Class 'App\Controller\AuthComponent' not found
File D:\xampp\htdocs\hwapp\src\Controller\PatientController.php
Line: 34``

Please read this section of the documentation: http://book.cakephp.org/3.0/en/controllers/components/authentication.html#configuring-authentication-handlers
It explains how to use other table for handling login and how to tell the AuthComponent to use anther controller and action to handle the logic.

Related

Common authentication table between Yii2 advance and Laravel 5.3

I have already one application built using Yii2 advance and working perfectly.
Now, client's requirement is to create new separate (but related with first) application using Laravel 5.3 and this new system must use the same database of Yii2.
A user should be able to login into both the application.
So, I'm curious is it even possible?
Any help would be appreciated.
Thanks,
Parth vora
Finally, I am able to achieve what I wanted.
So, here are the steps you need follow in your Laravel in order to login into Laravel application using auth table of Yii2:
Yii2 uses "user" name for the auth table, whereas Laravel uses "users".
So add this into your User model:
protected $table = "user";
Yii2 uses "password_hash" field to store the user password, whereas Laravel uses "password".
So add this into your User model:
public function getAuthPassword()
{
return $this->password_hash;
}
Yii2 uses "auth_key" field to store the user's remember token, whereas Laravel uses "remember_token". You also need to increase size of this field from 32 to 100, otherwise you will get an error upon logout.
So add this into your User model:
public function getRememberTokenName()
{
return 'auth_key';
}
You also need to increase the size of 'auth_key' field from 32 to 100, otherwise you will get an error upon logout.
Yii2 uses "int(11)" for created_at and updated_at field type, whereas Laravel uses "timestamp" type.
So add this into your User model:
protected $dateFormat = 'U';
Hope it might helpful to someone.
Thanks

Set A Role To User Programmatically without RBAC?

I don't use RBAC to validate users. I wouldn't mind using it if it's possible, but I don't think it is. Reason being, I use a REST API to validate users. I have this in my authenticate() function:
$API = new API();
$user = $API->getAccountDetailsByEmail($this->username);
if($user->password !== md5($this->password) ) {
// Validated
}
I want the user to also be assigned a role at this step. Which is why I tried the following below the above:
$this->setState('roles', 'admin');
But this doesn't work at all. I still get:
Error 403: You are not authorized to perform this action.
When I go to the page I am trying to make admin accessible. How do I programmatically set a user as an admin?
Am I missing something, or is there an easy way to assign a role to a user that was authenticated?
The CAccessControlFilter relies on the CWebUser::checkAccess() function. This function is called with the name of the role as a parameter. If you do not want RBAC then the easiest you could do is write your own CWebUser derived class and implement your own checkAccess.
You can activate this class in your config file by adding the "user" component:
'components'=> array
(
'user' => array
(
'class' => 'MyWebUser',
),
),
You could for example set a list of roles in the users' session and have the function check if the user has that role. Although I would advise against using the session to store roles (the database is beter) using setState is definitely a bad idea. IIRC this sets a cookie on the user side and a bit of an inventive user could figure out how to abuse this.
If your action rules are
array('allow',
'actions'=>array(
'myAction',
),
'users'=>array('#'),
'roles'=>array('admin'),
),
Then change them to:
array('allow',
'actions'=>array(
'myAction',
),
'users'=>array('#'),
'expression'=>'$user->getState("roles")=="admin"',
),
The roles parameter for action rules is for use ONLY with RBAC. So you need to do your validation differently if you aren't using RBAC.
If that isn't your issue, then please provide more details about what you are trying and what your access rules look like.

SimpleMembership updating the "isconfirmed" flag

My Users table (the one that I created) has the following columns:
UserId,UserName,FirstName,LastName,DOB
After I ran this command
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "Users", "UserId", "UserName", autoCreateTables: true);
it created the required simple membership tables for me.
How would I go about "UnConfirming" an user or setting the "IsConfirmed" flag to false in the webpages_Membership using the new SimpleMembership API?
(Earlier, before going to simplemembership using the "Membership" class I could update an user using the api call : Membership.UpdateUser( user );)
I can't answer your question directly since I couldn't figure out a way to 'unconfirm' an account either. What I ended up doing, however, may help whoever finds this question.
I basically use Roles as a gatekeeper. Whenever I create a new account I add that user to a "User" role:
Roles.AddUserToRole(newUser.Username, "User");
I use the Authorize attribute to restrict access to my controllers (and use [AllowAnonymous] for actions that I want to be public -- like RegisterUser, for example). Then, inside each action I add a method to restrict access to only users that are in the "User" role.
if (!Roles.IsUserInRole(role))
{
throw new HttpResponseException(
new HttpResponseMessage(HttpStatusCode.Unauthorized));
}
NOTE: I'm using Web API, but if you're using MVC you should have a much easier time. Instead of manually checking if a user is in a role in each action you can just use the authorize attribute:
[Authorize(Roles = "User")]
When I want to "UnConfirm" a user I just remove them from the "User" role.
Roles.RemoveUserFromRole(user.Username, "User");
This way if a user comes crawling back I can just reactivate their account by adding them back as a User.
What I ended up doing was updating that table directly via a SQL query. Not sure if thats the recommended way of doing it, but that seemed to work for me.
(Thanks for your suggestion too).
Look at this blog post on adding email confirmation to SimpleMembership registration process, which covers how the confirmation process works. The cliff notes are that when you create a new user you set the flag that you want to use confirmation like this.
string confirmationToken =
WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { Email = model.Email }, true);
When you do this the CreateUserAndAccount method returns a unique token that you can put in an email with a link so the user can confirm that they gave you a valid email address. When they click on the link it passes the token in the URL and the controller action can then confirm the token like this.
[AllowAnonymous]
public ActionResult RegisterConfirmation(string Id)
{
if (WebSecurity.ConfirmAccount(Id))
{
return RedirectToAction("ConfirmationSuccess");
}
return RedirectToAction("ConfirmationFailure");
}
The ConfirmAccount method checks if there is an uncomfirmed token that matches in the database and if there is it sets the isConfirmed flag to true. The user will not be able to logon until this is set to true.
set requireConfirmationToken to be true: (The 4th value shown below)
WebSecurity.CreateUserAndAccount(viewModel.UserName, viewModel.Password, null, true);
Source
http://www.w3schools.com/aspnet/met_websecurity_createuserandaccount.asp

Where should I place the code with roles in Yii framework?

Here's the code I found in Yii framework manual:
$auth=Yii::app()->authManager;
$auth->createOperation('createPost','create a post');
$auth->createOperation('readPost','read a post');
$auth->createOperation('updatePost','update a post');
$auth->createOperation('deletePost','delete a post');
$bizRule='return Yii::app()->user->id==$params["post"]->authID;';
$task=$auth->createTask('updateOwnPost','update a post by author himself',$bizRule);
$task->addChild('updatePost');
$role=$auth->createRole('reader');
$role->addChild('readPost');
$role=$auth->createRole('author');
$role->addChild('reader');
$role->addChild('createPost');
$role->addChild('updateOwnPost');
and so on.
The question is Where should I place the code for creating roles, tasks, etc?
You should use this code in protected/controllers/RbacController.php
After modifing protected/config/main.php
return array(
'components'=>array(
'db'=>array(
'class'=>'CDbConnection',
'connectionString'=>'sqlite:path/to/file.db',
),
'authManager'=>array(
'class'=>'CDbAuthManager',
'connectionID'=>'db',
),
),
);
This is the official documentation:
http://www.yiiframework.com/doc/guide/1.1/en/topics.auth#using-default-roles
This took me awhile to understand, so let me answer your questions as I understand how yii works.
You will first create the appropriate tables following the sql code found in framework/web/auth
You can use phpmyadmin to populate the database
You can also create a controller in which you will run all of code above. That gets run once, because you are just populating a database
The controller can be called myInitController.php and stored with your other controllers.
The controller can be as simple as
<?php
class myInitController extends Controller
{
public function actionRun()
{
$auth=Yii::app()->authManager;
$auth->createOperation('createPost','create a post');
echo "this is it";
}
}
Then you would run it by going to www.yourwebsite.com/myInit/Run
Verify what got written to the database. Don't push this controller to production. You don't want someone else running the command.
So your options are
hand enter data through something like phpmyadmin
create a customer controller which can store all of the php commands and execute
use gii to create models and CRUD functions (be careful of composite primary keys)
I hope this helps.
This piece of code will create the items in database. You have to execute it.
You can create an action in one of your controller and then run it.
localhost/myAppName/myController/myAction
Or you can create a php file as well. Then juste paste your piece of code inside and run it.

CheckAccess. Agile Web Application Development with Yii1.1

I need some help with CheckAccess function.
I'm reading book Agile Web Application Development with Yii1.1 and PHP5, and came to page 212. On this page I've to added a "Create user" menu item.
I login with the user that is associated with the project (in Db table project_user_role) like a member, and members has operateion called 'createUser'.
The problem is that I can't see the menu item which should be generated by the following code:
if (Yii::app()->user->checkAccess('createUser', array('project' => $model))) {
$this->menu[] = array('label' => 'Add User To Project', 'url' => array('adduser', 'id' => $model->id));
}
Thanks
Also with AuthAssignment there are two more tables and even having them is not full deal. You got to have set RBAC :).
Please SeeRole-Based Access Control