Login with name instead of email

Hi there,

I’m trying to create a login page where users can log in with their name instead of email.
How can I make this?

This is the code I use to log in with email:

// simple login form submission example
if($username = get('username') and $password = get('password')) {

  $user = $kirby->user($username);

  if($user and $user->login($password)) {
    // redirect to the homepage
    // or any other page
    
    if(!cookie::exists('loggedin')) {
		cookie::set('loggedin', 'true');
	}
	$url = site()->find("loggedin")->url();
	go($url); 
  } else {
    echo 'Invalid username or password';
  }
}

Find the user by username, get the email address and login with that. Note that you might have more than one user with the same username.

$user = $kirby->users()->findBy('username', $username);

This will return the first user with this username. If you have more than one user with the same username, you will have a problem.

Edit: Did you know we have a “Question :thinking:” category for questions?

1 Like

Thanks for the help!
But when I fill in a wrong password, I get this error:

19

You can wrap your login in a try - catch block and echo an error message instead.

1 Like

You’re an angel!

hello jarneuyt, would you be so kind to post the final code (of your controller, i guess) to solve this? i can follow the discussion here only to a certain point and i would be happy to be able to create a username/password authentification myself…
greetings,
matthias