How to send error log through email with laravel 5.6 and monolog - swiftmailer

In laravel 5.6 documentation it says You can use a different driver from the defaults when You create a log
Creating Monolog Handler Channels
So I tried the following in the config/logging.php file
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['masterLog', 'daily'],
],
'email' => [
'driver' => 'monolog',
'handler' => Monolog\Handler\SwiftMailerHandler::class,
'with' => [
'mailer' => Mail::to('test#test.com')->send(new App\Mail\TestMail()),
],
'level' => 'debug',
],
I created my own email channel with the handler Monolog\Handler\SwiftMailerHandler::class and I noticed the class constructor recives a mailer object so I try this
Mail::to('test#test.com')->send(new App\Mail\TestMail())
but I get the following error
RuntimeException
A facade root has not been set.
I'm testing the error by this way
try {
throw new Exception('Test Error');
} catch (\Exception $e) {
Log::stack(['datePayments', 'stack', 'email'])->emergency("user error", ['error' => $e, 'userID'=>Auth::id()]);
}
So how can I configure this to make it works?

Theres a package here https://github.com/designmynight/laravel-log-mailer that adds a mail driver to Laravel's LogManager which should do exactly what you are after.

Related

Laravel: How to set my custom password broker to be used by Password::sendResetLink?

The documentation of Laravel says:
You may be wondering how Laravel knows how to retrieve the user record from your application's database when calling the Password facade's sendResetLink method. The Laravel password broker utilizes your authentication system's "user providers" to retrieve database records. The user provider used by the password broker is configured within the passwords configuration array of your config/auth.php configuration file. To learn more about writing custom user providers, consult the authentication documentation
But how to set my custom password broker users:foo to be used by Password::sendResetLink in my custom package packages/custom-packages/foo/src/routes/api.php?
Route::post('forgot-password', function (Request $request) {
$request->validate(['email' => 'required|email|exists:foo.users,email']);
$status = Password::sendResetLink(
$request->only('email')
);
return $status === Password::RESET_LINK_SENT
? response()->json(['status' => __($status)])
: response()->json(['email' => __($status)]);
});
Below is my config/auth.php:
...
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
'users:foo' => [
'provider' => 'users:foo',
'table' => 'foo.password_resets',
'expire' => 60,
'throttle' => 60,
]
]
Sets your broker through the facade.
use Illuminate\Support\Facades\Password;
$broker = 'users:foo'; // the default value is 'users' from 'auth.defaults.passwords'.
Password::broker($broker); // sets the given broker
It will get config from "auth.passwords.{$name}" where $name is $broker.
If the config of the broker is undefined then throws the exception: "Password resetter [{$name}] is not defined.". In the good way will be created a new password broker with your config.

Laravel logging to to custom channel does not consider minimum level

So i made a custom logging handler with a custom logger to log to db, and it works correctly.
What i cannot manage to work is the minimum loggin level define in the configuration.
To test it i made a stack with single and my custom channel (let's call it database), hanving both a error level, and logged a message for every log level with artisan: the daily file contains 4 messages, but my custom channel has 8 messages while i expected only 4.
Testing with a stack of single and daily instead work correctly, so this makes me think that i have to handle the minimum loggin level in my custom classes, but i couldn't find anywhere something that tells it explicitly.
Is not a problem to update my custom classes to check the log level, but i want to be sure that i'm not mistaking something else about laravel logging.
config/logging.php
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['single', 'daily'],
//'channels' => ['single', 'database'],
'ignore_exceptions' => false,
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => 'error',
],
'database' => [
'driver' => 'custom',
'handler' => App\Logging\CustomLoggingHandler::class,
'via' => App\Logging\CustomLogger::class,
'level' => env('MIN_DB_LOGGING_LEVEL', 'error'),
],
],

Laravel LDAP (Adldap2) Can't authenticate,username is null into guard->attempt

Morning,
I keep getting the message "A username must be specified." when trying to login my app.
Connection to LDAP is OK, sync also, in my database/table users i see all username with password.
But can't login with anyone username.
Trying to dd($username) into LoginController, "guard()->attempt" show me "null".
Thanks for your help !
My version
Laravel Version: ^7.0
Adldap2-Laravel Version: ^6.1
PHP Version: ^7.2.5
LDAP Type: OpenLDAP
my .env
LDAP_HOSTS=ldap.forumsys.com
LDAP_BASE_DN=dc=example,dc=com
LDAP_USERNAME=cn=read-only-admin,dc=example,dc=com
LDAP_PASSWORD=password
LDAP_PASSWORD_SYNC=true
my ldap.php
<?php
return [
'logging' => env('LDAP_LOGGING', false),
'connections' => [
'default' => [
'auto_connect' => env('LDAP_AUTO_CONNECT', true),
'connection' => Adldap\Connections\Ldap::class,
'settings' => [
'schema' => Adldap\Schemas\OpenLDAP::class,
'account_prefix' => env('LDAP_ACCOUNT_PREFIX', ''),
'account_suffix' => env('LDAP_ACCOUNT_SUFFIX', ''),
'hosts' => explode(' ', env('LDAP_HOSTS', 'corp-dc1.corp.acme.org corp-dc2.corp.acme.org')),
'port' => env('LDAP_PORT', 389),
'timeout' => env('LDAP_TIMEOUT', 5),
'base_dn' => env('LDAP_BASE_DN', 'dc=corp,dc=acme,dc=org'),
'username' => env('LDAP_USERNAME', 'username'),
'password' => env('LDAP_PASSWORD', 'secret'),
'follow_referrals' => false,
'use_ssl' => env('LDAP_USE_SSL', false),
'use_tls' => env('LDAP_USE_TLS', false),
],
],
],
];
my ldap_auth
<?php
return [
'connection' => env('LDAP_CONNECTION', 'default'),
'provider' => Adldap\Laravel\Auth\DatabaseUserProvider::class,
'model' => App\User::class,
'rules' => [
// Denys deleted users from authenticating.
Adldap\Laravel\Validation\Rules\DenyTrashed::class,
// Allows only manually imported users to authenticate.
// Adldap\Laravel\Validation\Rules\OnlyImported::class,
],
'scopes' => [
// Only allows users with a user principal name to authenticate.
// Suitable when using ActiveDirectory.
// Adldap\Laravel\Scopes\UpnScope::class,
// Only allows users with a uid to authenticate.
// Suitable when using OpenLDAP.
// Adldap\Laravel\Scopes\UidScope::class,
],
'identifiers' => [
'ldap' => [
'locate_users_by' => 'uid',
'bind_users_by' => 'distinguishedname',
],
'database' => [
'guid_column' => 'objectguid',
'username_column' => 'username', //'email',
],
'windows' => [
'locate_users_by' => 'samaccountname',
'server_key' => 'AUTH_USER',
],
],
'passwords' => [
'sync' => env('LDAP_PASSWORD_SYNC', false),
'column' => 'password',
],
'login_fallback' => env('LDAP_LOGIN_FALLBACK', false),
'sync_attributes' => [
//'email' => 'userprincipalname',
'username' => 'uid',
'name' => 'cn',
],
'logging' => [
'enabled' => env('LDAP_LOGGING', true),
'events' => [
\Adldap\Laravel\Events\Importing::class => \Adldap\Laravel\Listeners\LogImport::class,
\Adldap\Laravel\Events\Synchronized::class => \Adldap\Laravel\Listeners\LogSynchronized::class,
\Adldap\Laravel\Events\Synchronizing::class => \Adldap\Laravel\Listeners\LogSynchronizing::class,
\Adldap\Laravel\Events\Authenticated::class => \Adldap\Laravel\Listeners\LogAuthenticated::class,
\Adldap\Laravel\Events\Authenticating::class => \Adldap\Laravel\Listeners\LogAuthentication::class,
\Adldap\Laravel\Events\AuthenticationFailed::class => \Adldap\Laravel\Listeners\LogAuthenticationFailure::class,
\Adldap\Laravel\Events\AuthenticationRejected::class => \Adldap\Laravel\Listeners\LogAuthenticationRejection::class,
\Adldap\Laravel\Events\AuthenticationSuccessful::class => \Adldap\Laravel\Listeners\LogAuthenticationSuccess::class,
\Adldap\Laravel\Events\DiscoveredWithCredentials::class => \Adldap\Laravel\Listeners\LogDiscovery::class,
\Adldap\Laravel\Events\AuthenticatedWithWindows::class => \Adldap\Laravel\Listeners\LogWindowsAuth::class,
\Adldap\Laravel\Events\AuthenticatedModelTrashed::class => \Adldap\Laravel\Listeners\LogTrashedModel::class,
],
],
];
my loginController
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function username()
{
return 'username';
}
}
Been through this pain myself.
It looks like you are connecting to LDAP with your service account, but I don't see where you are logging the authenticated user into Laravel. Do your users have to supply a username and password on a screen somewhere? If not, how do you grab the user and log them in to Laravel?
The way I did this in the businesses that had to go through LDAP was to have the normal Laravel login page, but a middle method within the login controller which sent a message to LDAP through the service account with the PW. If this succeeded, then login with Laravel's standard method. Basically just check the PW against LDAP and then log in rather than checking against the Laravel DB.
Example code - this will vary wildly but can give you an idea of what might work:
if(env('LOGIN', false) === 'LDAP'){
$ldap = new \App\Http\Controllers\ClientSpecific\BaseLDAPController();
$username = $request->input('username');
if($ldap->authenticate($username, $request->input('password'))){
return $this->sendLoginResponse($request);
}
}else {
if ($this->guard()->attempt($credentials, $request->has('remember'))) {
return $this->sendLoginResponse($request);
}
}
I know this is an old question, but I was still facing this issue even in 2020 and it took a lot of my time. Actually the problem is very silly if you are also trying to bind an OpenLDAP server with your Laravel application using Adldap2-Laravel package.
Adldap2-Laravel is by default configured for Microsoft's Active Directory. But for OpenLDAP, we need to properly change the Identifiers array as follows..
<?php
return [
// configurations settings...
'identifiers' => [
'ldap' => [
'locate_users_by' => 'uid', // changed from userprincipalname
'bind_users_by' => 'dn', // changed from distinguishedname
],
'database' => [
'guid_column' => 'objectguid',
'username_column' => 'username', //'email',
],
'windows' => [
'locate_users_by' => 'samaccountname',
'server_key' => 'AUTH_USER',
],
],
// rest of the configurations...
];
Do tell me if my answer is not clear for new comers since I'm also a newbie. I'll try to explain the solution further better :)

Creating Custom BigQueryHandler in Laravel

Hello there I am supposed to transfer artisan logs to bigquery and store it. I wrote Custom Channel
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['daily', 'bigquery'],
],
'bigquery' => [
'driver' => 'custom',
'level' => 'debug',
'via' => BigQueryHandler ::class,
'with' => [
'bq_dataset_name' => 'something',
'bq_table_name' => 'something_com_logs'
]
],
I have wrote BigQueryHandler class to write those logs using write() method. I have also wrote test case which works fine and updates the record in bigquery table. but If I invoke bigquery channel from artisan files it doesnt work. Can someone tell me whats wrong here?
the command to invoke bigquery channel is
\Log::channel('bigquery')->info('Something happened!');"
Have written it inside handle().

how to stop execution of ctp file in cakephp 2.x after validating the url

In my CakePHP application, I have applied Url validations so that admin can access only those actions which are defined for admin and same as with users.
In my application, "surveylist" is the action of admin and when any user directly access that action(surveylist), URL validations work(Unauthorized access msg is displayed).
But below that message ctp file of surveylist executes forcefully and show errors because I have validated URL through the try-catch block and it cannot get the set variables of action.
I want that ctp file should not execute if unauthorize error comes.
My code for surveylist is:-
public function surveylist($pg=null){
try{
if($this->checkPageAccess($this->params['controller'] . '/' . $this->params['action'])){
$this->Paginator->settings = array(
'Survey' => array(
'limit' => 5,
'order' => 'created desc',
'conditions'=>array('is_deleted'=> 0),
'page' => $pg
)
);
$numbers = $this->Paginator->paginate('Survey');
$this->set(compact('numbers'));
}else{
$this->Flash->set(__('Unauthorised access'));
}
}catch(Exception $e){
$this->Flash->set(__($e->getMessage()));
}
}
I don't want the ctp file of surveylist to execute if control comes to else.
Plz, help me out......
Thanx in advance...
I suppose you are using prefix to separate admin and users, if not please do that it is great way to handle and restrict methods.
After doing that you have to make condition to check which prefix(admin, user) is currently active and according that load Auth component and allow action in allow() method of Auth.
Example:
$this->loadComponent('Auth',[
/*'authorize' => [
'Acl.Actions' => ['actionPath' => 'controllers/']
],*/
'loginRedirect' => [
'controller' => 'Users',
'action' => 'index'
],
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
'password' => 'password'
]
]
],
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
],
'unauthorizedRedirect' => [
'controller' => 'Users',
'action' => 'login',
'prefix' => false
],
'authError' => 'You are not authorized to access that location.',
]);
if ($this->request->params['prefix']=='admin') {
// Put actions you want to access to admin in allow method's array
$this->Auth->allow(array('add', 'edit', etc...));
} else if ($this->request->params['prefix']=='user') {
// Put actions you want to access to user in allow method's array
$this->Auth->allow(array('login', 'view', etc...));
}
This way you can restrict actions for particular role.
Hope this helps!

Resources