allow both username and email in login laravel 5 - authentication

I use laravel's 5 built in authentication for login. im spending hours finding where is the database query located at that has been use when login, I want to both allow email and username is the email box. Anyone knows where that database query located at? anyone knows how to allow both username and password on the authentication.
PS: to sharpen the details, I just want the user to allow them to login both username and email.
PS: again! Im running on laravel 5 not 4!

Define both a login and an password input in your form then the request should look like :
public function authorize() {
return true;
}
public function rules()
{
return [
'login' => 'required',
'password' => 'required'
];
}
Then your login function should look like :
public function login(LoginRequest $request)
{
$field = filter_var($request->input('login'), FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
$request->merge([$field => $request->input('login')]);
if ($this->auth->attempt($request->only($field, 'password')))
{
return redirect('/');
}
return redirect('/login')->withErrors([
'error' => 'You email/username or password combination is wrong.',
]);
}
This is an optimized version because instead of doing 2 attemps to verify the credentials for both : if is a username or if is a password, laravel will do the work with verifying if the given data points to an email login or username.

Related

Login a user to wordpress from external application

Hi I am building a React native app based on my wordpress website so I need to make a registration and login logic to get the user id and user data, thankfully I made the registration logic by creating new user using the rest api, but I need help in making the login thing since I find nothing helpful while searching Google.
I want to post the username or email and the password to authenticate that the user do exist in my site
register_rest_route(
'custom-plugin', '/login/',
array(
'methods' => 'POST',
'callback' => 'login',
)
);
}
function login($request){
$creds = array();
$creds['user_login'] = $request["username"];
$creds['user_password'] = $request["password"];
$creds['remember'] = true;
$user = wp_signon( $creds, false );
if ( is_wp_error($user) )
echo $user->get_error_message();
return $user;
}
add_action( 'after_setup_theme', 'custom_login' );
Then your API will be created as
http://www.url.com/wp-json/custom-plugin/login
Try it with Postman You will get 200 as a response and user info
body:
{
"username": ""fakmamail#gmail.com",//or the username
"password": "t433434533"
}

Send email with TDD Laravel 5.6

I am doing the registration user
public function register(RegistrationUser $request)
{
$user = $this->usersRepo->create($request->all());
$user->activation_token = str_random(48);
$user->save();
Mail::to($user->email)->queue(new ActivationAccount($user->first_name, $user->last_name, $user->email, $request->input('password'), $url));
return redirect()->route('successful.registration')
}
My registration test is:
public function it_creates_a_new_user()
{
$this->withExceptionHandling();
$response = $this->get(route('register'))
->assertStatus(200);
$this->post('register', [
'first_name' => 'Juan',
'last_name' => 'Lopez',
'email' => 'jlopez#gmail.com',
'password' => 'secret',
'activation_tone' => str_random(48)
])->assertRedirect(route('successful.registration'));
$this->assertDatabaseHas('users', [
'email' => 'jlopez#gmail.com',
]);
}
I have two questions:
1) How can I write a test to send the registration email and verify that it sends and arrives well?
2) When the user clicks on his email he calls a method where the activation token is passed to activate his account
In my opinion you should use mail fake ,which will prevent mail from being sent. You may then assert that mailables were sent to users and even inspect the data they received.
please read laravel docs: https://laravel.com/docs/5.6/mocking#mail-fake
There must be a route which is handling activation token and functionality, so try to get the token and call route with specific token
Note: As a developer we need to make sure that our code works which our tests are confirming, Sending and delivering email should be not be covered as they considered to work as expected(by any email service provider).

How to send user login credentials after user registers

I am using laravel's default login and registration. I have successfully set up authentication, however I would like to send user's username and password to the emails they used during registration. How can I achieve this?
You can initiate a mail to user after you validated input received and before your create functions of your register controller present in
$email = new UserRegisterData(new User(['password' => $user->password, 'name' => $user->name]));
To do this you need to rewrite
protected function validator(array $data)
function in your register controller and modify that with this mail. as
protected function validator(array $data)
{
$email = new UserRegisterData(new User(['password' => $user->password, 'name' => $user->name]));
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:customers',
'password' => 'required|min:6|confirmed',
]);
}
once you hashed your password in create function, i think it can't be read. Also check if any security issue it may generate. Also you need to create mail as 'UserRegisterData' and add necessary code in it.

Laravel 5 multiple authentication

How can you set up multiple authentication in Laravel 5. Out of the box you can only set up 1 authentication. What if I have a customers table and an admin table and wish to set up authentication for each - each authenticated type of user should be restricted from viewing or accessing admin pages and vis versa?
* UPDATE *
I've created a users table which holds information common to both a jobseeker and recruiter i.e. name, password etc.
I've created a roles and role_user table
I've created two separate tables to hold jobseeker_profile and recruiter_profile
How can you authenticate a user with a role of type jobseeker using the following routes?
Route::get('jobseeker/login', 'Auth\AuthController#getLogin');
Route::post('jobseeker/login', 'Auth\AuthController#postLogin');
Route::get('recruiter/login', 'Auth\AuthController#getLogin');
Route::post('recruiter/login', 'Auth\AuthController#postLogin');
And how can you secure routes once authenticated - in the following how is the middleware going to know the type of user:
Route::get('jobseeker/profile', ['middleware' => 'auth', 'uses' => 'JobseekerProfileController#show']);
Route::get('jobseeker/profile/update', ['middleware' => 'auth', 'uses' => 'JobseekerProfileController#updateProfile']);
class JobseekerProfileController extends Controller {
public function updateProfile()
{
if (Auth::user())
{
// Auth::user() returns an instance of the authenticated user...
}
}
}
Laravel 5 authentication controller uses the following trait -would you edit the trait with your answer or create a new authentication controller with your answer below?
trait AuthenticatesAndRegistersUsers {
public function postLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email', 'password' => 'required',
]);
$credentials = $request->only('email', 'password');
if ($this->auth->attempt($credentials, $request->has('remember')))
{
return redirect()->intended($this->redirectPath());
}
return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors([
'email' => 'These credentials do not match our records.',
]);
}
}
You may create a roles table in your db assign role to every user accordingly and then at the time of login check what role a user have and then you can redirect/show pages accordingly. No need to create separate tables for every type of user.
Edited answer
if(Auth::attempt(['email' => $request->email, 'password' => $request->password]))
{
//using role with an expectation that you have one relation method named role defined in User model
//and roles table stores user type as name
if(Auth::user()->role->name == 'admin')
{
return redirect()->to('/administrator/dashboard');
}
elseif(Auth::user()->role->name == 'jobseeker')
{
return redirect()->to('jobseeker/dashboard');
}
}
You can achieve multiple authentication by this package
https://packagist.org/packages/sarav/laravel-multiauth
For more detailed explaination check my previously return answer here
How to use authentication for multiple tables in Laravel 5

How to do a Sign Up with OAuth (facebook, twitter, google)?

I use Laravel (5) as my php framework, it recently added a library for social authentication (facebook, google, twitter and github).
I've been wondering how would you do a Sign Up with OAuth, a login can easily be done by getting the user's email via OAuth, checking if it exists in your DB, and if it does, then log in that user. But how would you do the Sign Up?
Mathius - I've recently been working on a site doing something similar to what you've described and this is what has worked for me:
public function syncUserDetails($userData)
{
// First I check to see if there is a user in the DB
// with the oAuth email address
if ( $user = $this->user->where('email', $userData->email)->first() )
{
// If there is a user, I simply update their local info
// with what is on their oAuth account
$user->token = $userData->token;
$user->google_id = $userData->id;
$user->name = $userData->name;
$user->avatar = $userData->avatar;
$user->first_name = $userData->user['given_name'];
$user->last_name = $userData->user['family_name'];
$user->save();
return $user;
}
// Otherwise, if the user doesn't already exist,
// I create them in my local user's DB
return $this->user->firstOrCreate([
'email' => $userData->email,
'token' => $userData->token,
'google_id' => $userData->id,
'name' => $userData->name,
'avatar' => $userData->avatar,
'first_name' => $userData->user['given_name'],
'last_name' => $userData->user['family_name']
]);
}
This is what I'm using to log in a user. However, you could just as easily run this alongside your regular Laravel login method.