I have a working Yii app on my local lamp stack. Now when I put the app on a lamp server the app reads the db and runs, but the app isn't successfully writing to the db. I'm getting no errors logs. Any thoughts?
Here's how I'm updating the db:
public function actionIndex()
{
if ($_GET["yep"] == "") {
pd_error("You are not logged in!");
}
list($uid, $domain) = preg_split("/#/",$_GET["yep"],2);
$model=$this->loadModel($uid);
$this->redirect($model->URL."?".$model->Unique_ID);
}
public function loadModel($uid)
{
$model=People::model()->findByPk($uid);
$model->Login_Count++;
$model->Last_Logged=date('Y-m-d H:i:s');
if ($model->validate()) {
$model->save();
} else {
$this->render('notice');
}
return $model;
}
The weird thing is, even when the db doesn't update the Login_Count and Last_Logged the user still gets redirected to their url, so the sql must be valid because the notice page never loads. Any thoughts?
Update + Solution
The problem ended up being that the mysql server had autocommit set to false. To override this at the app level add the following line to the config/main.php db array:
'db'=>array(
...
'initSQLs'=>array('SET AUTOCOMMIT=1',),
...
);
Yii: using active record with autocommit off on mysql server
The rendering of notice page doesn't stop your redirect. It might be rendered, but you won't be able to see it because of redirect. Try to refactor your code.
You're validating your model twice and the validation probably might be skipped since there's no data coming from App user.
You don't check if People model actually found.
There is CWebUser::afterLogin method which you can override to do this kind of stuff (update login count and last login date)
Maybe this way (quick fix) will work:
function actionIndex()
{
if ($_GET["yep"] == "") {
pd_error("You are not logged in!");
}
list($uid, $domain) = preg_split("/#/",$_GET["yep"],2);
if (null === ($model=People::model()->findByPk($uid))
throw new CHttpException(404);
$model->Login_Count++;
$model->Last_Logged=date('Y-m-d H:i:s');
if ($model->save()) {
$this->redirect($model->URL."?".$model->Unique_ID);
} else {
// echo CHtml::errorSummary($model)
$this->render('notice');
}
}
Related
I have a database that in this: Admin has True isAdmin property, but other users have false isAdmin property.
I want to check if the user who logged in is an Admin or not by redirecting them to different pages in my app. My code in Controller is:
public function store(User $user)
{
if (auth()->attempt(request(['email', 'password']))) {
if ($user->isAdmin == 1) {
return redirect('/ShowUser');
}
{
return redirect('/lo');
}
}
return back()->withErrors(
[
'message' => 'Error'
]
);
}
But this code doesn't work; it sends the users to '/lo' all the time. How can I fix it?
You're missing an else keyword.
Right here:
if ($user->isAdmin == 1) {
return redirect('/ShowUser');
}
{ // <-- right here
return redirect('/lo');
}
add the else keyword.
if ($user->isAdmin == 1) {
return redirect('/ShowUser');
}
else { // <-- right here
return redirect('/lo');
}
anyway, your code will still run fine even after the edit above. But I have questions for you:
Is the user assumed to be in the database already?
What is the default value of isAdmin in the database?
Are you passing the isAdmin attribute as an input from a form or something?
And why is it a store request when you're just trying to log a user in?
It's a bit confusing. I can tell from your code that you're trying to log a user in, but you're doing it in a store method (nothing wrong with that, just convention), the store method is usually used in storing data (how coincidental!)
I have /signup/select-plan which lets the user select a plan, and /signup/tos which displays the terms of services. I want /signup/tos to be only accessible from /signup/select-plan. So if I try to go directly to /signup/tos without selecting a plan, I want it to not allow it. How do I go about this?
In the constructor, or the route (if you are not using contructors), you can check for the previous URL using the global helper url().
public function tos() {
if ( !request()->is('signup/tos') && url()->previous() != url('signup/select-plan') ) {
return redirect()->to('/'); //Send them somewhere else
}
}
In the controller of /signup/tos which returns the tos view just add the following code:
$referer = Request::referer();
// or
// $referer = Request::server('HTTP_REFERER');
if (strpos($referer,'signup/select-plan') !== false) {
//SHOW THE PAGE
}
else
{
dd("YOU ARE NOT ALLOWED")
}
What we are doing here is checking the HTTP referrer and allowing the page access only if user comes from select-plan
You are need of sessions in laravel. You can see the following docs to get more info: Laravel Sessions
First of all you need to configure till how much time you want to have the session variable so you can go to your directory config/sessions.php and you can edit the fields 'lifetime' => 120, also you can set expire_on_close by default it is being set to false.
Now you can have following routes:
Route::get('signup/select-plan', 'SignupController#selectPlan');
Route::post('signup/select-token', 'SignupController#selectToken');
Route::get('signup/tos', 'SignupController#tos');
Route::get('registered', 'SignupController#registered');
Now in your Signupcontroller you can have something like this:
public function selectPlan()
{
// return your views/form...
}
public function selectToken(Request $request)
{
$request->session()->put('select_plan_token', 'value');
return redirect('/signup/tos');
}
Now in signupController tos function you can always check the session value and manipulate the data accordingly
public function tos()
{
$value = $request->session()->get('select_plan_token');
// to your manipulation or show the view.
}
Now if the user is registered and you don't need the session value you can delete by following:
public function registered()
{
$request->session()->forget('select_plan_token');
// Return welcome screen or dashboard..
}
This method will delete the data from session. You can manipulate this. You won't be able to use in tos function as you are refreshing the page and you want data to persist. So its better to have it removed when the final step or the nextstep is carried out. Hope this helps.
Note: This is just the reference please go through the docs for more information and implement accordingly.
I'm new in laravel
I coded a script that many users may work with
but the problem that I have is this :
when a user like "Helen" signs in she can see her profile
but if next another user like "Maria" logs on , Marias panel will be shown for both of them
I think it means just one session can be active at the same time and the value of session will be for the latest user
and the older users session doesn't expire just the value in the session will be changed , thus she identifies as another user and can see that users profile, and also when a user logs out , because of close of the session , all users will be signed out.
here is my simple code :
public function Login(){
$this->Token();
$pack=Input::all();
try {
$result=DB::table('user')->where('Email','=',$pack['email'])->get();
if (Hash::check($pack['password'], $result[0]->Password)){
session(['there' => $result['0']->Email]);
return redirect('dashboard');
}
return redirect('dashboard')->with('does','wrong password');
}catch(Exception $e){
return redirect('dashboard')->with('does',.$e);
}
}
public function UserType() {
if(!session('there'))
return "Not Logged";
else {
$result = DB::table('user')->where('Email', '=', session('there'))->get();
if($result!=null)
return "User";
}
public function ShowDashboard(){
if($this->UserType()=="Not Logged")
else
return view('pages/dashboard');
}
I am not sure why you are session() to manage user logins... Also, they depend a lot on situations where users are login from the same computer, same browser... cookies... etc etc... and maybe that's why you might be getting 2 different session values at the same time...
In any case.. please try and prefer using Laravel's predefined functions of Auth to handle your login/logout procedures.
public function Login()
{
// What does this do? Check for a CSRF token? If yes, then
// please understand then Laravel automatically checks
// for the CSRF token on POST/PUT requests and therefore
// there is no special need to use the below function...
$this->Token();
$pack = request()->only(['email', 'password']);
// I don't really feel try catch is required here... but completely your choice...
try {
if(auth()->attempt($pack)) {
return redirect('dashboard')
}
return redirect->back()->with('does', 'wrong password');
} catch(Exception $e) {
return redirect->back()->with('does', $e);
}
}
public function ShowDashboard()
{
// You can remove this if/else by adding the 'auth' middleware
// to this route
if(!auth()->check())
return view('pages.dashboard');
else
return redirect(route('login'));
}
I found a lot of problems in your above code...
Please use camelCase for naming functions... (I haven't changed the naming in my code above because I don't really know what rules you are following at your workplace or idk...)
Please don't return strings for a simple true/false situation.
Please try and use Models whenever possible. The raw DB commands are required for very complex and extensive queries
After spending so many days, am trying to get some help from experts.
I am stuck with login redirection in my yii2 application only in chrome browser,
This is my controller class,
class InvitationsController extends Controller
{
public function beforeAction($action)
{ $array=array('index','imageupload','template','category','subcategory','slug','chooseanotherdesign');
if(!in_array($action->id, $array))
{
if (\Yii::$app->getUser()->isGuest &&
\Yii::$app->getRequest()->url !== Url::to(\Yii::$app->getUser()->loginUrl)
) {
\Yii::$app->getResponse()->redirect(\Yii::$app->getUser()->loginUrl,FALSE);
}
}
return parent::beforeAction($action);
}
public function actionGenerateevent(){
$redirectUrl="";
if(Yii::$app->request->post()){
unset(Yii::$app->session['copyinvitation']);
unset(Yii::$app->session['eventform']);
Yii::$app->session['eventform']=Yii::$app->request->post();
}
if (!Yii::$app->user->isGuest)
{
$eventid=$this->invitation->savecontinue(Yii::$app->session['eventform']);
$eventdata=$this->invitation->getEventById($eventid);
$refurl=Yii::$app->session['eventform']['refererurl'];
$aa['Events']=$eventdata;
$aa['refererurl']=$refurl;
Yii::$app->session['eventform']=$aa;
$redirectUrl = Yii::$app->urlManager->createAbsoluteUrl(['invitations/event/'.$eventdata['event_token']]);
return $this->redirect($redirectUrl);
}
}
}
My workflow
step1: submitting formdata to controller xx-action
step2: If user login it will proceed further action
Else
am trying to store the values in session then redirecting the page to login
step 3: after successful login am return back to same xx-action
This workflow is working fine in firefox but chrome it's making infinitive loop its not going through the login page.
Please refer am attached the screenshot
Please help me to solve this issue.
I can't infere how are you calling your actionGenerateevent() but you seems to have an error there:
$redirectUrl=""; //empty
...
return $this->redirect($redirectUrl); //still empty
Since you are not setting your $redirectUrl, your redirect is redirecting you to the current (same) url again and again, causing the loop.
This is the function used by redirectUrl() method: Url::to(). Its docs says:
an empty string: the currently requested URL will be returned;
I'm working on custom module and in my IndexController.php I'd written this function to add user to database
public function addAction() {
if($this->getRequest()->getParam('name', '') == ''){
$this->_redirect('etech/user');
//die; or exit;
}
$form = $this->getRequest()->getParams();
$user = Mage::getModel('test/test');
foreach ($form as $key => $val){
$user->setData($key, $val);
}
try{
$user->save();
}catch(Exception $e){
print_r($e);
}
$this->_redirect('etech/user', array('msg'=>'success'));
}
I want to prevent users from accessing this url directly as www.example.com/index.php/etech/user/add/. For this I'd made a check if($this->getRequest()->getParam('name', '') == ''){}. The redirect is working well except the code in there keeps executing and user sees a success message which should not be seen. For this, I'd used old fashioned exit or die to stop executing the code then it doesn't even redirect.
What is the magento way to handle it? Also, as I'm using getRequest()->getParams(), it return both parameters either in get or post. Isn't any way out to get only post parametrs?
It is correct to use $this->_redirect(), but you must follow it up with a return, ideally return $this;. You could also use exit or die, as you have been doing, but as I'm sure you know it would be better to let Magento do whatever it wants to do before redirecting you.
As long as you return immediately after $this->_redirect(), you won't have any issues.
Edit: And as for the request params question, I think you can call something like $this->getRequest()->getPostData() (that was false). The general convention is to use getParams() regardless of whether the data was sent via GET or POST, because technically your code shouldn't be concerned about that.
Edit #2:
If the general convention doesn't apply and you desperately need to restrict access to your page based on POST vs. GET, here's a handy snippet from Mohammad:
public function addAction()
{
if ($this->getRequest()->isPost()) {
// echo 'post'; do your stuff
} else {
// echo 'get'; redirect
}
}