SOLVED! I created a $password property in my Entity class thinking I needed to. The password field is added to the Entity through the entire request. None of the code posted below had to be changed.
I am using friendsofcake/Crud to build a REST api. When I save my User models, I have an afterSave() event that does the password salting and hashing. The POST data sent to my UsersController:add() method includes a ['password'] parameter, but my UsersTable has ['hash','salt'] fields.
Basically, I need to know if and where the POST['password'] parameter is, and if it is available in the UsersTable afterSave() method. Otherwise, my system is hashing and salting empty password strings!
I am new to CakePHP and having trouble finding straightforward answers for 3.*.
Here is the afterSave() method in my UsersTable class.
/**
* Updates Meta information after being created.
*/
public function afterSave(Event $event, Entity $entity, ArrayObject $options)
{
if($entity->returnAfterSave) return;
// update the public id
if(empty($entity->public_id))
{
$hashids = new Hashids(static::HASH_SALT, static::HASH_LENGTH);
$entity->public_id = $hashids->encode($entity->id);
}
// generate a password salt
if(empty($entity->salt))
{
$entity->generateSalt();
}
// salt and hash the password
if(empty($entity->hash))
{
// NOTE: I figured since the form data
// is loaded into the entity, I created a $password property
// in my User Entity class. This assumption may be the problem??
// Update: It was a bad assumption. Removing said property solved issue.
$entity->hashPassword();
}
// save the changes
$entity->returnAfterSave = true;
$this->save($entity);
}
Also, I understand that this code will not properly save any new passwords, I will update the code for password changes after my creates are working properly.
Related
Thank you in advance for your help and attentation!
My project is dedicated only for learning purposes and I'm totally confused with DDD and have the following situation:
There is the ubiquitous language of my domain where I have users and documents. It says the following:
- A user can create a document. One of the main purpose of my project is to provide users an ability to create different documents. I mean that the documents cannot exist without the users. So,I think that the process of a document creation belongs to my domain.
- A user can send a document for approval. It's one more thing that belongs to the domain. An approval process is one of the most important part of the project. It has its steps that other users must confirm.
- A user can approve a step of approval process.
- A user can reject a step of approval process.
That's enough to understand and answer my question:
Is it normal that a User can contain such methods as: CreateDocument(params), SendDocumentForApproval(docId), ApproveApprovalStepOfDocument(stepId)?
I'm comfused with it because It looks in code a bit strange.
For example for the document creatation process we have something like that:
public async Task<bool> CreateDocumentCommandHandler(CreateDocumentCommand command)
{
//We have our injected repositories
User user = await _userRepository.UserOfId(command.UserId);
Document document = User.CreateDocoment(command.*[Params for the document]);
_documentRepostiory.Add(document);
// It raises event before it makes a commit to the database
// It gets event from an entity. The entity keeps it as readonly collection.
// Here it raises DocumentCreatedEvent. This event contains logic which concerns
// creation some additional entities for the document and log actions.
await _documentRepository.UnitOfWork.SaveEntitiesAsync();
}
The approval process:
//The first try out to model this process:
public async Task<bool> SendDocumentForApprovalCommandHandler(SendDocumentForApprovalCommand command)
{
//We have our injected repositories
User user = await _userRepository.UserOfId(command.UserId);
//Here I have some problems.
//Is it okay that the method returns the document?
//The method that is placed inside the User has this logic:
//public Document SendDocumentForApproval(int docId)
//{
// Document document = this.GetDocument(docId);
//
// //Inside this method ChangedStatusToApproving is created
// document.SetStatusToApproving();
// return document;
//}
Document document = User.SendDocumentForApproval(command.DocId);
_documentRepostiory.Upadate(document);
// It raises event before it makes a commit to the database
// It gets event from an entity. The entity keeps it as readonly collection.
// Here it raises ChangedStatusToApproving. This event contains logic which concerns
// creation some additional entities for the document and log actions.
await _documentRepository.UnitOfWork.SaveEntitiesAsync();
}
//Is it okay to do something like the command handler above?
//The second one:
public async Task<bool> SendDocumentForApprovalCommandHandler(SendDocumentForApprovalCommand command)
{
//We have our injected repositories
User user = await _userRepository.UserOfId(command.UserId);
//The same one as we have in the previous method.
//But here I don't want to put the logic about the changing status of the doucnent inside it.
Document document = User.SendDocumentForApproval(command.DocId);
//I see that it breaks the method above (SendDocumentForApproval)
//Now It doesn't mean anything for our domain, does it?
//It is only getter like User.GetDocument or we can even do it
//by using repository - documentRepository.DocumentOfId(docId)
document.SetStatusToApproving();
_documentRepostiory.Upadate(document);
await _documentRepository.UnitOfWork.SaveEntitiesAsync();
}
// So, I think the first one is better, isn't it? It follows the ubiquitous language.
//And here is the final question: Why can't I do it like this:
public async Task<bool> SendDocumentForApprovalCommandHandler(SendDocumentForApprovalCommand command)
{
//Here we don't want to use the userRepository. We don't need at all
//Here as a consequence we also don't need a user entity
//Everything what we need is:
Document document = _documentRepository.DocOfId(command.DocId);
document.ForApproval();
_documentRepostiory.Upadate(document);
await _documentRepository.UnitOfWork.SaveEntitiesAsync();
}
//I think that the last approach breaks the ubiquitous language and we're about to having an anemic model.
//But here we have only two queries to the database because we don't need a user.
//Which of the approaches is better? Why? How can I do it more correctly if I want to apply DDD?
I want to explain my thoughts in more details.
Let's have a look at the user. They manage documents. A Document cannot exist without the user. Does it mean that the User is an aggregate root through we need to create, update, delete its aggregates.
And the document is also an aggregate root due to it contains an apporval process. The ApprovalProcess cannot exist without the document.
Does it mean that I need to do something like this:
public async Task<bool> SendDocumentForApprovalCommandHandler(SendDocumentForApprovalCommand command)
{
Document document = _documentRepository.DocumentOfId(command.DocId);
document.SendForApproval();
_documentRepository.SaveChangesAsync();//Raise a domain event - SentDocumentForApprovalEvent
}
// Here we have a handler for the event SentDocumentForApprovalEvent
public async Task SentDocumentForApprovalEventHandler(SentDocumentForApprovalEvent sentDocumentForApprovalEvent)
{
//Now I want to create an approval process for the document
//Can I do the next thing:
ApprovalProcess process = new ApprovalProcess(sentDocumentForApprovalEvent.DocId);
_approvalProcessRepository.Add(process);
_approvalProcessRepository.SaveEntitiesAsync();//Raise a domain event - InitiatedApprovalProcessEvent
//Or Should I create the approval process through Document?
//Looks terrible due to we need to call the repostiory amd
ApprovalProcess process = Document.InitiateApprovalProcess(sentDocumentForApprovalEvent.DocID);//Static method
_approvalProcessRepository.Add(process);
_approvalProcessRepository.SaveEntitiesAsync();
//log
}
// Here we have a handler for the event InitiatedApprovalProcessEvent
public async Task InitiatedApprovalProcesEventHandler(SentDocumentForApprovalEvent sentDocumentForApprovalEvent)
{
//The same question as we have with handler above.
//Should I create steps trough the approval process or just with the help of constructor of the step?
//log
}
Thank you so much and sorry for my terrible English!
Best regards
Is it normal that a User can contain such methods as: CreateDocument(params), SendDocumentForApproval(docId), ApproveApprovalStepOfDocument(stepId)?
In most domain models, the method belongs with the entity that manages the state that is going to change.
Document document = User.SendDocumentForApproval(command.DocId);
_documentRepository.Update(document);
The fact that your sample is updating the document repository here is a big hint that it is the document that is changing, and therefore we would normally expect to see SendDocumentForApproval as a method on the document.
document.SendDocumentForApproval(command.UserId)
_documentRepository.Update(document);
(Yes, the code doesn't read like written or spoken English.)
When creating a new document... creation patterns are weird. Udi Dahan suggests that there should always be some entity in your domain model that is responsible for creating the other entities, but I'm not convinced that the result is actually easier to work with in the long term.
How can we model the approval business process
General answer: business processes are protocols, which is to say that you can normally model them as a state machine. Here's the state we are in right now, here is some new information from the outside world, compute the consequences.
(Often, the data model for a process will just look like a history of events; the domain model's job is to then take the new information and compute the right events to store in the history. You don't have to do it that way, but there are interesting possibilities available when you can).
You are headed in a right direction, User and Document both are aggregates as they are created in separate transactions. When it comes to who references whom, IDDD principle of scalability says that aggregates should refer aggregates only via their IDs.
I think sticking to the ubiquitious, language your code should look something like this
class User {
private UserId id;
private String name;
User(String name) {
this.id = new UserId();
this.name = name;
}
Document createDocument(String name) {
Document document = new Document(name);
document.createdBy(this);
return document;
}
Document approve(Document document) {
document.approved();
return document;
}
}
class Document {
private DocumentId id;
private String name;
private UserId userId;
private Boolean isApproved;
Document(String name) {
this.id = new DocumentId();
this.name = name;
}
void createdBy(UserId userId) {
this.userId = userId;
}
void approved() {
this.isApproved = true;
}
}
// User creation
User user = new User("Someone");
userRepository.save(user);
//Document creation
User user = userRepository.find(new UserId("some-id"))
Document document = user.createDocument("important-document")
documentRepository.save(document)
// Approval
User user = userRepository.find(new UserId("some-id"))
Document document = documentRepository.find(new DocumentId("some-id"))
document = user.approve(Document)
I would highly recommend reading Vaughn Vernon's three part aggregate design paper series better aggregete design
In my database design, I have two tables, People & Auth. The Auth table holds authentication information and the person_id while the People table holds all other information (name, address, etc). There is a one-to-one relationship between the tables as seen in the models below.
The reason I have separated the data into two tables is because in my
application, I will have many people who do not have authentication
capabilities (customers to the user).
App/Auth.php
class Auth extends Model implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
public function person() {
$this->belongsTo('Person');
}
}
App/Person.php
class Person extends Model
{
public function auth() {
$this->hasOne('Auth');
}
}
In my AuthController::create() method, I am attempting to populate both models with the user supplied information like this:
protected function create(Request $request)
{
$person = \App\Person::create($request->all());
$auth = new \App\Auth;
$auth->fill($request->all());
$auth->person_id = $person->id;
$auth->save();
return $person;
}
In my application, I would like to authorize a user and pass a $user object as the authenticated person to subsequent routes. Am I doing this correctly? Is this the best way? There's cookies and bonus points if you can also explain how to retrieve the $user object after authentication...Auth table data is not needed in the $user object.
EDIT
I have changed my config/Auth.php file to reflect the changes as noted in the answers below (thx #user3702268). However, I have now found an error with my controller. In the AuthController::create() method, I am returning my App/Person object and this throws an ErrorException seeing as how App/Person does not implement the Authorizable trait. I do not want my App/Person object to be authorizable, but it is the object that I want returned as the authenticated $user in my views. How? Shall I simply override the postRegister method or is there a more Laravel way?
EDIT 2
I'm now returning the $auth object which uses the authorizable trait. In my views/controllers I'm trying to access the Person using Auth::user()->person but getting Class 'Person' not found errors
You should replace the App\User Class in config/auth.php line 31 the class that contains the username and password:
'model' => App\User::class,
to
'model' => App\Auth::class,
Be sure to encrypt the password before saving by using the bcrypt($request->get('password')) helper or Hash::make($request->get('password')). Then you can authenticate by calling:
Auth::attempt([$request->get('username'), $request->get('password')]);
You can retrieve the authenticated user using this:
Auth::user()
Scenerio:
Using Yii-rights + Yii-user module in my project. In Rights, I generated operations based on my controller action, under update I added a child UpdateOwn.
For UpdateOwn, the bizrule is suppose to be a simple comparison that the logged in user's ID is equal to $model->user_id field.
Problem:
I understand yii checkaccess allow you to pass in variables as parameters and comparing with your defined bizrule. But how does it work for Yii-rights module? How or what are the data/params passed in to be used in bizrule? How can I define or pass my own data/params?
Yii-rights is a wrapper for standart yii-rbac. In rights module you have web-interface for your RBAC. When you creating AuthItem (Operation in rights web interface) you can define your own bizrule.
Here is code for creating AuthItem:
$item = $this->_authorizer->createAuthItem($formModel->name, $type, $formModel->description, $formModel->bizRule, $formModel->data);
$item = $this->_authorizer->attachAuthItemBehavior($item);
_authorizer here is an example of RAuthorizer class. Then we go to RDbAuthManager, which extends CDbAuthManager, where we createAuthItem function:
public function createAuthItem($name,$type,$description='',$bizRule=null,$data=null)
{
$this->db->createCommand()
->insert($this->itemTable, array(
'name'=>$name,
'type'=>$type,
'description'=>$description,
'bizrule'=>$bizRule,
'data'=>serialize($data)
));
return new CAuthItem($this,$name,$type,$description,$bizRule,$data);
}
This is how created AuthItem, in rights. Personally i prefer to use web interface. It have alot of great fetures and much easier to handle then go to code each time.
Then when we perform checkAccess() on AuthItem we call execute bizRule:
public function executeBizRule($bizRule,$params,$data)
{
return $bizRule==='' || $bizRule===null || ($this->showErrors ? eval($bizRule)!=0 : #eval($bizRule)!=0);
}
This is how RBAC in yii work, and rights is just a cool wrapper for it. Rights doesn't change logic of how things must be done.
So in basic yii-rbac if you want to allow update only Own records you do:
$bizRule='return Yii::app()->user->id==$params["user"]->username;';
$task=$auth->createTask('updateOwnUser','update a your own account',$bizRule);
$task->addChild('updateUser');
Then you call it like this:
$user=$this->loadUser();
$params = array('user' => $user);
if(Yii::app()->user->checkAccess('updateOwnUser', $params){
..................
}
In rights it's already implemented with filters. Only thing what you need to do is add to your controller:
class MyController extends RController{
.............
public function filters()
{
return array(
'rights',
............
);
}
.............
}
So define your bizrule for item in web interface, change your controller code, and actually thats it. To know what variables to use in bizrule you can watch on RightsFilter.php code, where checkAccess() performed.
And on top of all of this i'll say about how checkAccess() does :
For each assigned auth item of the user, it first checks if the bizRule for the assignment returns true.
If true, it calls the item's checkAccess method. If the item's bizRule returns true,
2.1. If the item name is the same as the name passed in the original checkAccess() method, it returns true;
2.2. Otherwise, for every child item, it calls its checkAccess.
Hope this will clarify some aspects of RBAC and help in your task.
The yii-rights module has the following properties:
/**
* #property boolean whether to enable business rules.
*/
public $enableBizRule = true;
/**
* #property boolean whether to enable data for business rules.
*/
public $enableBizRuleData = false;
To set bizrule data via the web interface you have to set $enableBizRuleData = true in your application configuration.
Please note that the UI is limited and you can set data only for Auth-Items not for Auth-Assignments. Also the value for data has to be a serialized PHP variable.
As mentioned by #ineersa you can access $data in unserialized form in your bizRule.
It's also worth noting, that Yii checks first the bizRule for the Auth-Item and then additionally for the Auth-Assignment.
[edit] added example
Auth Item
bizRule
Check if the assignment has all the keys specified in the item data
return BizRule::compareKeys($params, $data, 'Editor');
data
a:1:{s:8:"language";b:1;}
Auth Assignment
Check if the application language matches the assignment data
bizRule
return BizRule::compareApplicationLanguage($params, $data);
data
a:1:{s:8:"language";s:5:"de_de";}
[edit] added code link
Here is the full Helper Code
Very simple question: I have a session object in my Service:
var session = this.GetSession(); //IAuthSession
if (!session.IsAuthenticated)
I can modify some values in the session class (e.g. Permissions) based on the parameters passed to the service; then I want to save them.
How?
The direct way of doing it: create a UserAuth object, popolate it with all the fields from IAuthSession, get the IDbConnectionFactory, save it.
Surely there is a faster and better way, but I was not able to find it!
More generally, how can I switch between IAuthSession anf UserAuth? I.e., given a IAuthSession object, how can I obtain a UserAuth object, modify it, and persist the modifications?
I have read this question on how to append metadata to a user login info, but something is still missing.
Once you have added what you need, how do you save it? (I doubt you just add the metadata to both session and UserAuth, and then you use IDbConnectionFactory to save the latter; there must be a better way!)
Old question but worth answering.
The UserAuthRepository being used should have an implementation of the UpdateUserAuth method that can be called to save the UserAuth changes
UpdateUserAuth(UserAuth existingUser, UserAuth newUser, string password)
Another easier way would be to just call the RegisterService using PUT which will update the existing registered user for you.
/// <summary>
/// Update an existing registraiton
/// </summary>
public object Put(Register request)
{
return Post(request);
}
The service call would be something similar to this:
using (var authService = base.ResolveService<RegisterService>())
{
var authResponse = authService.Put(
new Register {
UserName = session.UserName ?? session.Email,
Email = session.Email,
etc...
});
if (authResponse is IHttpError)
throw (Exception)authResponse;
}
It's more like theoretical question.
I have one table to hold dictionary items, and the next one for hold Users data.
User table contains a lot reference collumns of type many to one indicated on dictionary item table. It's looks like:
public class User
{
public int Id;
public Dictionary Status;
public Dictionary Type;
public Dictionary OrganizationUnit;
......
}
I want retrieve all dictionary on startup of aplication, and then when i retrieved user and invoke reference property to dictionary the dictionary object should be taken from cache.
I know i can use a 2nd level cache in this scenario, but i'm interested about other solution. Is there any?
It's posible to make my custom type and said that: use my custom cache to retrieved value of dictionary??
Across multiple session the second level cache is the best answer, the only other solutions to populate objects from a cache without using second level cache i can think of would be to use an onLoad interceptor (and simply leave your dictionaries unmapped) or do it manually somewhere in your application.
But why don't you want to use the seocondlevel cache? If your views on caching is very different from the storages there are providers for in hibernate it is possible for you to implement your own provider?
Why not store it in the session? Just pull the record set one time and push it into session and retrieve it each time you want it. I do something similar for other stuff and I believe my method should work for you. In my code I have a session manager that I call directly from any piece of code needs the session values. I choose this method since I can query the results and I can manipulate the storage and retrieval methods. When relying on NHibernate to do the Caching for me, I don't have the granularity of control to cause specific record sets to only be available to specific sessions. I also find that NHibernate is not as efficient as using the session directly. When profiling the CPU and memory usage I find that this method is faster and uses a little less memory. If you want to do it on a site level instead of session, look into HttpContext.Current.Cache.
The following example works perfectly for storing and retrieving record sets:
// Set the session
SessionManager.User = (Some code to pull the user record with relationships. Set the fetch mode to eager for each relationship else you will just have broken references.)
// Get the session
User myUser = SessionManager.User;
public static class SessionManager
{
public static User User
{
get { return GetSession("MySessionUser") as User; }
set { SetSession("MySessionUser", value); }
}
private static object GetSession(string key)
{
// Fix Null reference error
if (System.Web.HttpContext.Current == null || System.Web.HttpContext.Current.Session == null)
{
return null;
}
else
{
return System.Web.HttpContext.Current.Session[key];
}
}
private static void SetSession(string key, object valueIn)
{
// Fix null reference error
if (System.Web.HttpContext.Current.Session[key] == null)
{
System.Web.HttpContext.Current.Session.Add(key, valueIn);
}
else
{
System.Web.HttpContext.Current.Session[key] = valueIn;
}
}
}