laravel 4 logout after loginning directly? - laravel

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';
}
}
?>

Related

How to add PDF attachment in queue mails In Laravel?

I was able to send an email but when I put the attachData() in the UserMail there was an error. I think because of the parameter $this->pdf that should be declared in UserEmailJob, and I don't know how to fix it.
UserEmailJob
public $details;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct($details)
{
$this->details = $details;
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
$email = new UserEmail();
Mail::to($this->details['email'])->send($email);
}
UserEmail - mail class
I'm having error with this line $this->pdf->output()
public function __construct()
{
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->from('info#gmail.com', 'Mailtrap')
->subject('Stock Report - Laravel Tutorial')
->view('emails.userEmail')
->attachData($this->pdf->output(), 'stock_report.pdf');
}
UserController
public function mailClass()
{
$users = User::all();
$data['name'] = 'Hi';
$pdf = app('dompdf.wrapper');
$pdf->loadView('cert', $data);
$pdf->setPaper('A4', 'landscape');
$details = ['email' => 'abc#gamil.com'];
UserEmailJob::dispatch($details);
return response()->json(['status' => 'success', 'message' => 'Report has been sent successfully.']);
}
Because $this->pdf is not defined in your class.
try this:
private $pdf;
public function __construct($pdf) {
$this->pdf = $pdf;
}
public function build(){
return $this->from('info#gmail.com', 'Mailtrap')
->subject('Stock Report - Laravel Tutorial')
->view('emails.userEmail')
->attach($this->pdf);
}
and in your UserController
UserEmailJob::dispatch($details, $pdf->output());
So modify it
public $details;
public $pdfStream;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct($details, $pdfStream)
{
$this->details = $details;
$this->pdfStream = $pdfStream;
}
public function handle()
{
$email = new UserEmail($this->pdfStream);
Mail::to($this->details['email'])->send($email);
}
EDIT: it is probably not recommended to stream the pdf via json
UserEmailJob
public $details;
public $data;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct($details, $data)
{
$this->details = $details;
$this->data = $data;
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
$email = new UserEmail($this->data);
Mail::to($this->details['email'])->send($email);
}
UserEmail
private $data;
public function __construct($data)
{
$this->data = $data;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
$pdf = app('dompdf.wrapper');
$pdf->loadView('cert', $this->data);
$pdf->setPaper('A4', 'landscape');
return $this->from('info#gmail.com', 'Mailtrap')
->subject('Stock Report - Laravel Tutorial')
->view('emails.userEmail')
->attachData($pdf->output(), 'stock_report.pdf');
}
UserController
public function mailClass()
{
$users = User::all();
$data['name'] = 'Hi';
$details = ['email' => 'abc#gamil.com'];
UserEmailJob::dispatch($details, $data);
return response()->json(['status' => 'success', 'message' => 'Report has been sent successfully.']);
}

How to use 2 attributes in Validation Rule Class Laravel

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'))]
]);

Laravel 5.6 - Eloquent relation create fail (type error)

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;
}

As validatePassword () receives the user's password?

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

Adding active to Auth::attempt returns false with active => 1 but fine without active => 1?

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;
}

Resources