As validatePassword() receives the user's password?
I not know how validatePassword() get password user.
$password - Getting here is assigned to the user's password?
<?php
namespace app\models;
class User extends \yii\base\Object implements \yii\web\IdentityInterface
{
public $id;
public $username;
public $password;
public $authKey;
public $accessToken;
private static $users = [
'100' => [
'id' => '100',
'username' => 'admin',
'password' => 'admin',
'authKey' => 'test100key',
'accessToken' => '100-token',
],
'101' => [
'id' => '101',
'username' => 'demo',
'password' => 'demo',
'authKey' => 'test101key',
'accessToken' => '101-token',
],
];
/**
* #inheritdoc
*/
public static function findIdentity($id)
{
return isset(self::$users[$id]) ? new static(self::$users[$id]) : null;
}
/**
* #inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
foreach (self::$users as $user) {
if ($user['accessToken'] === $token) {
return new static($user);
}
}
return null;
}
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByUsername($username)
{
foreach (self::$users as $user) {
if (strcasecmp($user['username'], $username) === 0) {
return new static($user);
}
}
return null;
}
/**
* #inheritdoc
*/
public function getId()
{
return $this->id;
}
/**
* #inheritdoc
*/
public function getAuthKey()
{
return $this->authKey;
}
/**
* #inheritdoc
*/
public function validateAuthKey($authKey)
{
Yii::info('Пароль validateAuthKey ----'.$authKey);
return $this->authKey === $authKey;
}
/**
* Validates password
*
* #param string $password password to validate
* #return boolean if password provided is valid for current user
*/
public function validatePassword($password)
{
return $this->password === $password;
}
}
THe code you show is the User.php model code in basic template application.
as you can see in site controller the action login call $model->login()
public function actionLogin()
{
if (!\Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) { // *** here
return $this->goBack();
}
return $this->render('login', [
'model' => $model,
]);
}
($model is obtained by new LoginForm();).
in $model->login (alias in LoginForm->login()) you have this code
/**
* Logs in a user using the provided username and password.
* #return boolean whether the user is logged in successfully
*/
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
}
return false;
}
this code perform the login
Related
How can I use two attributes in the Validation Rule of Laravel. This is my function where I have 2 variables groupid and grouppassword. Currently only groupid is taken.
public function groupPasswordValidationReal(Request $request){
$groupid = $request->input('groupid');
$grouppassword = $request->input('grouppassword');
$validator = \Validator::make($request->all(), [
'groupid' => [new ValidRequest] //How to pass grouppassword in this function???
]);
return redirect('home')->with('success', 'Request is send!');
}
How can I pass both to my Validation Class? Here you can see the functions in the Validation Class.
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use App\Group;
class ValidTest implements Rule
{
public function passes($attribute, $value)
{
//$value is groupid
$validPassword = Group::where([['idgroups', $value],['group_password', /*Here I need grouppassword*/]])->first();
if($validPassword){
return true;
}else{
return false;
}
}
public function message()
{
return 'Wrong Password!';
}
}
Add property and constructor to your ValidTest class. Pass the required value as an argument to the new object.
ValidTest.php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use App\Group;
class ValidTest implements Rule
{
/**
* The group password.
*
* #var string
*/
public $groupPassword;
/**
* Create a new rule instance.
*
* #param \App\Source $source
* #param string $branch
* #return void
*/
public function __construct($groupPassword)
{
$this->groupPassword = $groupPassword;
}
public function passes($attribute, $value)
{
//$value is groupid
//$this->groupPassword is group_password
$validPassword = Group::where([['idgroups', $value],['group_password', $this->groupPassword]])->first();
if($validPassword){
return true;
}else{
return false;
}
}
public function message()
{
return 'Wrong Password!';
}
}
Controller
public function groupPasswordValidationReal(Request $request){
$groupid = $request->input('groupid');
$grouppassword = $request->input('grouppassword');
$validator = \Validator::make($request->all(), [
'groupid' => new ValidTest($grouppassword)
]);
return redirect('home')->with('success', 'Request is send!');
}
Source : custom-validation-rules-in-laravel-5-5
Note : This is not a tested solution.
Use the Rule constructor like
class ValidUser implements Rule
{
private $grouppassword;
/**
* Create a new rule instance.
*
* #return void
*/
public function __construct($grouppassword)
{
$this->grouppassword = $grouppassword;
}
/**
* Determine if the validation rule passes.
*
* #param string $attribute
* #param mixed $value
* #return bool
*/
public function passes($attribute, $value)
{
// $this->grouppassword
// $groupid = $value
// Do your logic...
return true;
}
/**
* Get the validation error message.
*
* #return string
*/
public function message()
{
return 'The :attribute must something...';
}
}
Usage
Route::post('/user', function (Request $request) {
// Parameter validation
$validator = Validator::make($request->all(), [
'groupid' => 'required',
'grouppassword' => ['required', new ValidUser($request->groupid), ]
]);
if ($validator->fails())
return response()->json(['error' => $validator->errors()], 422);
});
I think you could use a closure there. So something like this:
$validator = \Validator::make($request->all(), function() use ($groupid, $grouppassword) {
$validPassword = Group::where([['idgroups', $value],['group_password', $grouppassword]])->first();
if($validPassword){
return true;
}else{
return false;
}
}
I haven't run it though.
If you are calling the validation from a Request class, you can access the extra value as e.g.
request()->validate([
'groupid' => [new ValidTest(request()->input('grouppassword'))]
]);
This is the error I am getting the at moment:
Type error: Argument 1 passed to Illuminate\Database\Eloquent\Relations\BelongsToMany::save()
must be an instance of Illuminate\Database\Eloquent\Model,
integer given,
called in /home/sasha/Documents/OffProjects/vetnearme/vetnearme/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php on line 814
The create user method, where I call the giveRole() method:
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
// On registration user will be given the default role of user
$user->giveRole();
$verifyUser = VerifyUser::create([
'user_id' => $user->id,
'token' => str_random(40)
]);
Mail::to($user->email)->send(new VerifyMail($user));
return $user;
}
HasPermissionsTrait:
<?php
namespace App\App\Permissions;
use App\{Role, Permission};
/**
*
*/
trait HasPermissionsTrait
{
public function giveRole($role = 'user')
{
$role = \DB::table('roles')->where('name', '=', $role)->first();
$this->roles()->saveMany([$role->id]);
return $this;
}
public function givePermission(...$permissions)
{
$permissions = $this->getPermissions(\array_flatten($permissions));
if($permissions === null)
return $this;
$this->permissions()->saveMany($permissions);
return $this;
}
public function widrawPermission(...$permissions)
{
$permissions = $this->getPermissions(\array_flatten($permissions));
$this->permissions()->detach($permissions);
return $this;
}
public function updatePermissions(...$permissions)
{
$this->permissions()->detach();
return $this->givePermission($permissions);
}
public function hasRole(...$roles)
{
foreach ($roles as $role) {
if($this->roles->contains('name', $role))
return true;
}
return false;
}
public function hasPermissionTo($permission)
{
return $this->hasPermissionThroughRole($permission) || $this->hasPermission($permission);
}
protected function hasPermission($permission)
{
return (bool) $this->permissions->where('name', $permission->name)->count();
}
protected function hasPermissionThroughRole($permission)
{
foreach ($permission->roles as $role) {
if($this->role->contains($role))
return true;
}
return false;
}
protected function getPermissions(array $permissions)
{
return Permissions::whereIn('name', $permissions)->get();
}
public function roles()
{
return $this->belongsToMany(Role::class, 'users_roles', 'user_id', 'role_id');
}
public function permissions()
{
return $this->belongsToMany(Permissions::class, 'users_permissions');
}
}
Role model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
public function permissions()
{
return $this->belongsToMany(Permissions::class, 'roles_permissions');
}
}
User model:
namespace App;
use App\App\Permissions\HasPermissionsTrait;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable, HasPermissionsTrait;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function clinic()
{
return $this->hasOne(Clinic::class, 'owner_id');
}
public function files()
{
return $this->hasMany('App/Media');
}
public function verifyUser()
{
return $this->hasOne('App\VerifyUser');
}
}
What am I doing wrong here?
Have you tried passing in the role model instead of the id? Also, on a separate note, it looks as if you might as well just call save as you are not actually ever utilizing an array in this instance.
trait HasPermissionsTrait
{
public function giveRole($role = 'user')
{
$role = \DB::table('roles')->where('name', '=', $role)->first();
$this->roles()->saveMany([$role]);
return $this;
}
}
saveMany calls save:
public function saveMany($models, array $joinings = [])
{
foreach ($models as $key => $model) {
$this->save($model, (array) Arr::get($joinings, $key), false);
}
$this->touchIfTouching();
return $models;
}
and save has typecasted Model, not int:
/**
* Save a new model and attach it to the parent model.
*
* #param \Illuminate\Database\Eloquent\Model $model
* #param array $joining
* #param bool $touch
* #return \Illuminate\Database\Eloquent\Model
*/
public function save(Model $model, array $joining = [], $touch = true)
{
$model->save(['touch' => false]);
$this->attach($model->getKey(), $joining, $touch);
return $model;
}
i try to login by email and password
auth::attempt success login but when redirect to link after login it logout by itself , on localhost all things good but when i upload my project on host this problem occured
login function
public function login(){
$validator=Validator::make(Input::all(),array(
'email' => 'email|required',
'password' => 'required'
));
if($validator->fails()){
$messages = $validator->messages();
$msg='';
foreach ($messages->all() as $message)
{
$msg .= "<li>".$message."</li><br />";
}
return $msg;
}
else{
$email = Input::get('email');
$password = Input::get('password');
$user=Auth::attempt(array(
'email' => $email,
'password' => $password,
'activated' => 1
),true);
//die(Auth::user()->rule);
if($user){
//Auth::login($user);
//die('1111111111');
return 1;
}
else{
return "يوجد خطأ فى البريد الإلكترونى أو كلمة المرور";
}
//die('11111111111111111');
}
}
model
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
use Mmanos\Social\SocialTrait;
class User extends Eloquent implements UserInterface, RemindableInterface
{
use SocialTrait;
protected $fillable = array('username','password','rule', 'email','active','phone','address','add_info','image','first_name','sec_name','country','area','baqah_id');
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
public static function is_admin(){
if(Auth::user()->rule=='admin'){
return true;
}
return false;
}
/*
one to one relation
*/
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password');
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return $this->email;
}
public function getRememberToken()
{
return $this->remember_token;
}
public function setRememberToken($value)
{
$this->remember_token = $value;
}
public function getRememberTokenName()
{
return 'remember_token';
}
}
?>
I am new at Symfony. I have been trying to create a reusable form and upload an image with it. The problem is that the image it is not saved in the path i have given. I dont know what i am doing wrong. I would really appreciate any suggestion.
Entity
<?php
namespace test\TestBundle\Entity\media;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\validator\Constraints as Assert;
/**
* Media
*#ORM\Entity
* #ORM\Table(name="upload")
* #ORM\HasLifecycleCallbacks
*/
class Media
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(name="name",type="string",length=255)
* #Assert\NotBlank
*/
public $name;
/**
* #ORM\Column(name="path",type="string",length=255, nullable=true)
*/
public $path;
public $file;
/**
* #ORM\PostLoad()
*/
public function postLoad()
{
$this->updateAt = new \DateTime();
}
public function getUploadRootDir()
{
return __dir__.'/../../../../web/uploads';
}
public function getAbsolutePath()
{
return null === $this->path ? null : $this->getUploadRootDir().'/'.$this->path;
}
public function getAssetPath()
{
return 'uploads/'.$this->path;
}
/**
* #ORM\Prepersist()
* #ORM\Preupdate()
*/
public function preUpload()
{
$this->tempFile = $this->getAbsolutePath();
$this->oldFile = $this->getPath();
$this->updateAt = new \DateTime();
if (null !== $this->file)
$this->path = sha1(uniqid(mt_rand(),true)).'.'.$this->file->guessExtension();
}
/**
* #ORM\PostPersist()
* #ORM\PostUpdate()
*/
public function upload()
{
if (null !== $this->file) {
$this->file->move($this->getUploadRootDir(),$this->path);
unset($this->file);
if ($this->oldFile != null) unlink($this->tempFile);
}
}
/**
* #ORM\PreRemove()
*/
public function preRemoveUpload()
{
$this->tempFile = $this->getAbsolutePath();
}
/**
* #ORM\PostRemove()
*/
public function removeUpload()
{
if (file_exists($this->tempFile)) unlink($this->tempFile);
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
public function getPath()
{
return $this->path;
}
public function getName()
{
var_dump($this->name);
return $this->name;
}
}
Controller
namespace test\TestBundle\Controller\media;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use test\TestBundle\Entity\media\Media;
use test\TestBundle\Form\media\MediaType;
/**
* media\Media controller.
*
* #Route("/img")
*/
class MediaController extends Controller
{
/**
* Lists all media\Media entities.
*
* #Route("/", name="img")
* #Method("GET")
* #Template()
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('testTestBundle:media\Media')->findAll();
return array(
'entities' => $entities,
);
}
/**
* Creates a new media\Media entity.
*
* #Route("/", name="img_create")
* #Method("POST")
* #Template("testTestBundle:media\Media:new.html.twig")
*/
public function createAction(Request $request)
{
$entity = new Media();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('img_show', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Creates a form to create a media\Media entity.
*
* #param Media $entity The entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(Media $entity)
{
$form = $this->createForm(new MediaType(), $entity, array(
'action' => $this->generateUrl('img_create'),
'method' => 'POST',
));
$form->add('submit', 'submit', array('label' => 'Create'));
return $form;
}
/**
* Displays a form to create a new media\Media entity.
*
* #Route("/new", name="img_new")
* #Method("GET")
* #Template()
*/
public function newAction()
{
$entity = new Media();
$form = $this->createCreateForm($entity);
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Finds and displays a media\Media entity.
*
* #Route("/{id}", name="img_show")
* #Method("GET")
* #Template()
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('testTestBundle:media\Media')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find media\Media entity.');
}
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
);
}
/**
* Displays a form to edit an existing media\Media entity.
*
* #Route("/{id}/edit", name="img_edit")
* #Method("GET")
* #Template()
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('testTestBundle:media\Media')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find media\Media entity.');
}
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Creates a form to edit a media\Media entity.
*
* #param Media $entity The entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createEditForm(Media $entity)
{
$form = $this->createForm(new MediaType(), $entity, array(
'action' => $this->generateUrl('img_update', array('id' => $entity->getId())),
'method' => 'PUT',
));
$form->add('submit', 'submit', array('label' => 'Update'));
return $form;
}
/**
* Edits an existing media\Media entity.
*
* #Route("/{id}", name="img_update")
* #Method("PUT")
* #Template("testTestBundle:media\Media:edit.html.twig")
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('testTestBundle:media\Media')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find media\Media entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
return $this->redirect($this->generateUrl('img_edit', array('id' => $id)));
}
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Deletes a media\Media entity.
*
* #Route("/{id}", name="img_delete")
* #Method("DELETE")
*/
public function deleteAction(Request $request, $id)
{
$form = $this->createDeleteForm($id);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('testTestBundle:media\Media')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find media\Media entity.');
}
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('img'));
}
/**
* Creates a form to delete a media\Media entity by id.
*
* #param mixed $id The entity id
*
* #return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm($id)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('img_delete', array('id' => $id)))
->setMethod('DELETE')
->add('submit', 'submit', array('label' => 'Delete'))
->getForm()
;
}
}
Form
namespace test\TestBundle\Form\media;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class MediaType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('file','file', array('required' => false))
->add('name')
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'test\TestBundle\Entity\media\Media'
));
}
/**
* #return string
*/
public function getName()
{
return 'test_testbundle_media_media';
}
}
I you are playing with Symfony2 forms and file upload I'd not recommend doing it as it's described in official documentation.
Please take a look at https://github.com/dustin10/VichUploaderBundle, configure your upload, link entity and enjoy!
I think the documentation is a great example for basic file upload.
Try to update your entity like this :
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(name="name",type="string",length=255)
* #Assert\NotBlank
*/
public $name;
/**
* #ORM\Column(name="path",type="string",length=255, nullable=true)
*/
public $path;
/**
* #Assert\File(maxSize="6000000")
*/
public $file;
/**
* Sets file.
*
* #param UploadedFile $file
*/
public function setFile(UploadedFile $file = null)
{
$this->file = $file;
}
/**
* Get file.
*
* #return UploadedFile
*/
public function getFile()
{
return $this->file;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return File
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set path
*
* #param string $path
* #return File
*/
public function setPath($path)
{
$this->path = $path;
return $this;
}
/**
* Get path
*
* #return string
*/
public function getPath()
{
return $this->path;
}
public function getAbsolutePath()
{
return null === $this->path ? null : $this->getUploadRootDir().'/'.$this->path;
}
public function getWebPath()
{
return null === $this->path ? null : $this->getUploadDir().'/'.$this->path;
}
public function getUploadRootDir()
{
return __DIR__.'/../../../../web/'.$this->getUploadDir();
}
public function getUploadDir()
{
return 'uploads/documents/';
}
public function upload()
{
if (null === $this->getFile()){
return;
}
$this->getFile()->move(
$this->getUploadRootDir(),
$this->getFile()->getClientOriginalName()
);
$this->path = $this->getFile()->getClientOriginalName();
$this->file = null;
}
And in your controller, a simple upload action for GET and POST :
public function UploadAction()
{
$document = new Media();
$form = $this->createFormBuilder($document)
->add('file')
->getForm();
if ($this->getRequest()->isMethod('POST')) {
$form->handleRequest($this->getRequest());
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$account = $em->getRepository('AccountingAccountBundle:Account')->findOneBy(array('id' => $accountId));
$document->setAccount($account);
$document->upload();
$em->persist($document);
$em->flush();
}
}
return array('form' => $form->createView());
}
If this example don't work on your server, maybe you have a problem with rights in your file system.
the problem was in the path directories, just needed one more directory return dir.'/../../../../../web/uploads'; like this :)
Most simplefied idea:
Create normal form in twig,and try to use/rebuilt to your own need trait below.
I used it in some simple uploads connected to entity, it's not a great code (no file validation etc. ) , but it can be a good start for you.
$location variable is configured if trait is in entity dir
user trait below to upload (
<?php
namespace AdminBundle\Entity;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
trait LinkFileTrait
{
private $location='/../../../web/media/link' ;
private $path=__DIR__;
public function checkDir(){
$id=$this->getId();
$fs=new Filesystem();
if(!$fs->exists($this->path.$this->location))
$fs->mkdir($this->path.$this->location);
$this->setImagePath($this->path.$this->location.'/'.$id.'');
if(!$fs->exists($this->getImagePath()))
$fs->mkdir($this->getImagePath());
}
public function getImages(){
$this->checkDir();
$finder = new Finder();
return $finder->files() ->in($this->getImagePath());
}
public function getRandomImage(){
$images=$this->getImages();
$images=iterator_to_array($images);
if(count($images)<1)
return null;
shuffle($images);
return $images[0];
}
public function UploadFile(UploadedFile $file){
$file->move($this->getImagePath().'/',$file->getClientOriginalName());
}
public function removeImage($file){
$this->checkDir();
$fs=new Filesystem();
if($fs->exists($this->getImagePath().'/'.$file))
$fs->remove($this->getImagePath().'/'.$file);
}
public function imageExists($image){
$this->checkDir();
$fs=new Filesystem();
return $fs->exists($this->getImagePath().'/'.$image);
}
public function getRelativePath($path){
$path=strtr($path,"\\","/");
$x=explode('../web/',$path);
return $x[1];
}
public function getImageName($path){
$path=strtr($path,"\\","/");
$x=explode('/',$path);
return $x[count($x)-1];
}
public function getFileName($path){
$x=explode('/',$path);
return $x[count($x)-1];
}
}
and in your controller
public function imagesAction(Link $link,Request $request)
{
$link->checkDir();
$images=$link->getImages();
if($request->getMethod()=='POST'){
$file=$request->files->all()['plik'];
$link->UploadFile($file);
}
return array('link'=>$link,'images'=>$images);
}
I am using PHPUnit to test. Here is my class with the failing test in bold:
//Check that the database is clean
public function testNoUsers(){
$users = User::all();
$this->assertEquals(count($users), 0);
}
//Test that users can login and a find and search works.
public function testUserRegistrationAndSave(){
User::create(array(
'email' => 'thisisatest#gmail.com',
'password' => Hash::make('first_password')
));
$user = User::where('email', '=', 'thisisatest#gmail.com')->first();
$this->assertEquals('thisisatest#gmail.com', $user->email);
}
//Make sure that the email is a proper email address
public function testShouldNotSaveWithInvalidEmail(){
$invalidUser = new User(array(
'email' => 'thisisatest',
'password' => Hash::make('first_password')
));
$this->assertEquals($invalidUser->save(), false, 'Incorrect email address');
}
//Make sure that if the email is not filled out, it can't be saved.
public function testEmailIsFilled(){
$invalidUser = new User(array(
'password' => Hash::make('first_password')
));
$this->assertEquals($invalidUser->save(), false, 'Email not filled out!');
}
public function testUserActive(){
$invalidUser = new User(array(
'email' => 'test#test.com',
'password' => Hash::make('first_password')
));
$invalidUser->save();
//Has active = 1
$validUser = new User(array(
'email' => 'test#test.com',
'password' => Hash::make('first_password'),
'active' => 1
));
$validUser->save();
//User with no active can't login
$login = $invalidUser->login();
$this->assertEquals(false, $login, 'Inactive user logged in');
var_dump($validUser->active); //This outputs 1
//Reset password to plaintext
$validUser->password = "first_password";
$login = $validUser->login();
**$this->assertEquals(true, $login, 'Active user logged in');** //Error is here
}
}
And here is my login method. This returns FALSE when I add active => 1, but returns true when I remove the active => 1 part:
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Model implements UserInterface, RemindableInterface {
protected $fillable = array('email', 'password');
protected $softDelete = true;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password');
protected static $rules = array(
'email' => 'required|email|unique:users|min:4'
);
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the token value for the "remember me" session.
*
* #return string
*/
public function getRememberToken()
{
return $this->remember_token;
}
/**
* Set the token value for the "remember me" session.
*
* #param string $value
* #return void
*/
public function setRememberToken($value)
{
$this->remember_token = $value;
}
/**
* Get the column name for the "remember me" token.
*
* #return string
*/
public function getRememberTokenName()
{
return 'remember_token';
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return $this->email;
}
**public function login(){
if(Auth::attempt(array('email' => $this->email, 'password' => $this->password, 'active' => 1), true)){
return true;
}else{
return false;
}
}**
}
I am using PHPUnit 4 running tests with SQLite. The migration adds the active field with a default value of 1, so I am not sure why this is not working.
You will have to do it manually, but it's easy:
public function login()
{
$loggable = $user = User::where('email', $this->email) &&
Hash::check($this->password, $user->password) &&
$user->active;
if ($loggable)
{
Auth::login($user);
}
return $loggable;
}