Laravel 4 - username in URL changes to {Username} after pressing submit - url

I'm new to Laravel and am stuck on a syntax issue. I'm trying to make a view that will enable an admin to change the password of a user but when I click submit the page refreshes and the URL has replaced the username (ex: public/users/alex/edit to public/users/{username}/edit). If anyone could explain why this isn't working it'd be greatly appreciated! I made something similar where the users can change their own password and that one seems to be working fine. My only guess is that I'm not carrying over the $username properly but I haven't a clue of how else to do it. Thank y'all so much! Any bit of info helps!
Here is the UserController for the view:
public function getEdit ($username) {
$user = User::whereUsername($username)->first();
return View::make('users.edit', ['user' => $user]);
}
public function postEdit($username){
$validator = Validator::make(Input::all(),
array(
'password' => 'required|min:6',
'password_again' => 'required|same:password'
)
);
if($validator->fails()){
return Redirect::route('user-edit')
->withErrors($validator)
->with('username', $username);
} else {
/*Change password*/
$user = User::whereUsername($username)->first();
$password = Input::get('password');
$user->password = Hash::make($password);
/*password is the field $password is the variable that will be used in the password field*/
if($user->save()){
return Redirect::route('home')
->with('global', 'The password has been changed.');
}
}
return Redirect::route('account-change-password')
->with('global', 'The password could not be changed.');
}
the Route:
/*ADMIN - edit users (GET)*/
Route::get('users/{username}/edit', array(
'as' => 'user-edit',
'uses' => 'UserController#getEdit'
));
/*ADMIN - edit users (POST)*/
Route::post('users/{username}/edit', array(
'as' => 'user-edit-post',
'uses' => 'UserController#postEdit'
));
and the View/Blade:
#extends('layout.main')
#section('content')
<form action="{{ URL::route('user-edit-post') }}" method="post">
<div class="field">
New password: <input type="password" name="password">
#if($errors->has('password'))
{{$errors->first('password')}}
#endif
</div>
<div class="field">
New password again: <input type="password" name="password_again">
#if($errors->has('password_again'))
{{$errors->first('password_again')}}
#endif
</div>
<input type="submit" value="Change Password">
{{ Form::token() }}
</form>
#stop

It does not seem like you pass the username anywhere inside your form. Have you tried using {{ Form::open(...) }} and {{ Form::close() }} (see http://laravel.com/docs/html)? Those functions will handle parameter passing for you and include hidden variables if necessary.
Good luck!
Michal

Related

Issue in react final form

I am using react final form for validation purpose for login page which has forgot password and register link as well, now when I am clicking forgot password or register link ,it should not trigger any validation even though I am not filling my user name and password .I have tried t keep forgot password and register link away from tag but it is still triggering the validation on click of forgot password and register link .It should only trigger the validation when I m hitting submit button.
It should not ask to validate the form when I am clicking on any hyper link on the page as hyperlinks does not have any validations.
Here is the code sample
loginPage = () => {
const {t: translate} = this.props;
const {
match: {
params: {
authUrlKey = ''
} = {},
} = {},
} = this.props;
return (
<Form
onSubmit={ (values)=> this.validateUserCredentials(values)}
render={({ handleSubmit}) => (
<form onSubmit={handleSubmit}>
<button className="hidden" type="submit"/>
<h1 className="hw-block--pb">{translate('login.heading')}</h1>
<p className="hw-text-lead hw-block--pb-small">{translate('login.text')}</p>
{ this.state.description !=='' && <p className="hw-text-lead hw-block--pb-small">{this.state.description}</p> }
<div className="hw-grid">
<div className="hw-grid__item hw-one-whole hw-medium--one-fifth hw-large--one-sixth">
<label className="hw-label">{translate('login.landcode')}
<Field name="landcode" component={Dropdown} options={getCountryList()} onOptionSelect={this.onCountrySelect}/>
</label>
</div>
<div className="hw-grid__item hw-one-whole hw-medium--four-fifths hw-large--five-sixths">
<label className="hw-label">{translate('login.mobileNumber')}
<Field type="text" component={InputType}
validate={composeValidators(mobileNumberRequired, validMobileNumberWithISDCode)}
placeholder={translate('login.mobileNumberPlaceHolder')} name="phoneNumber"/>
</label>
</div>
</div>
<label className="hw-label">{translate('login.password')}
<Field type="password" component={InputType} validate={passwordRequired} placeholder={translate('login.passwordPlaceHolder')} name="password"/>
</label>
<Link className="hw-link" to={{ pathname: '/password/reset', state: {authUrlKey} }}>{translate('login.forgotPassword')}</Link>
<ErrorInfo error={this.state.error} errorMessage={this.state.errorMessage} translate={translate}/>
<div className="hw-block hw-block--mt-small">
<div className="hw-grid">
<div className="hw-grid__item hw-small--one-whole hw-medium--one-quarter hw-block--mb-smaller">
<button className="hw-button hw-button--primary hw-button--full" type="submit">{translate('login.loginButton')}</button>
</div>
<div className="hw-grid__item hw-one-whole hw-medium--three-quarters hw-block--mt-smaller">
<Link className="hw-link"
to={{ pathname: '/register', state: {authUrlKey} }}>{translate('login.registerButton')}</Link>
</div>
</div>
</div>
</form>)}
/>
)}
validations function used in code
export const validMobileNumberWithISDCode = (fieldValue='') => {
const value = trimValue(fieldValue);
const regex1 = /^\+?((45)|(46)|(47))?( )?\d{8,10}$/
return (regex1.test(value))? undefined : message[root.lang].validMobileNumber;
}
export const validMobileNumber = (fieldValue='') => {
const value = trimValue(fieldValue);
const regex1 = /^\d{8,10}$/;
return (regex1.test(value))? undefined : message[root.lang].validMobileNumber;
}
export const mobileNumberRequired = (fieldValue='') => {
const value = trimValue(fieldValue);
return value ? undefined : message[root.lang].mobileNumberRequired;
}
export const passwordRequired = (fieldValue='') => {
const value = trimValue(fieldValue);
return value ? undefined: message[root.lang].passwordRequired;
}
export const required =(fieldValue)=> {
const value = trimValue(fieldValue);
return value ? undefined : message[root.lang].required;
}```
validateUserCredentials -> This function does not contains any validation.It is used to retrieve form values and send it to server
React Final Form calls your validation function on every value change in the form, to ensure that the form validity is always up to date. Since you did not include the code for your validation function, I cannot ascertain what you are attempting to do. Your validation function should be very cheap to run (e.g. required fields, value length, etc.). The actual authentication should happen on submit.

Redirect to URI sends back the POSTed params added in browser's URL bar

Grails Version: 3.3.4,
Groovy Version: 2.4.14,
JVM Version: 1.8.0_161,
Kubuntu 14.04
I wrote a simple authentication form (in the end it will be POSTed through https):
<form action='auth' method='POST' id='loginForm' class='cssform' autocomplete='off'>
<p>
<label for='j_username'>Login ID</label>
<input type='text' class='text_' name='j_username' id='j_username' />
</p>
<p>
<label for='j_password'>Password</label>
<input type='password' class='text_' name='j_password' id='j_password' />
</p>
<p>
<input type='submit' value='Login' />
</p>
The controller is:
class LoginController {
def index() {
if (session.user?.name == 'test') {
render view: '/login/youarealreadyin'
}
else {
render view: '/login/auth'
}
}
def auth() {
def loginName = params.j_username?.trim()
def pass = params.j_password?.trim()
if (loginName == 'test' && pass == 'TEST' ) {
session.user = [name: loginName]
redirect uri: '/'
}
else {
render view: '/login/denied'
}
}
}
After correct login and redirect to uri: '/' - I see the name and password in the URL field of the browser:
http://localhost:8080/?j_username=test&j_password=TEST
I could swear that this didn't happen with grails 3 in the first versions... I cannot remember when...
It would be nice, not to send back the POSTed password as GET params in the URL.
If I render a specific view instead to redirect it doesn't happen.
If you are reporting this as undesired behavior, our GitHub issue tracker at https://github.com/grails/grails-core/issues is a better place to do that. This has already been reported though at https://github.com/grails/grails-core/issues/10965 and it looks like the fix has been verified in 3.3.5.BUILD-SNAPSHOT and looks good.
If you are simply asking if this is intended behavior, it isn't.

ember-simple-auth cookieExpirationTime not working

I need to implement a "remember me" feature in my application.
I am using the built-in devise authenticator and have the following as my Session Store:
// app/session-stores/application.js
import CookieStore from 'ember-simple-auth/session-stores/cookie';
export default CookieStore.extend({
cookieName: 'myapp-session-cookie'
});
I have a login-form component with the following:
rememberMe: false,
setExpirationTime() {
const expirationTime = this.get('rememberMe') ? (14 * 24 * 60 * 60) : null;
this.set('session.store.cookieExpirationTime', expirationTime);
},
actions: {
authenticateWithDevise() {
this.setExpirationTime();
let { identification, password } = this.getProperties('identification', 'password');
this.get('session').authenticate('authenticator:devise', identification, password).then(() => {
this.sendAction('onLoggedIn');
}).catch((reason) => {
this.set('errorMessage', reason.errors[0]);
});
}
}
and of course in the corresponding template I have:
<form role="form" {{action "authenticateWithDevise" on="submit"}}>
{{input type="email" value=identification placeholder="Email" class="icon-email"}}
{{input type="password" value=password placeholder="Password" class="icon-lock"}}
{{input id='remember_me' type='checkbox' checked=rememberMe}}
</form>
What happens is session is never remembered, no matter whether cookieExpirationTime was set or null.
My question is: should I also implement something else on the server side? I'm currently using devise's rememberable. Also, I've tried searching both here and on github but can only find conversations and code that seems obsolete, like this:
https://github.com/simplabs/ember-simple-auth/pull/451
Can somebody please shed some light? Thanks!

Symfony3 - Repeated FieldType not rendering

I have a repeated fieldtype that is not being rendered when I access the page.
I have this method in my controller:
/**
* #Route("/{token}", name="pass_reset_form")
*
* Function to reset password.
*/
public function ResetAction(Request $reset, $token)
{
$form = $this->createForm(ResetformType::class);
$form->handleRequest($reset);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('VendorMyBundle:Logins')->findByToken($token);
if (!empty($user))
{
// encode password and update in the DB
$password = $this->get('security.password_encoder')
->encodePassword($user[0], $form["newPassword"]->getData());
$user[0]->setPassword($password);
$em->flush();
$this->addFlash('notice', 'The password has been successfully reset. You can now login.');
return $this->redirectToRoute('login_route');
}
}
return $this->render(
'VendorMyBundle:Default:resetEntry.html.twig',
array('form' => $form->createView())
);
}
and this is the ResetformType:
namespace Vendor\MyBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
class ResetformType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('newPassword', RepeatedType::class, array(
'type' => PasswordType::class,
'invalid_message' => 'The password fields must match.',
'required' => true,
'first_options' => array('label' => 'Password'),
'second_options' => array('label' => 'Repeat Password'),
));
}
}
and this is the standard twig code:
{% block body1 %}
{{ form_start(form) }}
<button type="submit">Reset Password</button>
{{ form_end(form) }}
{% endblock %}
Whenever I access the route that takes me on that rendered view I only see the form button. I view page source and all that is in HTML is the form button and a hidden form token field.
<form name="resetform" method="post">
<button type="submit">Reset Password</button>
<input type="hidden" id="resetform__token" name="resetform[_token]" value="2NJ7Uht8bgVUV27GnD4FHrCOjTFCIXXQyraJkG4jSmc" />
</form>
What am I missing?
Answering for anybody who bumps into the same issue.
Either clear your cache or specifically render fields separately, in my case with:
{{ form_row(form.newPassword) }}.

MVC 5 - Prevent password storing

I need to prevent the storing of username/password on my MVC 5 site.
I have set the both the form and input elements to autocomplete="off" and I'm sure the site is running HTML5. For all intents and purposes it should not want to store the login information, yet, it still prompts for it after login.
As suggested, I tried changing the input field names to something other than "username" and "password", but it changed nothing.
I have even tried the trick of adding dummy username & password hidden elements outside the form, tried inside the form as well. No joy.
I have also tried doing it in jQuery, with no success
$("input").attr("autocomplete", "off");
Form tag:
<form action="/" autocomplete="off" class="form-horizontal" method="post" role="form" novalidate="novalidate">
input element:
<input autocomplete="off" class="form-control" data-val="true" data-val-regex="Mobile number must be a Numbers only." data-val-regex-pattern="[0-9]*\.?[0-9]+" data-val-required="The Mobile field is required." id="Username" name="Username" type="text" value="">
Tested in IE and chrome, but prompt to save info.
Any help or advice would be greatly appreciated. How do banks prevent this?
I tested many solution and finally, came with this one.
HTML code
#Html.TextBoxFor(m => m.UserName, new { #class = "form-control", #placeholder = "UserName", #autofocus = "", #autocomplete = "off" })
#Html.TextBoxFor(m => m.Password, new { #class = "form-control", #placeholder = "Password", #autocomplete = "off" })
CSS code
#Password {
text-security: disc;
-webkit-text-security: disc;
-moz-text-security: disc;
}
JavaScript code
window.onload = function () {
init();
}
function init() {
var x = document.getElementsByTagName("input")["Password"];
var style = window.getComputedStyle(x);
console.log(style);
if (style.webkitTextSecurity) {
// Do nothing
} else {
x.setAttribute("type", "password");
}
}

Resources