I am using the basic login and registration scaffold that comes with Laravel 5.3. I've also created a logging function so that I can log some of the basic user actions for my platform, such as updating or deleting records.
I'd like to add the logging to the user login process so that I can log when they've logged in and a failed attempt. Because I'm using the basic included scaffolding, I'm not sure where to do this?
If you want to hook into login process and just log something. Consider hooking into the authentication events provided by Laravel's Authentication events
/**
* The event listener mappings for the application.
*
* #var array
*/
protected $listen = [
'Illuminate\Auth\Events\Registered' => [
'App\Listeners\LogRegisteredUser',
],
'Illuminate\Auth\Events\Attempting' => [
'App\Listeners\LogAuthenticationAttempt',
],
'Illuminate\Auth\Events\Authenticated' => [
'App\Listeners\LogAuthenticated',
],
'Illuminate\Auth\Events\Login' => [
'App\Listeners\LogSuccessfulLogin',
],
'Illuminate\Auth\Events\Failed' => [
'App\Listeners\LogFailedLogin',
],
'Illuminate\Auth\Events\Logout' => [
'App\Listeners\LogSuccessfulLogout',
],
'Illuminate\Auth\Events\Lockout' => [
'App\Listeners\LogLockout',
],
];
Related
i created laravel cms using vue and axios.
i want get current user that sending post requests
so i followed laravel api documentation and take this structure
// bootstrap.js
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
window.axios.defaults.headers.common['Authorization'] = `Bearer ${window.api_token}`;
// vue component file
axios.post('/api/v1/person', this.person)
.then(data => {
this.$emit('added', data.data);
this.person.id = data.data.data.id
});
// Route in api.php
Route::prefix('v1')->name('api.')->group(function () {
/** Person Routes */
Route::prefix('person')->namespace('Person')->name('person.')->group(function(){
Route::post('/', 'PersonController#index');
});
});
//in laravel controller i retrun
return response()->json(auth('api')->user());
but i get this result
even i checked console headers and Authorization header set properly
i can get all post data but laravel don`t pass me the user
also i made a repository of this project in github
if you want can follow this link
https://github.com/mohammadZx/crm
In the documentation it states that you have to set the correct guard for Passport to work. Update auth.php config.
'guards' => [
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
by default, laravel trying to find user by hashing token and for this reason laravel return null because your user api tokens not hashed. so if you change auth.php setting to don't searching hashes api_tokens, this problem will be fixed
'guards' => [
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false
],
],
The problem that I can't use two SocialiteProviders at the same time
in file EventServiceProvider I have the following
protected $listen = [
'App\Events\SomeEvent' => [
'App\Listeners\EventListener',
],
\SocialiteProviders\Manager\SocialiteWasCalled::class => [
// add your listeners (aka providers) here
'SocialiteProviders\VKontakte\VKontakteExtendSocialite#handle',
],
\SocialiteProviders\Manager\SocialiteWasCalled::class => [
\JhaoDa\SocialiteProviders\Odnoklassniki\OdnoklassnikiExtendSocialite::class
],
];
So If the Odnoklassniki provider works, there is no possibility to use Vkontakte provider. It gives the following:
InvalidArgumentException in Manager.php line 90:
Driver [vkontakte] not supported.
And if I comment Odnoklassniki, Ir will not work also.
How to make it both work.
When you place another item with the same key of an array, it overwrites previous value. Just add them to one key:
protected $listen = [
'App\Events\SomeEvent' => [
'App\Listeners\EventListener',
],
\SocialiteProviders\Manager\SocialiteWasCalled::class => [
// add your listeners (aka providers) here
'SocialiteProviders\VKontakte\VKontakteExtendSocialite#handle',
\JhaoDa\SocialiteProviders\Odnoklassniki\OdnoklassnikiExtendSocialite::class
],
];
I have an existing Yii2 application and have been trying to implement a REST API as an additional module (Maybe a module isn't the correct way to go about this?) But I'm having some trouble configuring the route structures. It doesn't quite work and doesn't follow the expected results, based of the following guide.
I've built an additional module that looks like this:
module
api
controllers
UserController.php
Module.php
UserController.php
<?php
namespace app\modules\api\controllers;
use yii\rest\ActiveController;
class UserController extends ActiveController
{
public $modelClass = 'app\models\User';
}
Module.php
<?php
namespace app\modules\api;
/**
* onco module definition class
*/
class Module extends \yii\base\Module
{
public $defaultController = 'user';
/**
* #inheritdoc
*/
public $controllerNamespace = 'app\modules\api\controllers';
/**
* #inheritdoc
*/
public function init()
{
parent::init();
// custom initialization code goes here
}
}
In my config file I have the added following:
'request' => [
...
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
],
...
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => false, // have tried as true also
'rules' => [
...
['class' => 'yii\rest\UrlRule', 'controller' => '\app\modules\api\controllers\user'],
],
],
...
'modules' => [
...
'api' => [ // module for RESTful API
'class' => 'app\modules\api\Module',
],
]
When I run the following urls through postman I get the following:
http://localhost/site1/web/api/users -> 404
http://localhost/site1/web/api/users/index -> 404
http://localhost/site1/web/api/user/index -> returns json repsonse
http://localhost/site1/web/api/user/2 -> 404
I'm unsure as to why the predicted routes of noted in the docs as:
Trying it Out With the above minimal amount of effort, you have
already finished your task of creating the RESTful APIs for accessing
the user data. The APIs you have created include:
GET /users: list all users page by page;
HEAD /users: show the overview information of user listing;
POST /users: create a new user;
GET /users/123: return the details of the user 123;
HEAD /users/123: show the overview information of user 123;
PATCH /users/123 and PUT /users/123: update the user 123;
DELETE /users/123: delete the user 123;
OPTIONS /users: show the supported verbs regarding endpoint /users;
OPTIONS /users/123: show the supported verbs regarding endpoint /users/123
What have I likely done wrong in this setup? Is there a better way to implement an API into an existing website, whilst maintaining DRY practices?
try this:
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => ['api/user'],
]
]
],
...
'modules' => [
...
'api' => [
'basePath' => '#app/modules/api',
'class' => 'app\modules\api\Module',
],
]
Also be sure to implement prettyUrl's related server server configs.
Sometimes, we'd like to separate users and admins in different 2 tables.
I think it is a good practice.
I am looking if that is possible in Laravel 5.
Before reading the following, you are supposed to have basic knowledge on ServiceProvider, Facade and IoC in Laravel 5. Here we go.
According to the doc of Laravel, you could find the Facade 'Auth' is refering to the Illuminate\Auth\AuthManager, which has a magic __call(). You could see the major function is not in AuthManager, but in Illuminate\Auth\Guard
Guard has a Provider. This provider has a $model property, according to which the EloquentUserProvider would create this model by "new $model". These are all we need to know. Here goes the code.
1.We need to create a AdminAuthServiceProvider.
public function register(){
Auth::extend('adminEloquent', function($app){
// you can use Config::get() to retrieve the model class name from config file
$myProvider = new EloquentUserProvider($app['hash'], '\App\AdminModel')
return new Guard($myProvider, $app['session.store']);
})
$app->singleton('auth.driver_admin', function($app){
return Auth::driver('adminEloquent');
});
}
2.Facade:
class AdminAuth extends Facade {
protected static function getFacadeAccessor() { return 'auth.driver_admin'; }
}
3. add the alias to Kernel:
'aliases' => [
//has to be beneath the 'Auth' alias
'AdminAuth' => '\App\Facades\AdminAuth'
]
Hope this could be helpful.
I have created a laravel package where you can handle multiple authentication.
Step 1 : Composer require
Firstly, composer require the multiauth package
composer require sarav/laravel-multiauth dev-master
Step 2 : Replacing default auth service provider
Replace
Illuminate\Auth\AuthServiceProvider::class
with
Sarav\Multiauth\MultiauthServiceProvider
in your config/app.php file
Step 3 : Modify auth.php
Modify your config/auth.php file to something like this
'multi' => [
'user' => [
'driver' => 'eloquent',
'model' => App\User::class,
'table' => 'users'
],
'admin' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
'table' => 'admins'
]
],
Thats it! Now you can try multiple authentication by passing the user as first parameter. For example
\Auth::loginUsingId("user", 1); // Login user with id 1
\Auth::loginUsingId("admin", 1); // Login admin with id 1
// Attempts to login user with email id johndoe#gmail.com
\Auth::attempt("user", ['email' => 'johndoe#gmail.com', 'password' => 'password']);
// Attempts to login admin with email id johndoe#gmail.com
\Auth::attempt("admin", ['email' => 'johndoe#gmail.com', 'password' => 'password']);
For more detailed documentation
http://sarav.co/blog/multiple-authentication-in-laravel/
http://sarav.co/blog/multiple-authentication-in-laravel-continued/
How do I use zfc rbac role providers?
I understand guards prevent users from accessing routes but it seems like I need the role providers as well. Are these database permissions? In the example below is 'article' a controller and the part after the '.' the permission granted on that controller? How can I test these once in place? Many thanks.
return [
'zfc_rbac' => [
'role_provider' => [
'ZfcRbac\Role\InMemoryRoleProvider' => [
'admin' => [
'permissions' => [
'article.delete',
'article.edit',
'article.archive',
'article.read'
]
],
'member' => [
'permissions' => [
'article.edit',
'article.archive',
'article.read'
]
],
'guest' => [
'permissions' => ['article.read']
]
]
]
]
];
Here you can read about role providers
In ZF-Rbac one identity can have different roles with different permissions/privileges. To collect the roles for the authorizationService you need role providers. They will include a RoleProvicerInterface (link) with the getRoles method which is supposed to return the roles that the authorization service has to work with.
Each Identity has an IdentityInterface (link) which has also a getRoles method. This will return an array of roleNames which will be mapped to the roles from the RolesProvider to find out about permissions/privileges.
You can then find out what the current user (identity) is allowed to do.