I've started a Silex project a week ago and still getting some issues within the service-container. Although being quite simple.
Here is what happens to me:
$app->post('/', function (Request $request) use ($app) {
$success = (new \Malendar\Application\Service\User\LoginUserService($app['user_repository'], $app['session']))->execute($request);
if ($success) {
return $app->redirect($app["url_generator"]->generate("calendar"));
} else {
return new Response($app['twig']->render('login.html', ['formError' => true]), 400);
}});
I've created a LoginUserService class that given my user respository and the session service I'm able to login the user, that means, compare to database and checking that both username and password are in the system. That works perfectly but the issue comes with the session provider. Here is the class code:
class LoginUserService implements ApplicationServiceInterface
{
private $userRepository;
private $session;
public function __construct(UserCaseRepository $userRepository, Session $session)
{
$this->userRepository = $userRepository;
$this->session = $session;
}
public function execute($request = null)
{
// TODO: Implement execute() method.
$userName = $request->get('user');
$password = $request->get('password');
$user = $this->userRepository->findByUsername($userName);
var_dump($user);
if (!empty($user) && $user->validate($password)) {
$this->session->start();
$this->session->set('id', $user->getUserId());
$this->session->set('username', $user->getName());
$this->session->set('email', $user->getEmail());
$this->session->save();
return true;
} else {
return false;
}
}
}
$this->session which I believe gets the app['session'] do not set the value of username, email and id, they remain null, and I can assure you that all data is well provided.
On the other hand, If I'm doing it outside the class, it works and the username it is set:
$app->post('/', function (Request $request) use ($app) {
$success = (new \Malendar\Application\Service\User\LoginUserService($app['user_repository'], $app['session']))->execute($request);
$app['session']->set('username', 'Pedro');
But of course it would like to pursue the usage of my loginService what do I am missing?
Thank you beforehand =)
Related
I am seeing some behaviour. I can't explain when accessing user data via the Auth facade in Laravel class. Here's an extract of my code:
private $data;
private $userID;//Set property
function __construct()
{
$this->middleware('auth');//Call middleware
$this->userID = Auth::id();//Define property as user ID
}
public function index() {
return view('');
}
public function MyTestMethod() {
echo $this->userID;//This returns null
echo Auth::id();//This works & returns the current user ID
}
I am logged in and have included use Illuminate\Support\Facades\Auth; in the class thus the code works, but only when accessing Auth in methods - else it returns a null value.
Most odd, I can't work out what is causing this. Any thoughts much appreciated as ever. Thanks in advance!
In Laravel Laravel 5.3.4 or above, you can't access the session or authenticated user in your controller's constructor, since the middlware isn't runnig yet.
As an alternative, you may define a Closure based middleware directly in your controller's constructor.:
try this :
function __construct()
{
$this->middleware(function ($request, $next) {
if (!auth()->check()) {
return redirect('/login');
}
$this->userID = auth()->id(); // or auth()->user()->id
return $next($request);
});
}
another alternative solution go you your base controller class and add __get function like this :
class Controller
{
public function __get(string $name)
{
if($name === 'user'){
return Auth::user();
}
return null;
}
}
and now if your current controller you can use it like this $this->user:
class YourController extends Controller
{
public function MyTestMethod() {
echo $this->user;
}
}
You should try this :
function __construct() {
$this->userID = Auth::user()?Auth::user()->id:null;
}
OR
public function __construct()
{
$this->middleware(function ($request, $next) {
$this->userID = Auth::user()->id;
return $next($request);
});
}
When I am trying to send mail, everytime a new member is added to the user table, so that they can get a setup password link. I have been trying to get this to work but seem not to be.
public function store(AddUser $request)
{
$user = $request->all();
$user['activate'] = $this->active();
$user['guid'] = $this->guid();
$user['accountno'] = $this->generateAndValidateAccountno();
$check = User::find($user['phone']);
if(!$check) {
$id = User::create($user);
$this->sendEmail($user['accountno']);
}
return redirect('employee');
}
public function sendEmail(Request $request, $id)
{
$user = User::find($id);
Beautymail::send('emails.welcome', [], function($message)
{
$message
->to('$id->email', '$id->fname')
->subject('Welcome!');
});
}
}
Not sure what am doing wrong
Just use the same request class in the controller and the model. In your user model, add use Illuminate\Http\Request at the top of the class to tell it which Request class to use.
Just change:
public function sendEmail(Request $request, $id){...}
to
public function sendEmail($id){...}
I have added a custom authentication component for a Yii2 RESTful project and it is validating credentials OK but it is not returning the valid User object to \Yii::$app->user
The component looks like this:
public function authenticate($user, $request, $response) {
$bearerToken = \Yii::$app->getRequest()->getQueryParam('bearer_token');
$user = Account::findIdentityByAccessToken($bearerToken);
return $user;
}
And the Account model method looks like this:
public static function findIdentityByAccessToken($token, $userType = null) {
return static::findOne(['bearer_token' => $token]);
}
I can see $user is the expected record of Account when debugging in the authenticate() method but \Yii::app()->user seems to be a newly instatiated user. \Yii::app()->user->identity is equal to null.
Can anyone see what I'm doing wrong here?
To login user this is not enough:
Account::findIdentityByAccessToken($bearerToken);
You need to call $user->login($identity) inside authentificate(). See for example how it's implemented in yii\web\User loginByAccessToken():
public function loginByAccessToken($token, $type = null)
{
/* #var $class IdentityInterface */
$class = $this->identityClass;
$identity = $class::findIdentityByAccessToken($token, $type);
if ($identity && $this->login($identity)) {
return $identity;
} else {
return null;
}
}
So you can also call it in your custom auth method:
$identity = $user->loginByAccessToken($accessToken, get_class($this));
See for example how it's implemented in yii\filters\auth\QueryParamAuth.
And you also need to return $identity, not $user. Also handling failure is missing in your code. See how it's implemented in built-in auth methods:
HttpBasicAuth
HttpBearerAuth
QueryParamAuth
More from official docs:
yii\web\User login()
yii\filters\auth\AuthInterface
Update:
Nothing forces you to use loginByAccessToken(), I just mentioned it as an example.
Here is an example of custom auth method that I wrote quite a while ago, not sure if it's 100% safe and true, but I hope it can help you to understand these details:
Custom auth method:
<?php
namespace api\components;
use yii\filters\auth\AuthMethod;
class HttpPostAuth extends AuthMethod
{
/**
* #see yii\filters\auth\HttpBasicAuth
*/
public $auth;
/**
* #inheritdoc
*/
public function authenticate($user, $request, $response)
{
$username = $request->post('username');
$password = $request->post('password');
if ($username !== null && $password !== null) {
$identity = call_user_func($this->auth, $username, $password);
if ($identity !== null) {
$user->switchIdentity($identity);
} else {
$this->handleFailure($response);
}
return $identity;
}
return null;
}
}
Usage in REST controller:
/**
* #inheritdoc
*/
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => HttpPostAuth::className(),
'auth' => function ($username, $password) {
$user = new User;
$user->domain_name = $username;
// This will validate password according with LDAP
if (!$user->validatePassword($password)) {
return null;
}
return User::find()->username($username)->one();
},
];
return $behaviors;
}
Specifying $auth callable is also can be found in HttpBasicAuth.
I have functions setAttribute($key, $value) and getAttribute($key, $default) in my User class. When the user is authenticated I want to set several attributes to be set that will be used later in various controllers.
I tried setting the attributes in my success handler function:
public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
$token->getUser()->setAttribute("user_data_set", 1);
}
But when I tried calling it in my controller the value has not been set
public function indexAction(Request $request) {
//Get the logged in user
$user = $this->getUser();
//Entity Manager
$em = $this->getDoctrine()->getManager();
// this page is just used as the starting point to redirect the user to the appropriate page
if($user->getAttribute("user_data_set", 0) == 1)
{
//Get Symfony1 route from the user data table
$old_homepage = $user->getAttribute("user_homepage", "#default_homepage");
//Convert route to Symfony2 format
$new_homepage = $this->setForwardingAddress($old_homepage);
return $this->redirect($this->generateUrl($new_homepage));
}
else
{
return $this->redirect('login');
}
}
How can I modify the global user instead of a local reference?
You obviously want cross-request solution so you'll need to use DB or session.
For example:
// Injecting Session service
public function __construct(Session $session){
$this->session = $session
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
$this->session->set('user_data_set', 1);
}
And then in your controller:
$foo = $session->get('user_data_set');
Is this what you wanted?
I'm using laravel (4.2) framework to develop a web application (PHP 5.4.25). I've create a repository-interface that was implemented with eloquent-repository, I use that repository inside a UserController:
# app/controllers/UsersController.php
use Gas\Storage\User\UserRepositoryInterface as User;
class UsersController extends \BaseController {
protected $user;
public function __construct(User $user) {
$this->user = $user;
}
public function store() {
$input = Input::all();
$validator = Validator::make(Input::all(), $this->user->getRoles());
if ( $validator->passes() ) {
$this->user->getUser()->username = Input::get('username');
$this->user->getUser()->password = Hash::make(Input::get('password'));
$this->user->getUser()->first_name = Input::get('first_name');
$this->user->getUser()->last_name = Input::get('last_name');
$this->user->getUser()->email = Input::get('email');
$this->user->save();
return false;
} else {
return true;
}
}
}
My Repository implementation:
namespace Gas\Storage\User;
# app/lib/Gas/Storage/User/EloquentUserRepository.php
use User;
class EloquentUserRepository implements UserRepositoryInterface {
public $_eloquentUser;
public function __construct(User $user) {
$this->_eloquentUser = $user;
}
public function all()
{
return User::all();
}
public function find($id)
{
return User::find($id);
}
public function create($input)
{
return User::create($input);
}
public function save()
{
$this->_eloquentUser->save();
}
public function getRoles()
{
return User::$rules;
}
public function getUser()
{
return $this->_eloquentUser;
}
}
I've also create a UsersControllerTest to testing the controller and all works fine, the user was added to the DB. After I mocked my UserRepositoryInterface because I don't need to test the DB insert, but I just want to test the controller
class UsersControllerTest extends TestCase {
private $mock;
public function setUp() {
parent::setUp();
}
public function tearDown() {
Mockery::close();
}
public function mock($class) {
$mock = Mockery::mock($class);
$this->app->instance($class, $mock);
return $mock;
}
public function testStore() {
$this->mock = $this->mock('Gas\Storage\User\UserRepositoryInterface[save]');
$this->mock
->shouldReceive('save')
->once();
$data['username'] = 'xxxxxx';
$data['first_name'] = 'xxxx';
$data['last_name'] = 'xxxx';
$data['email'] = 'prova#gmail.com';
$data['password'] = 'password';
$data['password_confirmation'] = 'password';
$response = $this->call('POST', 'users', $data);
var_dump($response->getContent());
}
}
My ruote file:
Route::resource('users', 'UsersController');
When I run the test I get the following error:
Mockery\Exception\InvalidCountException : Method save() from Mockery_0_Gas_Storage_User_UserRepositoryInterface should be called
exactly 1 times but called 0 times.
Why the mocked method save has not be called?
What is wrong?
EDIT: without partial mock all works fine, now the question is: why with partial mock it doesn't work?
Thanks
Looking back at your code, it seems like you should be able to use partial mocks just by changing your mock function to something like this:
public function mock($class) {
$mock = Mockery::mock($class);
$ioc_binding = preg_replace('/\[.*\]/', '', $class);
$this->app->instance($ioc_binding, $mock);
return $mock;
}
You are telling the mock to expect the save() method, but the save() is on the Eloquent model inside the Repository, not the Repository you are mocking.
Your code is currently leaking details of the implementation of the Repository.
Instead of calling:
$this->user->getUser()->username = Input::get('username');
You need to pass an instance of the User into the Repository:
$this->user->add(User::create(Input::all());
Or you pass the array of Input into the Repository and allow the Repository to create a new User instance internally:
$this->user->add(Input::all());
You would then mock the add() method in your test:
$this->mock->shouldReceive('add')->once();
The comments about Laravel not being suited for mocking or unit testing are wrong.