How to implement system wide conditions in Laravel 5.4 - laravel-5

I am creating a Laravel (v5.4) app in which a user can create several 'organisations' and each organisation can have several 'projects'. But at any given time, the user will be working on one organisation only. The user can select the current working organisation by selecting from the list of organisations displayed in the top-menu along with the user`s name. Now, I want that when a project create page is displayed, rather than providing a dropdown to select the organisation, the system should know the selected organisation and create the project under this organisation only. There are many other things to be created like, surveys, tasks etc. and the system must select the default organisation instead of getting it from a dropdown list.
Till now, I have tried to accomplish it by setting the 'organisation_id' in session and retrieving it from session on all the create forms but I was wondering if there is any better way of achieving this?

The session is a very appropriate place to store this information. You could add a layer using a middleware to check that the organization_id is stored in session between requests and also as a security against user's somehow accessing organizations they don't belong to by checking that the user's id does belong to it. For example:
class CanAccessOrganization
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (!session('organization_id')) {
// default to the user's first organization.
session(['organization_id', Auth::user()->organizations->first()->id]);
} else {
// does this user belong to the organization?
$organization = Organization::find(session('organization_id'));
if (!in_array($organization->id, Auth::user()->organizations->pluck('id')->all()) {
// unauthorized! stop the request
abort(403);
}
// set (or reset) the session
session(['organization_id', $organization->id]);
}
return $next($request);
}
}

Related

How do i track an order using laravel lumen?

I'm integrating APIs that will be connected to an E-Commerce platform. I'm supposed to add an option to track orders, how do I do that?
Also, there's no frontend yet so I'm using postman to test all the API's.
the orders go through different locations on their way to the buyer, and I'd like the customer to now at which station their item is
php artisan make:observer OrderObserver
then something in the observer like this:
/**
* Handles the correct fields when updating
* #param Order $order
* #return void
*/
public function updating(User $user)
{
if($order->isDirty('some_column_you_use_to_change_status')) {
$someStatusTable = SomeStatusTable::where('track_id', $order->track_id)->first();
$someStatusTable->status = "whateverYOUwant";
}
}
I really don't know your logic but i think this could be something.
by the wat ->isDirty() watches if columns were changed.
you can also get the $order->getOriginal(('some_column_you_use_to_change_status')
I use this for example history of a Model to register history or even set new versions in my models

Laravel 8 Mail Notifications

I'm using Laravel 8, and my Client asks to be able to modify the mailables content.
I need to show the different notification templates, and let the users add text, action buttons, etc.
I'm thinking on building a DB structure to store the different fields with the corresponding order, but I'm not sure if it is possible to apply that on the toMail method.
For example: a NotificationTemplate Model that hasMany NotificationField (this can have type and content).
And then try to use it as a query builder:
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
$fields = NotificationTemplate::where('name', 'example')->fields;
$mail = (new MailMessage);
foreach($fields as $field){
if($field->$type = 'line'){
$mail->line($field->content);
}
}
return $mail;
}
Is this possible? Or is there another way to allow the admins of a Laravel 8 app to modify the Mail notificiation message from the frontend?
Thanks, HernĂ¡n.
You can simply give the admin a textarea where he can customize the content of email.
I use this package armincms/option to stock the content and in your template email you can use option()->content

Add extra question to Laravel forgotten password form and custom its error messages

I'd like to customize the forgotten password form in Laravel.
When asking to reset the password, the user will have to answer a simple question (the name your first pet, the name of your childhood best friend, etc) besides inserting his/her email. This is to avoid other people asking password reset if they know the account's email, but are not the owner of the account.
I also would like to custom the errors messages to, actually, not show errors. For example, if an invalid email is inserted, it would not show the error message "We can't find a user with that e-mail address." I don't like it because someone may guess the email of a user by trying different emails until she/he stops getting the error message. Instead, I would like to show the message "If the information provided is correct, you will receive an email with the link to reset your password."
How to add these functionalities to Laravel auth?
I am looking for a solution that I don't have to create an entire login system from scratch (I think that if I try to design everything from scratch I'd probably miss something and create security vulnerabilities). I'd like to keep the Laravel auth system and just add these two features.
Feel free to suggest other ways to achieve the desired result and to make my question clearer. I'll appreciate that.
The good news is you don't need to rewrite everything.
The bad news is, you need to understand traits and how to extend/override them, which can be a little confusing.
The default controller that Laravel creates ForgotPasswordController doesn't do much. Everything it does is in the trait. The trait SendsPasswordResetEmails contains a few methods, most importantly for the validation in validateEmail method.
You can override this validateEmail method with one that checks for an answered question. You override traits by altering the 'use' statement.
For example change;
use SendsPasswordResetEmails
to:
use SendsPasswordResetEmails {
validateEmail as originValidateEmail
}
This will tell the code to re-name the original method validateEmail to originValidateEmail allowing you to create a new validateEmail in your own ForgotPasswordController.
You can then, inside ForgotPasswordController add a replacement which will be called by the default reset password code:
protected function validateEmail(Request $request)
{
// add in your own validation rules, etc.
$request->validate(['email' => 'required|email', 'questionfield' => 'required']);
}
To alter the error message, you can simply edit the language file found in resources/lang/en/passwords.php
Hope that helps.
Thanks to the user #Darryl E. Clarke, I managed to solve the problem. Here is what I did:
Add this line at the top of the file ForgotPasswordController, after namespace:
use App\User;
Add these 3 methods in the same file:
/**
* Send a reset link to the given user.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
*/
public function sendResetLinkEmail(Request $request)
{
$this->validateRequest($request);
// We will send the password reset link to this user. Regardless if that
// worked, we will send the same response. We won't display error messages
// That is because we do not want people guessing the users' email. If we
// send an error message telling that the email is wrong, then a malicious
// person may guess a user' email by trying until he/she stops getting that
// error message.
$user = User::whereEmail($request->email)->first();
if ($user == null) {
return $this->sendResponse();
}
if ($user->secrete_question != $request->secrete_question) {
return $this->sendResponse();
}
$this->broker()->sendResetLink(
$this->credentials($request)
);
return $this->sendResponse();
}
/**
* Validate the given request.
*
* #param \Illuminate\Http\Request $request
* #return void
*/
protected function validateRequest(Request $request)
{
$request->validate(['email' => 'required|email', 'secrete_question' => 'required|string']);
}
/**
* Get the response for a password reset link.
*
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
*/
protected function sendResponse()
{
$response = 'If the information provided is correct, you will receive an email with a link to reset your password.';
return back()->with('status', $response);
}
Customize it the way you want.
Hope that it will helps others!!

Joomla! 3.xx *onUserLogout* event not working

I have successfully implemented the onUserAuthenticate event to implement my custom authentication API inside the Joomla! site that I am working on.
Now I want to also have some custom code run on the onUserLogout event.
I have added the following code to the custom authentication plugin file.
But this method is not getting fired/invoked while the previous one(onUserAuthenticate) is working just fine.
/**
* Method to handle the SSO logout
*
* #param array $user Holds the user data.
* #param array $options Array holding options (client, ...).
*
* #return boolean Always returns true.
*
* #since 1.6
*/
public function onUserLogout($user, $options = array()) {
if (JFactory::getApplication()->isSite()) {
// Set the cookie to expired date.
setcookie('customAuth', '123', time() - (60 * 60 * 24 * 365), '/', '.customdomain.org');
}
return true;
}
Okay so I was getting it all wrong.
So I was adding the aforementioned method inside the same plugin file that handled the onUserAuthenticate.
For Joomla! the login is a separate process which has its respective events like onUserAuthenticate.
But it seems like the event onUserLogout has to be inside the plugin with the type of user.
So I created a separate plugin inside the user plugin type directory, installed it, and enabled it....And voila!! it worked.
This had me scratching my head for quite a while.

How to get order store config variable in Admin

I created a module where it return via xml the payment details in Magento Admin order page.
It works very well with a single store config data.
But if I have diferents payment credentials for Store Id 1 and store Id 2 [p.e. for backoffice key 1111-1111-1111-1111 (store 1) and other 2222-2222-2222-2222 (store 2), I only can return the default values for admin view with this function...
$subent_id = Mage::getStoreConfig('payment/multibancopayment/subentidade');
Does any one khow how i can get store specific data based in order store id?
Example: in admin order page details, if the order was made in store 1 I need 1111-1111-1111-1111, but if was made in store 2, I need 2222-2222-2222-2222. For now I'm just getting default values with the function above.
Did you try
$subent_id = Mage::getStoreConfig('payment/multibancopayment/subentidade', $storeIdHere);
See /app/Mage.php
/**
* Retrieve config value for store by path
*
* #param string $path
* #param mixed $store
* #return mixed
*/
public static function getStoreConfig($path, $store = null)
{
return self::app()->getStore($store)->getConfig($path);
}
Entire class here

Resources