Is There Any Way to Bypass Model::created() Event on Laravel? - laravel-5.1

UserModel.php
In my user model there is created event which is called every time when new user is created using User::Save()
protected static function boot()
{
parent::boot();
self::created(function (User $user) {
// Some operation goes here
});
}
Now what i want is for some reason i don't want to call that created when i create new user record.
Is there any way to bypass createdEvent ??

Check this withoutEvent method on model included in recent version of Laravel.
https://github.com/laravel/framework/blob/d4f89f9ca33c70672b0c5eeb0f9523a557841e69/CHANGELOG-5.7.md#v5726-2019-02-12

Related

How to manage response data of steps implemented in Gherkin using QAF API?

Looking for ways to carry over data from previous step to subsequent using QAF. Is there an option for such behavior?
In qaf your step can return a value. If you step is returning a value and you want to use it in another step you can use store into 'var-name' step after step that returning value. For example
When create new user using "{'name':'user1','password':'user123'}"
And store into 'newUser'
Then system should have user '${newUser}'
Your step may look like below:
#QAFTestStep(description="create new user using {userInfo}")
public User createUser(User user){
//steps to createUser
long id = userDao.createUser(user);
user.setId(id);
return user;
}
#QAFTestStep(description="system should have user {userInfo}")
public void createUser(User user){
//steps to createUser
User user = userDao.getUser(user.getId);
Validator.assertThat("get user from system",user, Matchers.notNull());
}
Below is example of web services test:
Given user requests 'myservice.getuser.reqcall'
And say 'userID' is value at jsonpath '$.id'
Then ...

MVC3: Session_Start Fires twice when testing for Roles

I need to do some authentication for a web app with MVC3. The customer would like there to be a generic page to show if they do not have any of the role groups in windows AD that are allowed to use the app. I found a pretty simple way to do it, but just curious if it is a valid way or if there is something better out there.
Basically in the Session_Start in the global I am checking for User.IsInRole() and if that returns false then I do a Response.Redirect(). This question is: after it his the code in the IF statement and hits the Response.Redirect() code then it hits the session one more time before it goes to the AccessDenied page in the root of the app. Is this okay? Will it cause any issues If they are valid and does not enter the If to do the response.redirect?
//if (!User.IsInRole("test_user"))
//{
// Response.Redirect("~/AccessDenied.aspx", true);
//}
I would recommend you to write your Authorization filter for MVC3 and do this type of logic there:
public class RoleFilter: AuthorizeAttribute
{
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext filterContext)
{
if (!User.IsInRole("test_user"))
{
filterContext.HttpContext.Response.StatusCode = 302;
filterContext.Result = new RedirectResult("~/AcessDenied.aspx");
}
}
}
Also I wouldn't recommend you to use Response.Redirect because it aborts current thread.

how to get an unsaved entity on server but not for saving?

i need to send my unsaved entity from the client to the server but not for saving changes
but inorder to do a process using the data on the entity and then change some of it's values and pass it back to the client
is this possible?
if not what are my options?
i tried to export the entity and then send it to a method on the webapi controller that gets a JObject but didn't find a way to deserialize it to the server entity
We did have a similar problem and found a solution as follows:
You need to take into consideration the way breeze manages it's objects.
1.Create custom saveBundle.
Consider complex order object.You need to fill your save bundle with each nested object inside order.
Like:
var saveBundle = new Array();
saveBundle.push(order.SaleAccountingInfo);
saveBundle.push(order.CostAccountingInfo);
saveBundle.push(order);
2.Create custom save options, where you can point to your custom Save Method on server
Like:
var so = new breeze.SaveOptions({ resourceName: "BookOrder" });
3.Call standard breeze function and pass it created params
manager.saveChanges(saveBundle, so).fail(function () {
// manager.rejectChanges();TODO check what needed
deferred.resolve(true);
});
On server you need to have you custom function ready and hook some breeze delegates
[HttpPost]
public SaveResult BookOrder(JObject orderBundle)
{
context.BeforeSaveEntityDelegate = OrderBeforeSaveEntity;
context.BeforeSaveEntitiesDelegate = SaveOrder;
context.AfterSaveEntitiesDelegate = BookOrderAfterSave;
try
{
return context.SaveChanges(orderBundle);
}
catch (Exception)
{
throw;
}
}
You can a lot of stuff in first two delegates but it is the last one you are looking for
private void BookOrderAfterSave(Dictionary<Type, List<EntityInfo>> orderSaveMap, List<KeyMapping> orderKeyMappings)
{
var orderEntity = orderSaveMap.Where(c => c.Key == typeof(BL.Orders.Order)).Select(d => d.Value).SingleOrDefault();
BL.Orders.Order order = (BL.Orders.Order)orderEntity[0].Entity; //your entity
//logic here
}
Hope it points to right direction.
we are doing something similar here. it'll save the entity so i'm not sure if this fits your question.
you can do:
entity.entityAspect.setModified()
then issue a saveChange()
then you can do your calculations on the server.
in our case we are using breeze.webapi so we are doing this in the beforeSave(entity) method.
breeze by design sends the changed entity then back to the client where the cache gets updated with your changes done on the server.

ASP.Net MVC 4: Update Profile after Windows authentication only once after login

I have an Intranet application with Windows authentication set for user authentication which works fine, only problem is that I do not want to say 'Hello, mydomain\user!' but use the user's full display name which I find in the Active Directory.
In fact I want to populate the profile with even more details from our domain, the problem is that I only want to do this AD query only once after the user has been authenticated on his first call to the application. I have all the AD and profile things working, but I do not find a good place to put the code so that it is called exactly once after login. I suspect a custom AuthorizeAttribute might be a way... Any help is greatly appreciated. Thanks!!
Try storing the information in session or within cookies or local storage on the client side.
Well, I finally came up with a solution - can this be considered as a as a valid answer? Basically I wrote a custom AuthorizationFilter and put a flag into the session to do the whole work only once. However I hoped to find an event "User_Authenticated" which is fired only once. But I guess this is more appropriate for Forms authentication.
public class ProfileUpdater : IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
// if there is a profile already in the session we do not update this
Controller controller = filterContext.Controller as Controller;
if (controller != null && controller.Session["ProfileUpdated"] != null)
{
return;
}
else if (controller == null)
{
return;
}
UserPrincipal domainUser = DomainHelper.GetDomainUser(controller.User.Identity.Name);
if (domainUser != null)
{
controller.Profile.SetPropertyValue("DisplayName", domainUser.DisplayName);
controller.Session["ProfileUpdated"] = true; // just put a marker object into the session to show we alreay updated the Profile
}
return;
}
}

symfony sfGuardUser hasCrendential live after update

I'm using symfony 1.4 and the sfGuardDoctrinePlugin, I've got it installed and setup fine but I have the following problem:
If I login as an admin and update the permissions for a user, that user must logout then login again before having the newly added credential/permission.
Is there a way around this?
I'm not sure how easy this would be to fix. When a user logs in I think their credentials are added to their session attributes there and then. So when the admin updates their credentials their session still holds the old credentials. This means any call to hasCredential isn't "live".
Thanks
This would add extra queries to each and every request to your application. You could force update of the credentials by $user->getSfGuardUser()->refresh(true), which would reload the entity and all its relations (and thus its permissions).
Thanks for your answer, I've modified the processForm function of the sfGuardUser module's actions class.
If I login and change my own permissions, the session is updated there and then.
My problem is that if I edit the user permissions of another user, I would need to edit their session data. To solve this I enabled database sessions, so I now have sessions saving there instead of to file. So my next problem is how to isolate the session for the other user.
The sessions database has the following columns: sess_id, sess_data, sess_time.
sess_data is serialized and that is what I would need to update.
But I think symfony updates the session ids quite often and it would be hard to always isolate the correct session for the other user.
I think that it would also be slow to try and unserialize, check user_id then reserialize the data. I would need a user_id column I think.
I know this is an old question, but I recently had this same problem and it took me way longer than it should have to find the answer (which was posted in Symfony's code snippet section). Paste this function in your myUser class and all problems go away:
/**
* Overridden method that actually reads the permission from DB
* instead of relying on data present when the user logs in.
*
* #param string permission name
*
* #return boolean true if the user has credential
*/
public function hasCredential($permission_name)
{
if (!$this->isAuthenticated()) {
return false;
}
$gu = $this->getGuardUser();
$groups = $gu->getGroups();
$permissions = $gu->getPermissions();
$permission_names = array();
foreach($permissions as $permission) {
$permission_names[] = $permission->getName();
}
foreach($groups as $group) {
$group_permissions = $group->getPermissions();
foreach($group_permissions as $group_permission) {
$permission_names = array_merge($permission_names, array($group_permission->getName()));
}
}
$permission_names = array_unique($permission_names);
return (in_array($permission_name, $permission_names)) ? true : false;
}

Resources