Is there a way to send CakeResponse from blackhole callback - ajax

I am trying to make the ajax request more user friendly. It is a scenario that using a token which can be reuse in a period of time. However in time that a user has inactive for a certain time and tried to use the form, user will observe that the ajax not working but donno why. What I'm gonna do here is to display the message.
Using my testing code, doing return new CakeResponse seems to be return true in blackhole and therefore the $result is true although the User edit should not be triggered
public function beforeFilter() {
$this->Security->blackHoleCallback = 'blackhole';
}
public function blackhole($type) {
if ($this->request->is('ajax')) {
$this->log('blackhole here','debug');
return new CakeResponse(array('body'=> json_encode(array('data'=>'The request has been blackholed')),'status'=>500));
}else{
$this->log('blackhole there','debug');
return new CakeResponse(array('body'=> json_encode(array('data'=>'The request has been blackholed')),'status'=>500));
}
}
in the userapp
public function edit() {
$userId=$this->Auth->user('id');
if (empty($this->request->data)) {
$this->request->data = $this->User->read(null, $userId);
}
if ($this->request->is('ajax')) {
if($result = $this->{$this->modelClass}->edit($userId, $this->request->data)){
$this->Session->write('Auth', $this->User->read(null, $userId));
return new CakeResponse(array('body'=> json_encode(array('data'=>'saved')),'status'=>200));
}else{
return new CakeResponse(array('body'=> json_encode(array('data'=>'error')),'status'=>500));
}
}
}
Progress 1:
Unsolved, perhaps needed to use event handler or exception, though it will be somehow complicated . Still thinking while refining other plugin feature.

Related

pass collection of records to policy

this is my tables structure :
i want to get all Request State Records where Request_status.Department_id equals with User.Department_id . and user only can see own request_state records i defined a policy to handle this job but this policy only can handle 1 request_state record . this policy can't handle array of request_state Model ! how can i use get() instead of first()
Policy :
public function view(User $user, RequestState $requestState)
{
return$user->department_id===$requestState->department_id&&$user->hasRole('department');
}
Controller :
public function show_request()
{
$RequestState=RequestState::where('department_id',auth()->user()->department_id)->first();
nullable($RequestState)->getOrSend(function (){
return Responder::requestDoesNotFound();
});
if(auth()->user()->can('view',$RequestState)){
return 'ok';
}
}
The policy is fine as-is. The changes should be in the controller.
Your controller method is called show_request(). The name implies it is showing a single request. But the controller logic shows it is showing all the requests for the user. You need to either validate each request individually, or assume that all the requests have the same department_id, since that is what your query pulls. Assuming you want to check all the RequestStates in the collection, you can them to a single TRUE/FALSE;
public function show_request()
{
$requestStates = RequestState::where('department_id', auth()->user()->department_id)->fget();
nullable($RequestState)->getOrSend(function (){
return Responder::requestDoesNotFound();
});
return $requestStates->reduce(function ($accumulator, $requestState) {
return $accumulator and auth()->user()->can('view', $requestState);
}, TRUE);
}
As I can see, you want lo allow the users to see the list of request they have access. You can create a new method in your controller method to validate all the requests.
It should be something like this:
public function show_requests()
{
$requestStates = RequestState::where('department_id',auth()->user()->department_id)->get();
if(sizeof($requestStates) > 0 ){
for($i = 0; $i < size($requestStates); $i++ ) {
if (!(auth()->user()->can('view', $requestStates[$i]))) {
//Unset the record the user can't see
unset($requestStates[$i]);
}
}
//Return all records the user can see
return $requestStates;
}
else {
return Responder::requestDoesNotFound();
}
}

laravel social login for multiple user session getting lost on callback url

public function SocialRedirectEmployer($provider)
{
session()->set('role_id', request()->segment(3));
return Socialite::driver($provider)->redirect();
}
public function SocialRedirectEmp($provider)
{
session()->put('role_id', request()->segment(3));
session(['my_variable' => "lll"]);
return Socialite::driver($provider)->redirect();
}
Routes are
Route::get('loginEmployer/{provider}/rec', [App\Http\Controllers\Auth\LoginController::class, 'SocialRedirectEmployer']);
Route::get('loginEmp/{provider}/emp', [App\Http\Controllers\Auth\LoginController::class, 'SocialRedirectEmp']);
Route::get('login/{provider}/callback',[App\Http\Controllers\Auth\LoginController::class, 'SocialCallback']);
Afer call back url session is lost getting null
public function SocialCallback($provider){
$userSocial = Socialite::driver($provider)->stateless()->user();
$role = session()->get('role_id');
var_dump("role = ".$role);
dd(session('my_variable'));
dd(\request()->segment(3));
}
and request segment also not getting no callback url
For Session, You can use
use Session;
where library define
And for callback url you can this

SignInStatus always returns Success on TwoFactorAuthentication is enabled in webapi using asp.net identity

I am implementing 2 factor authentication in WebApi, asp.net identity and OWIN. Every time I log in, I get SignInStatus = Success never reaches to SignInStatus = RequiresVerification though user TwoFactorAuthentication is enabled.
Below are some code snippets,
Startup.cs:
private void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
app.UseOAuthBearerTokens(OAuthOptions);
}
Action method for enabling two factor authentication,
[HttpPost]
public async Task<IHttpActionResult> EnableTwoFactorAuthentication()
{
var user = await this.AppUserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
IdentityResult result = await this.AppUserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), true);
await this.AppSignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
}
return Ok();
}
Please suggest a solution.
If you get stuck here, one way to solve the problem is to copy the methods from SignInManager directly into your code and call those instead so you can step through the methods and see why you are getting the wrong status. For me the problem ended up being that I instantiated my UserManager with:
new MyUserManager()
instead of the right way:
HttpContext.GetOwinContext().Get<MyUserManager>()
I was using this as my template for setting it up:
https://github.com/adamtuliper/ASP.NET-Identity-Samples/tree/master/BasicTemplate%20-%20Two%20Factor/BasicTemplate
SignInManager return RequiresVerification if :
dbo.ASpnetUsers has for user set to true TwoFactorEnabled and EmailConfirmed and user email should be confirmed, email not be empty or null.
var result = SignInManager.PasswordSignIn(usernameIdentity, model.Password, model.RememberMe, shouldLockout: true);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", returnUrl);
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid username or password.");
return View(model);
}

RedirectToAction not working as expected

I have a simple MVC3 application that I want to retrieve some configuration details from a service, allow the user to edit and save the configuration.
If any errors are detected during the saving process, these are to be returned and reported back to the user.
The problem is that the configuration containing the errors is failing to be called and the currently saved values are just being redisplayed.
Stepping through the code, when errors are detected, it should redirect to itself using the passed config object but it doesn't and uses the method with no parameter.
Can anyone see where I'm going wrong?
Below are the two controller methods that are being called:
//
// GET: /Settings/Edit/
public ActionResult Edit()
{
SettingsViewModel config = null;
// Set up a channel factory to use the webHTTPBinding
using (WebChannelFactory<IChangeService> serviceChannel =
new WebChannelFactory<IChangeService>(new Uri(baseServiceUrl)))
{
// Retrieve the current configuration from the service for editing
IChangeService channel = serviceChannel.CreateChannel();
config = channel.GetSysConfig();
}
ViewBag.Message = "Service Configuration";
return View(config);
}
//
// POST: /Settings/Edit/
[HttpPost]
public ActionResult Edit( SettingsViewModel config)
{
try
{
if (ModelState.IsValid)
{
// Set up a channel factory to use the webHTTPBinding
using (WebChannelFactory<IChangeService> serviceChannel = new WebChannelFactory<IChangeService>(new Uri(baseServiceUrl)))
{
IChangeService channel = serviceChannel.CreateChannel();
config = channel.SetSysConfig(config);
// Check for any errors returned by the service
if (config.ConfigErrors != null && config.ConfigErrors.Count > 0)
{
// Force the redisplay of the page displaying the errors at the top
return RedirectToAction("Edit", config);
}
}
}
return RedirectToAction("Index", config);
}
catch
{
return View();
}
}
return RedirectToAction("Index", config);
You cannot pass complex objects like this when redirecting. You will need to pass query string parameters one by one:
return RedirectToAction("Index", new {
Prop1 = config.Prop1,
Prop2 = config.Prop2,
...
});
Also I couldn't see an Index action in your controller. Maybe it's a typo. Another thing I notice is that you have an Edit GET action to which you are probably trying to redirect but this Edit action doesn't take any parameters so it just seems weird. If you are trying to redirect to the POST Edit action, well, that's obviously impossible since a redirect is always on GET by its very nature.

Custom component check-in/check-out best practices

I'm creating a component in Joomla! 1.7 and I'd like to take advantage of the framework's check-out/check-in features. Currently
How do I mark a component record as "checked out" when a user requests the edit task for that record?
How do I mark a record as "checked in" when the user attempts to store his or her edits?
How do I test the checked-in/checked-out status of a component's record at edit time?
Thanks!
Basicly you need two methods in your model, which you can call whenever you want to:
function checkin()
{
if ($this->_id)
{
$item= & $this->getTable();
if(! $item->checkin($this->_id)) {
$this->setError($this->_db->getErrorMsg());
return false;
}
}
return false;
}
function checkout($uid = null)
{
if ($this->_id)
{
// Make sure we have a user id to checkout the article with
if (is_null($uid)) {
$user =& JFactory::getUser();
$uid = $user->get('id');
}
// Lets get to it and checkout the thing...
$item= & $this->getTable();
if(!$item->checkout($uid, $this->_id)) {
$this->setError($this->_db->getErrorMsg());
return false;
}
return true;
}
return false;
}
To mark item as checked, first of all you have to have column called checked_out with default value 0, also you need checked_out_time to store time, when item was checked out.
Hope it helps.

Resources