When I am trying to send amount data to user dashboard directly by using auth middleware, then getting error "Attempt to read property "name" on null" - laravel-9

I am trying to send product details to user dashboard, if user is login then it should directly show on dashboard and if not then it should be ask for register then on same popup he can edit the amount and pay on next click.
I am trying to send using session however getting error.
Attempt to read property "name" on null
public function addToCart(About $about)
{
if (Auth::check()) {
if(session()->has('cart'))
{
$cart = new Account(session()->get('cart'));
}
else{
$cart= new Account();
}
$cart->add($about);
//dd($cart);
session()->put('cart', $cart);
//return redirect()->back();
return view('amount', compact('cart'));
}}

Related

Not geting token Google Oauth

I'm trying to use google API for login but for some reason both $_GET["code"] and $this->request->getVar('code') are empty and I can't fetch my token because of it. I have tried $_GET["code"] instead of $this->request->getVar('code') but nothing is working:
Error Image second image
I was following this video tutorial: click here
public function signup_with_gmail() {
require_once APPPATH.'Libraries\vendor\autoload.php';
$google_client = new \Google_Client();
//$google_client->setApplicationName("pharma");
$google_client->setClientId('clientID');
$google_client->setClientSecret('SECRET');
$google_client->setRedirectUri('http://localhost/pharma/User/sign_in');
$google_client->addScope('email');
$google_client->addScope('profile');
print_r($this->request->getVar('code') === NULL);
print_r($_GET['code']);
if ($this->request->getVar('code') != NULL) {
$token = $google_client->fetchAccessTokenWithAuthCode($this->request->getVar('code'));
if(!$token['error']){
$google_client->setAccessToken($token['access_token']);
$session->set('access_token', $token['access_token']);
//now get profile data create another object
$google_service = new \Google_Service_Oauth2($google_client);
$data = $google_service->userinfo->get();
print_r($data);
}
}
print_r($data);
}
The code in $this->request->getVar('code') will be generated only when you will hit the URL created using $google_client->createAuthUrl();
So, you can do it like this...
In Controller write
$data['loginButton'] = $google_client->createAuthUrl();
Pass this $data['loginButton'] to the view in the anchor tag for the Sign in with Google button.
Now when you will click on the Sign in with Google button it will redirect back to the same localhost.com/login URL but this time you will have the code in the URL. So you can fetch it with $this->request->getVar('code') and follow the rest of the process.
Please make sure all the detail like ClientId & ClientSecret is correct
And update to the latest "google/apiclient": "^2.10"

MVC 4 website back press return the same form with old values

I am new in MVC 4 web development and i am creating a control panel. I have developed a Add user page and submit information in database successfully.
But after submit when i press back button it will show previous form.
i am using redirection the page to same page after submit form.
here is the code to redirect
public ActionResult AdminPanel(RegisterUserModel user)
{
if (ModelState.IsValid) // Check the model state for any validation errors
{
if (user.AddUserToDB(user.username, user.password, user.fullName,user.contactNo,user.COAId)) // Calls the Login class checkUser() for existence of the user in the database.
{
TempData["SuccessMessage"] = "User Added Sucessfully!";
ModelState.Clear();
return Redirect("AdminPanel");
}
else
{
ViewBag.SuccessMessage = "User Not Added";
return View();
}
}
SelectList clientsList = GetClinetList();
ViewBag.clientsList = clientsList;
return View(); // Return the same view with validation errors.
}
I have tried many examples but issue not resolved yet so kindly give my suggesstions
If you don't want the user to be able to see the previous content when clicking back, then you must indicate that content should not be cached by the browser and must revalidate with the origin server
A summary of this behaviour is here - http://blog.55minutes.com/2011/10/how-to-defeat-the-browser-back-button-cache/
You could create a nocache attribute, like this one - https://stackoverflow.com/a/10011896/1538039, and apply it to your controller methods.

Current user doesn't persist when reloading an app (Ionic2 + Parse Server)

I'm currently working on Ionic 2 app with Parse Server backend.
I implemented signed up process. No problems here, everything works as expected: new account is created, user is logged in after sign up and current user exists.
Now I want to use current user and bypass sign up/login page next time user opens the app (if the user is already logged in ). The Parse documentation clearly states:
“It would be bothersome if the user had to log in every time they
open your app. You can avoid this by using the cached
current Parse.User object. Whenever you use any signup or login
methods, the user is cached in localStorage.”
In my case, however, I can't manage to make it work. I create current user according to Parse documentation during initialization process of the app:
var currentUser = Parse.User.current();
if (currentUser) {
// do stuff with the user
} else {
// show the signup or login page
}
Every time I open the app after successful sign up the current user is NULL.
Any ideas?
I kinda understand what's going on, but still don't understand why.
During signup or login Parse is supposed to save current user to local storage, but if local storage is not available for some reason, it saves it to memory map. And this is what happens in my case: Parse always saves current user to memory map, which is, of cause, temporary storage. Hence, every time I reload the app, Parse memory map is empty. I don't understand why in my environment Parse decides that local storage is unavailable. I couldn't find in the code where this decision is made. It seems to me that memory map is default (which is probably not true). Could it be that local storage functionality is not implemented yet in the open source version of Parse? Or does it have something to do with Ionic2 implementation?
Is there anybody out there from Parse team who is familiar with this part of Parse code?
Thanks.
Hi I use Local Storage.
import { Component } from '#angular/core';
import { NavController,Alert,Storage,LocalStorage } from 'ionic-angular';
import {HomePage} from'../home/home';
import {UserdetailPage} from'../userdetail/userdetail';
declare var require:any;
var Parse = require('parse/node');
#Component({
templateUrl: 'build/pages/user/user.html',
})
export class UserPage {
public currentUser:any;
public local:any;
username:string="";
password:string="";
repassword: string="";
sign:string = "SIGN IN";
constructor(private nav: NavController) {
Parse.initialize(XXXXX);
Parse.serverURL = 'XXXXXX';
this.local = new Storage(LocalStorage);
this.currentUser = this.local.get('userid');
console.log(this.currentUser);
}
signin(){
console.log("username:"+this.username);
console.log("password:"+this.password);
if(this.username!="" &&this.password!=""){
if(this.repassword!=""){
// Register User Session
this.register();
}
else if(this.repassword==""&&this.username!=""&&this.password!=""){
this.login();
}
}
}
changeSign(s:string){
console.log(s);
if(s!="")
this.sign = "SIGN UP (Register New Account)";
else
this.sign ="SIGN IN";
}
register(){
if(this.repassword==this.password){
var parseuser = new Parse.User();
parseuser.set("username",this.username);
parseuser.set("password",this.password);
parseuser.signUp(null, {
success:user=>this.registerSucessAlert(),
error: error=>this.registerFailAlert("Register Fail, The user name exists or Server is down")
});
}
else{
this.registerFailAlert("Password is not the same");
}
}
login(){
console.log("Login");
Parse.User.logIn(this.username, this.password, {
success:user=>this.loginSucessAlert(),
error:error=>this.loginFailAlert()
});
}
loginSucessAlert(){
this.currentUser = Parse.User.current().id;
this.local.set('userid',this.currentUser);
let alert = Alert.create({
title:'Login',
subTitle:'Hi '+this.username+', Press to Continue.',
buttons:[{text:'OaaaK',
handle:()=>{this.nav.setRoot(UserdetailPage);}}]
});
this.nav.present(alert);
}
loginFailAlert(){
let alert = Alert.create({
title:'Login',
subTitle:'Login Error',
buttons:['OK']
});
this.nav.present(alert);
}
registerSucessAlert(){
this.currentUser = Parse.User.current().id;
this.local.set('userid',this.currentUser);
let alert = Alert.create({
title:'Resgiter',
subTitle:'Thank you'+this.username+' for register, Press to Continue.',
buttons:['OK']
});
this.nav.present(alert);
}
registerFailAlert(err:string){
let alert = Alert.create({
title:'Register Fail',
subTitle:err,
buttons:['OK']
});
this.nav.present(alert);
}
}

Laravel route with variable in the url

I am trying to implement the password reset logic. The user gets the link to reset the password in the email. The url looks like
http://example.com/reset/resetcode
I have the route defined for it:
Route::get('reset/{resetcode}', function(){
return View::make('users.reset_password');
});
The form is rendered in the view to submit the email, new password etc. For the post of the form I have route defined as:
Route::post('reset/{resetcode}', array( 'as' => 'reset', 'uses' => 'UserController#passwordReset'));
I grab the resetcode from post route inside the passwordReset controller below
public function passwordReset($resetcode)
{
$validation = Validator::make(Input::all(), UserModel::$rulesPasswordReset);
if ($validation->passes())
{
try
{
// Find the user using the user email address
$user = Sentry::findUserByLogin(Input::get('email'));
// Check if the reset password code is valid
if ($user->checkResetPasswordCode($resetcode))
{
// Attempt to reset the user password
if ($user->attemptResetPassword($resetcode, 'new_password'))
{
// Password reset passed
}
else
{
// Password reset failed
}
}
else
{
// The provided password reset code is Invalid
}
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
}
else return Redirect::route('reset')->withInput()
->withErrors($validation)
->with('title', 'resetrequestfailure')
->with('message', 'Seems like you made some errors.');
}
The problem I am having is when I do Redirect::route after the validation fails. I am getting the resetcode from the route defined for post. When validation fails, the redirect route messes up and I cannot get the resetcode the second time. The supposed url of format
http://example.com/reset/8f1Z7wA4uVt7VemBpGSfaoI9mcjdEwtK8elCnQOb
becomes
http://bcnet.org/reset/%7Bcode%7D
It has to do with /{resetcode} part of the route and this is variable, so how can I get the correct resetcode even after the validation fails meaning that the url remains intact. Or how can I fix it to the appropriate Redirect::route after the validation failure.
You need to include the $resetcode on your return
else return Redirect::route('reset', $resetcode)->withInput()
->withErrors($validation)

MVC page to page redirection

I'm new to MVC (using 4, framework 4.0) and I understand the basics but this page redirect isn't working as I expect. The application is a login/authentication which if the user successfully logs in it redirects them to the target application. That part works just fine. However the user may forget his/her login credentials, so I have a series of pages that will prompt the user for a registered email address and decoded captcha value. If that information is validated then another page prompts for a series of (up to 3) pre-determined security question answers (in the case of a password forgotten). If the security challenge question is successfully answered the user is redirected to a password change page. At any point in the process the user may click a cancel button which should redirect back to the login page and clear any state variables tracking their progress through the recovery process. The problem is I keep getting stuck on pages that even after a RedirectToAction("SomeAction", "SomeController"); I still stay on the page? The URI even changes on the browser but the page asking for email address or security question stays active. I'm using an ajax $.get() to call various actions for submit and cancel.
view is defined like this:
#using (Html.BeginForm("RecoverUserCredentialsByModel", "Account", FormMethod.Get, new { id = "form1" }))
{
<!--... three input controls and a submit and cancel button-->
<p>
<button id="btnSubmit" onclick="return CheckUserEmail()">Submit</button>
<button id="btnCancel" onclick="return CancelRecovery()">Cancel</button>
</p>
}
<script type="text/javascript">
function CheckUserEmail() {
var emailAddress = document.getElementById("EmailAddress").value;
var pictogramHref = document.getElementById("pictogramHref").src;
var pictogramAnswer = document.getElementById("Pictogram").value;
if (emailAddress != null) {
var url = "/Account/ValidateEmail";
$.get(url, { "emailAddress": emailAddress, "pictogramHref": pictogramHref, "pictogramTranslation": pictogramAnswer }, null);
return true;
}
}
</script>
<script type="text/javascript">
function CancelRecovery() {
var url = "/AuthenticationModule/Account/CancelRecovery";
$.get(url, {}, null);
return true;
}
</script>
Codebehind redirections look like:
/// <summary>
/// Global cancel recovery, clears the stateful session object and redirects back to login view
/// </summary>
/// <returns>ActionResult</returns>
[AllowAnonymous]
public ActionResult CancelRecovery()
{
LoginModel statefulLoginModel = null;
try
{
// Reset everything active and redirect to login view
statefulLoginModel = new LoginModel();
Session["LoginModel"] = statefulLoginModel;
return Redirector(statefulLoginModel);
}
catch (Exception ex)
{
// Log the error and Reset everything active and redirect to login view
FileLogger.Log(ex);
statefulLoginModel = new LoginModel();
Session["LoginModel"] = statefulLoginModel;
return Redirector(statefulLoginModel);
}
}
[AllowAnonymous]
public ActionResult Redirector(LoginModel model)
{
... some code
Session["LoginModel"] = statefulLoginModel;
if (loginState == 0)
{
RedirectToAction("LogOn");
}
}
When it hits the RedirectToAction("LogOn"); the view "RecoverUserInfo" stays active on the browser and no redirection occurs?
What am I doing wrong?
Try this..........
Proper Syntax is return RedirectToAction("ActionName","ControllerName");
In this case if Logon Action is written on the same Controller Then use following Code..
return RedirectToAction("LogOn");
or it is written on another controller then just replace your Action Name and Controller Name in the following code.
return RedirectToAction("ActionName","ControllerName");