how can i authenticate user and create jwt token for that with username field in users table and password fields in another table ?
$credentials = [
'phone' => $request->phone,
'confirm.password' => $request->confirmation_code,
];
try {
// attempt to verify the credentials and create a token for the user
if (! $token = JWTAuth::attempt($credentials)) {
return response()->json(['state' => False, 'error' => 'Invalid Credentials.'], 401);
}
} catch (JWTException $e) {
// something went wrong whilst attempting to encode the token
return response()->json(['state' => False, 'error' => 'can not create token !'], 500);
}
my password is in confirm table and password field. the user table in related to confirm table in thier model.
Related
So here it is, I'm trying to make an email confirmation system. Everything is very simple, when creating the account, an account and a token are created and an email with a link containing the email address and the token is sent to the email address used to create the account. The links contained in the email bring back one on a route in GET which has as parameter the email address as well as the token and this route executes a function in a controller and what this function does is mainly to check if the account is already confirmed, if not, it checks if the token is valid and if it is, it changes the value of "emailConfirmed" from false to true. It is able to set itself to true, that is not the problem. The problem is that it does not send this new value of true to the database
Here is the function in my controller:
public function confirmMail($email, $theToken)
{
$user = ZUser::where('email', $email)->take(1)->get()[0];
if ($user->emailConfirmed == false) // If email is not confirmed
{
$token = Token::where('email', $email)->where('token', $theToken)->first(); // Get the line where there is the same email and token then in the URL
if (!is_null($token) || !empty($token)) // If $token is not null or not empty, so if the query found something
{
$user->emailConfirmed = true;
try
{
$user->save();
}
catch (Excpetion $e)
{
return response()->json(['message'=> "Error while saving", 'success' => false, 'status' => "Request Failed", 'id' => null], 400);
}
return response()->json(['message'=> "The value of emailConfirmed is $user->emailConfirmed", 'success' => false, 'status' => "Request Failed", 'id' => null], 400);
}
return response()->json(['message'=> "Cannot confirm the email, non-existent account", 'success' => false, 'status' => "Request Failed", 'id' => null], 400);
}
return response()->json(['message'=> "Email already confirmed", 'success' => false, 'status' => "Request Failed", 'id' => null], 400);
}
Here is my route:
Route::get('/confirm/mail/{email}/{token}', [ControllerUser::class, 'confirmMail'], function ($email, $token) {})->name('confirmMail');
Here is an example of the mail (it is the correct link the the confirmation page):
Here is the result of the confirmation page:
Here is the data in the database after "confirming" the email (emailConfirmed is still at 0):
I am really lost, I don't know why it isn't working since I did the same thing to be able to "create" an account, I had to execute a save on the DB. What can I do the solve the problem ?
I found the answer to my question. The problem was related with the primary key. In my model I had protected $primaryKey = 'iduser';but in my migration the name of the field was actually $table->id('idUser'); so I change my primary key in my model for protected $primaryKey = 'idUser';
How to force the user to fill the form after login with google or facebook. I ma using laravel 5.4 with socials. In my app i want to allow google and facebook login but user can create a standard user too. When login with one of the social providers (facebook or google) i want the user to fill other fields in the form to complete the registration.
The handleProviderCallback:
public function handleProviderCallback($provider)
{
try{
$socialUser = Socialite::driver($provider)->stateless()->user();
}catch (Exception $e){
return redirect('/');
}
// check if we have logged PROVIDER
$socialProvider = Social::where('provider_id', $socialUser->getId())->first();
// if we don`t have a provider create a user and provider
if(!$socialProvider){
// i want the user to go back in the form and finish the registration
return view('auth.socials')->with('socialUser', $socialUser)->with('provider', $provider);
}
else{
// return the user
$user = $socialProvider->user;
}
// log the user in our app :)
auth()->login($user);
return redirect('/home');
the problem is when submiting the form i get an exception:
Client error: `POST https://accounts.google.com/o/oauth2/token` resulted in
a `400 Bad Request` response:
{
"error" : "invalid_grant",
"error_description" : "Invalid code."
}
If i use the method handleProviderCallback like this:
public function handleProviderCallback($provider)
{
try{
$socialUser = Socialite::driver($provider)->stateless()->user();
}catch (Exception $e){
return redirect('/');
}
// check if we have logged PROVIDER
$socialProvider = Social::where('provider_id', $socialUser->getId())->first();
// if we don`t have a provider create a user and provider
if(!$socialProvider){
$user = User::firstOrCreate(
['email' => $socialUser->getEmail()],
// i have to manualy add the missing fields
['name' => $socialUser->getName(), 'forename' => 'test', 'password' => '' ,'address' => 'adasda', 'country' => 'asasfasf', 'town' => 'asfasfsfsfs', 'legal_person' => '0', 'newsletter' => '1', 'phone' => '1235241521']
);
// add provider for this user
$user->socials()->create(
['provider_id' => $socialUser->getId(), 'provider' => $provider]
);
}
else{
// return the user
$user = $socialProvider->user;
}
// log the user in our app :)
auth()->login($user);
return redirect('/home');
}
the user get logged in, but as you can see i have to manually insert the missing fields in the firstOrCreate method (which are required in the users table)
Any suggestion how to do this?
I have an issue with user authentication. I can create a new user and use laravel's Hash::make command to encrypt the password which all appears to be working correctly see database record below :
Now for the login script. I did a dump die on the $input and confirmed it has the post data from the login form inside it.
Code :
public function CheckLogin()
{
$input = Request::all();
// create our user data for the authentication
$userdata = array(
'Email' => $input['email'],
'Password' => $input['password']
);
// attempt to do the login
if (Auth::attempt($userdata)) {
// if(Auth::attempt(['Email' => $input['email'], 'Password' =>$input['password'], 'ArchivedOn' => null])){
//return redirect()->intended('devices');
return redirect()->intended('devices');
} else {
$err = 'Login Failed Please check credentials and try again.';
return view('welcome', compact('err'));
}
}
The Auth::attempt appears to always return false as it always re-directs to the welcome page with the error message I specified.
I expectect I am missing something obvious but I thought I would ask for a fresh pair of eyes on this as I can't see the problem.
Your userdata should be:-
$userdata = array(
'Email' => $input['email'],
'password' => $input['password']
);
Note: You need to write Password 's p character in small letter. You can change email with Email or Username whatever name you want but password must be 'password'.
Check this link for more detail.
So I am developing Ionic app with Laravel back-end and using JWT authentication.
My question is...since im using 4 fields when registering a user, and only 2 when logging in (email and pass), I suppose that upon registration the token should be made of only those 2 fields...
This is the working sign up function:
public function signUp()
{
$credentials = Input::all();
if (User::whereEmail($credentials['email'])->first()) {
return Response::json([
'error' => 'User with given e-mail already exists',
], 409);
} elseif (User::wherePhone($credentials['phone'])->first()) {
return Response::json([
'error' => 'User with given phone number already exists',
], 409);
} else {
$user = User::create($credentials);
$token = JWTAuth::fromUser($user);
return Response::json(compact('token'));
}
}
However if I change $credentials = Input::only('email', 'password') the full user won't be created (since there are fields missing).
But even if I leave $credentials as-is, and make combinations like
$token = JWTAuth::fromUser(Input::only('email', 'password')) or parse e-mail and password to JSON, or something similar...I get a "Trying to get a property of non-object" error, or that array is given instead of an object to JWTAuth...
JWTAuth::fromUser(Input::only('email', 'password')) expects a User object.
If you wish to use credentials you can do something like this:
// grab credentials from the request
$credentials = Input::only('email', 'password');
try {
// attempt to verify the credentials and create a token for the user
if (! $token = JWTAuth::attempt($credentials)) {
return Response::json(['error' => 'invalid_credentials'], 401);
}
} catch (JWTException $e) {
// something went wrong whilst attempting to encode the token
return Response::json(['error' => 'could_not_create_token'], 500);
}
// all good so return the token
return Response::json(compact('token'));
https://github.com/tymondesigns/jwt-auth/wiki/Creating-Tokens
I have a registration form in my site,where the users submits their personal details such as name,email id,dob,and mobile number to be stored in my database. Now I am in the idea to include the connect with facebook button,,by using that link,the user can provide their details by logging into their account. those details can be stored in my database. my expectation looks like this image..help me to implement this
First, you need to decide whether you want to use PHP or JavaScript for Facebook's SDK. Then, download the SDK from:
https://developers.facebook.com/docs/facebook-login/login-flow-for-web/v2.2
Here's a "Getting started" guide for PHP:
https://developers.facebook.com/docs/php/gettingstarted/4.0.0
And here's the same kind of guide for JavaScript:
https://developers.facebook.com/docs/javascript
Here's a part of my code for Facebook Login written with PHP. Note that I'm using CodeIgniter as a framwork for my project:
public function registerWithFacebook()
{
try {
// Proceed knowing you have a logged in user who's authenticated
$facebook_user_data = $this->facebook->get_user();
} catch (FacebookApiException $e) {
$user = null;
print_r($e);
return false;
}
// if we don't have the facebook-user array variable, leave the method
if (!$facebook_user_data) {
return false;
}
// If we can't get the email, leave the method
if(!$facebook_user_data['email']) {
return false;
}
// If user is already registered with Facebook, start sessions and redirect user to app home page (exit the method at this point)
if ($this->facebook_model->facebookUserIdExistsAlreadyInDatabase($facebook_user_data)) {
$session = $this->user_model->getUserInfo($facebook_user_data['id']);
$data = array(
'user_id' => $session['user_id'],
'name' => $session['name'],
'email' => $session['email'],
'profilepic' => $session['profilepic'],
'loggedin' => true,
);
$this->session->set_userdata($data);
redirect(base_url().'home');
exit();
}
// Generate password for new user since you can't get the password from Facebook (obviously)
$generated_password = random_string('alnum', 8);
$data = [
'email' => $facebook_user_data['email'],
'name' => $facebook_user_data['name'],
'password' => $this->phpass->hash($generated_password),
'profilepic' => 'https://graph.facebook.com/'.$facebook_user_data['id'].'/picture?width=160&height=160',
'user_facebook_id' => $facebook_user_data['id'],
];
// Insert data to your database
$new_user = $this->facebook_model->add_facebook_user($data);
// If new user's data was saved successfully to database, start sessions and redirect user
if($new_user) {
$session = $this->user_model->getUserInfo($facebook_user_data['id']);
$data = array(
'user_id' => $session['user_id'],
'name' => $session['name'],
'email' => $session['email'],
'profilepic' => 'https://graph.facebook.com/'.$facebook_user_data['id'].'/picture?width=160&height=160',
'loggedin' => true,
);
$this->session->set_userdata($data);
redirect(base_url().'home');
}
}