Yii set user for every action in controller - yii

i try to set user for every action in controller.
I have acces rules,
and i was set 2 diferent menu for admin and quest.
But I have one action which is not in any menu.
Default user for actions in yii is quest, so if I don't mentioned action in menu for admin, user for that action will be quest.
I don't want to mentioned that action in menu (layout) but i want to user for that action be admin.
In theory I want to set user for every individual action.
public function actionTest()
{
!Yii::app()->user->isGuest;
...
}
Something similar this but this is not work.
MORE CODE:::
I have controller TestController
I have layout main.php
I have login form, and action logout.
So next:
My controller:
class TestController extends Controller
{
/**
* Declares class-based actions.
*/
public function accessRules()
{
return array(
array('allow',
'actions'=>array('login'),
'users'=>array('*'),
),
array('allow',
'actions'=>array('test1','test2','logout','test3'),
'users'=>array('#'),
),
);
}
public function actionLogin()
{
$this->render('login');
}
public function actionTest1()
{
$this->render('test1');
}
public function actionTest2()
{
$this->render('test2');
}
public function actionTest3()
{
$this->render('test3');
}
public function actionLogout()
{
...
}
}
In layout main.php i have criteria for menu:
if(Yii::app()->user->isGuest)
{
$this->widget('bootstrap.widgets.TbNavbar',array(
'items'=>array(
array(
'class'=>'bootstrap.widgets.TbMenu',
'items'=>array(
array('label'=>'Login', 'url'=>array('/test/login')),
),
),
),
));
}
else
{
$this->widget('bootstrap.widgets.TbNavbar',array(
'items'=>array(
array(
'class'=>'bootstrap.widgets.TbMenu',
'items'=>array(
array('label'=>'Test1', 'url'=>array('/test/test1')),
array('label'=>'Test2', 'url'=>array('/test/test2')),
array('label'=>'Logout ('.Yii::app()->user->name.')', 'url'=>array('/test/logout'), 'visible'=>!Yii::app()->user->isGuest)
),
),
),
));
}
Like you can see I did not set test3 in 'else' but in test 2 I set redirect to test3 and after login test1 and test2 user will not be quest but test3 will because that is default.
In this situation it is not syntax error.

Related

notification system in Laravel 8

I am working on a laravel app where i have a user(organizer) who post an event ,and other users can comment on this event .
I am trying to make notifications system in laravel 8 between the organizer and the users when commenting on these event !
but i get this error (Call to a member function notify() on null).
This is my class :
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class NewCommentPosted extends Notification
{
use Queueable;
protected $user;
protected $event;
public function __construct($user, $event)
{
$this->user = $user;
$this->event = $event;
}
public function via($notifiable)
{
return ['database'];
}
public function toArray($notifiable)
{
return [
'user' => $this->user->name,
'eventTitle' => $this->event->title,
'eventId' => $this->event->id
];
}
This is storefunction() in my controller :
namespace App\Http\Controllers;
use App\Models\Event;
use App\Models\Comment;
use App\Notifications\NewCommentPosted;
use Illuminate\Http\Request;
class CommentController extends Controller
{
public function store(Event $event)
{
request()->validate([
'content' => 'required|min:5'
]);
$comment = new Comment();
$comment->content = request('content');
$comment->user_id = auth()->user()->id;
$event->comments()->save($comment);
$event->user->notify(new NewCommentPosted(auth()->user(), $event));
return redirect()->route('events.show', [$event->id, $event->title]);
}
Any help please !!?

Error with Laravel authentication

I'm new to Laravel and I am trying to implement authentication in my application, when I post the login form this error is returned in my browser:
I have no idea what this error means, where it occurs, or how to fix it.
This is my signin function in my authentication controller that handles all logins:
public function signin()
{
// validate the info, create rules for the inputs
$rules = array(
'email' => 'required|email', // make sure the email is an actual email
'password' => 'required|min:6' // password can only be alphanumeric and has to be greater than 3 characters
);
// run the validation rules on the inputs from the form
$validator = Validator::make(Input::all(), $rules);
// if the validator fails, redirect back to the form
if ($validator->fails()) {
return Redirect::to('/authentication')
->withErrors($validator) // send back all errors to the login form
->withInput(Input::except('password')); // send back the input (not the password) so that we can repopulate the form
} else {
// create our user data for the authentication
$user = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
// attempt to do the login
if (Auth::attempt($user)) {
// validation successful!
// redirect them to the secure section or whatever
// return Redirect::to('secure');
// for now we'll just echo success (even though echoing in a controller is bad)
return Redirect::to('dashboard.index');
} else {
// validation not successful, send back to form
return Redirect::to('/authentication')
->with('failed', 'Incorrect email / password!');
}
}
}
This is my User model:
<?php
class User extends Eloquent{
// MASS ASSIGNMENT -------------------------------------------------------
// define which attributes are mass assignable (for security)
protected $fillable = array('email','school_id','role_id','activation_key','reset_key','login_status','account_status');
// LINK THIS MODEL TO OUR DATABASE TABLE ---------------------------------
protected $table = 'users';
// DEFINE RELATIONSHIPS --------------------------------------------------
public function roles() {
return $this->belongsTo('Role');
}
public function schools() {
return $this->belongsTo('Institution');
}
public function lectures() {
return $this->hasOne('Lecturer');
}
public function students() {
return $this->hasOne('Student');
}
public function getId()
{
return $this->id;
}
}
Let's take a look at Laravel's default User model:
class User extends Eloquent ...
so far so good
... implements UserInterface, RemindableInterface {
Oooops looks like you're missing something ;)
Also the two traits are not unimportant.
Here's how it should look like:
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
// MASS ASSIGNMENT -------------------------------------------------------
// define which attributes are mass assignable (for security)
protected $fillable = array('email','school_id','role_id','activation_key','reset_key','login_status','account_status');
// [the rest of your model]

Successful Pages after registration in yii controller

I want to redirect to another pages after successful registration. How I can I restrict this pages to be visited directly from url. only display after registration.
public function actionRegistration()
{
.......
if($model->save())
{
$this->redirect(Yii::app()->request->baseUrl.'/site/success_registration');
}
............
}
public function actionSuccess_registration()
{
$this->render('success_registration');
}
You could probably add some rules and filters, or you could check the referrer in the actionSuccess_registration but the simplest way to make the view non-accessible from anywhere else would be to render the success_registration view from inside actionRegistration. actionSuccess_registration is therefore redundant if all it does is render the view.
public function actionRegistration()
{
.......
if($model->save())
{
$this->render('success_registration');
return;
}
............
}
check this out for authentication in yii.
so u could do like this:
class YourController extends CController
{
......
public function filters()
{
return array(
'accessControl',
);
}
public function accessRules()
{
return array(
array('deny',
'actions'=>array('registration'),
'users'=>array('?'),
),
array('allow',
'actions'=>array('success_registration'),
'users'=>array('#'),
),
array('deny',
'actions'=>array('delete'),
'users'=>array('*'),
),
);
}
}
in your method
public function actionRegistration()
{
.......
if($model->save())
{
$this->redirect($this->createUrl('site/success_registration'));
}
............
}
It would be easier if you used flash messages instead. That's what they are there for.
public function actionRegister()
{
if(Yii::app()->user->hasFlash('registered')) {
$this->render('success_login');
} else {
// Process POST registration data here.
// If registration was successul you do:
Yii::app()->user->setFlash('registered',true);
$this->refresh();
// Otherwhise you render the registration form here
}
}
you should go to the project file and go to the protected folder ->controller folder and then open the SiteController.php
please find the "public action actionLogin()" in the SiteController.php.
after that find this line:
$this->redirect(Yii::app()->user->returnUrl);
in the actionLogin() function.
for example i want it is redirect to the user controller.i add .'?r=user' at the end of code.
$this->redirect(Yii::app()->user->returnUrl.'?r=user');

Why does Yii-enforced authentication only work on the homepage/static pages?

I need to enforce authentication across all pages of a YII application. To do this I've extended the SiteController class with the following code I got from http://www.heirbaut.nl/2010/02/23/forcing-a-yii-application-to-authenticate/:
/**
* #return array action filters
*/
public function filters(){
return array(
'accessControl', // perform access control for CRUD operations
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* #return array access control rules
*/
public function accessRules(){
return array(
array('allow', // allow all users to perform 'login'
'actions'=>array('login'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform any action
'users'=>array('#'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
This only does what it's supposed to, redirect all requests for unauthenticaed users to the login form, for the index.php url. But index.php?r=person and consequentially, the main menu of the application bypasses this restriction and show up regardless of authenthication.
Every controller needs to reference that code. An option is to create your own controller that extends CController and place it in your protected/components folder
class MyController extends CController{
/**
* #return array action filters
*/
public function filters(){
return array(
'accessControl', // perform access control for CRUD operations
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* #return array access control rules
*/
public function accessRules(){
return array(
array('allow', // allow authenticated user to perform any action
'users'=>array('#'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
}
Then in your controller classes you need to extend MyController and override accessRules() to add any additional rules
public class SiteController extends MyController{
...
public function accessRules(){
$rules=parent::accessRules();
array_unshift($rules,array(
'allow', // allow all users to perform 'login'
'actions'=>array('login'),
'users'=>array('*'),
));
return $rules;
}
...
}

Yii inherit attributeLabels

With Yii php framework, I use inheritance.
In my AbstractModel, I have this method:
public function attributeLabels()
{
return array(
'0'=>Yii::t('default','No'),
'1'=>Yii::t('default','Yes'),
);
}
In my object who extends AbstractModel, I have this method:
public function attributeLabels()
{
return array(
'username' => Yii::t('user', 'email'),
);
}
In a view file, I use:
<?php echo CHtml::activeLabel($model, $model->property);?>
But I never show 'No' or 'Yes' from asbtractModel. If I put all in my model it works. But I want to use inheritance.
How can I concat parent attributeLabels with current model attributeLabels?
Simply merge the return value of the parent method in MyObject (model class):
public function attributeLabels() {
return array_merge(
parent::attributeLabels(),
array(
'username' => Yii::t('user', 'email'),
)
);
}
You may also use CMap::mergeArray().