Laravel route with variable in the url - authentication

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)

Related

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"

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

Only allow user to go to a page if he/she passes the validation

How can I prevent users from entering a specific page if they put a wrong value in VueJS?
For example I have this code snippet that I grabbed from my code that validates if user's chosen date will match the date from my JSON.
checkBirthday: function() {
//compare results birthday and input birthday
let inputBDAY = moment(this.date).format("MMMM DD, YYYY");
if (this.results.BIRT_D == inputBDAY) {
//redirect to details page
this.$router.push("/details/" + this.MEMB_N);
} else {
alert("Wrong Birthday");
}
}
This is my routes.js snippet
{
path: '/details/:MEMB_N', component: details
},
I want only to redirect a page if the validation is true and prevent if false.
Right now:
I can access the page I want even if I don't validate the birthday
Use navigation guards on the 'secure' page/component. Read this

How to use DirtyKeys to know if "email" field in PFUser has been modified?

I'm using cloudcode of Parse-Server and mailgun to send email-verification Code to users that signup or change their email.
The BeforeSave Method :
Parse.Cloud.beforeSave(Parse.User, function(request, response) {
var verificationCode = Math.floor(Math.random()*999999);
var text = "Hi ... this is a verification code:" + verificationCode;
var data = {
from: 'WBP Team <info#test.eu>',
to: request.object.get("email"),
subject: 'Please verify your e-mail for you Account',
text: text
};
mailgun.messages().send(data, function (error, body) {
if (error) {
response.error("Email not sent..."+error);
}else{
var user = Parse.User.current();
user.set("emailVerificationCode", verificationCode);
user.save();
response.success("Email Sent");
}
console.log(body);
});
});
Now the email is sent everytime the user modify any filed. But I would like to use the method only when the user change the email.
This has been answered here: you just check if request.object.dirtyKeys() contains "email"; if this is the case, the email property was changed, and you can send your verification.
Note that this check also catches the first saving (i.e. creation) of a user; if you want to avoid sending a mail then, you can use request.object.isNew() to find out if the operation is a create or an update.

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

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");