Here is my code which is working fine with MySQL but when I switch MySQL to MongoDB registration is working properly but the login attempt is returning false.
I am creating an API for login and registration for my project.
I have also implemented JWT token package in laravel 9.
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Models\User;
use Carbon\Carbon;
class AuthController extends Controller
{
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login','register']]);
}
public function login(Request $request)
{
$request->validate([
'strEmail' => 'required|string|email',
'strPassword' => 'required|string',
]);
$credentials = $request->only('strEmail', 'strPassword');
$token = Auth::attempt($credentials);
if (!$token) {
return response()->json([
'status' => 'error',
'message' => 'Unauthorized',
], 401);
}
$user = Auth::user();
return response()->json([
'status' => 'success',
'user' => $user,
'authorisation' => [
'token' => $token,
'type' => 'bearer',
]
]);
}
public function register(Request $request){
$request->validate([
'strFirstName' => 'required|string|max:255',
'strLastName' => 'required|string|max:255',
'strEmail' => 'required|string|email|max:255|unique:users',
'strPassword' => 'required|string|min:6',
]);
$user = User::create([
'strFirstName' => $request->strFirstName,
'strLastName' => $request->strLastName,
'strEmail' => $request->strEmail,
'strPassword' => Hash::make($request->strPassword),
'isLogin' => 1,
'LastLoginDate'=> Carbon::now(),
'EnterDatetime' => new \DateTime(),
'IP' => \Request::ip(),
]);
$token = Auth::login($user);
return response()->json([
'status' => 'success',
'message' => 'User created successfully',
'user' => $user,
'authorisation' => [
'token' => $token,
'type' => 'bearer',
]
]);
}
}
here is the user model
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Jenssegers\Mongodb\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use PHPOpenSourceSaver\JWTAuth\Contracts\JWTSubject;
use Jenssegers\Mongodb\Eloquent\Model;
class User extends Authenticatable implements JWTSubject
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array<int, string>
*/
please help.
I have tried this code with MySQL and both registration and login work with MySQL.
I finally solved it. Auth only accepts the password field as a "password".
Related
I can sign up and details are then added to the database but I can't use info from the database to successfully login. It just brings back the same page with no error messages. This is the UserController code
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use App\Http\Requests;
use Auth;
class UserController extends Controller
public function getSignin()
{
return view('user.signin');
}
public function postSignin(Request $request)
{
$this->validate($request, [
'email' => 'email|required',
'password' => 'required|min:4'
]);
if (Auth::attempt(['email' => $request->input('email'), 'password' => $request->input('password')])) {
return redirect()->route('user.profile');
}
return redirect()->back();
}
```auth file
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}
Probably because you're saving your password with bcrypt, but on Auth::attempt you pass it in a plain text. Try this:
Auth::attempt(['email' => $request->input('email'), 'password' => bcrypt($request->input('password'))])
Started the project again using Laravel's built in login and register system.
I use postman to add user in my laravel project I get null token but the user has added
why?
{
"token": null }
how I can fix this error?
I use laravel 5.6
and
this my user model :
<?php
namespace App;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password','username','lastname','tel','tel',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* #return array
*/
public function getJWTCustomClaims()
{
return [];
}
}
and this my register controller
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\User;
use JWTFactory;
use JWTAuth;
use Validator;
use Response;
class APIRegisterController extends Controller
{
//
public function register( Request $request){
$validator = Validator::make($request -> all(),[
'email' => 'required|string|email|max:255|unique:users',
'username' =>'required',
'tel' => 'required',
'name' => 'required',
'lastname' => 'required',
'adress' => 'required',
'password'=> 'required'
]);
if ($validator -> fails()) {
# code...
return response()->json($validator->errors());
}
User::create([
'name' => $request->get('name'),
'email' => $request->get('email'),
'tel' => $request->get('tel'),
'username' => $request->get('username'),
'lastname' => $request->get('lastname'),
'adress' => $request->get('adress'),
'password'=> bcrypt($request->get('password'))
]);
$user = User::first();
$token = JWTAuth::fromUser($user);
return Response::json( compact('token'));
}
}
and this is my controller
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\User;
use Illuminate\Support\Facades\Response;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Facades\JWTFactory;
use Validator;
class APIRegisterController extends Controller
{
//
public function register( Request $request){
$validator = Validator::make($request -> all(),[
'email' => 'required|string|email|max:255|unique:users',
'username' =>'required',
'tel' => 'required',
'name' => 'required',
'lastname' => 'required',
'adress' => 'required',
'password'=> 'required'
]);
if ($validator -> fails()) {
# code...
return response()->json($validator->errors());
}
User::create([
'name' => $request->get('name'),
'email' => $request->get('email'),
'tel' => $request->get('tel'),
'username' => $request->get('username'),
'lastname' => $request->get('lastname'),
'adress' => $request->get('adress'),
'password'=> bcrypt($request->get('password'))
]);
$user = User::first();
$token = JWTAuth::fromUser($user);
return Response::json( compact('token'));
}
}
I alreday get a error and this my question question and I fiwx it
how I can fix this error?
I use laravel 5.6
I already had a similar problem before, but I realize my$user->password holds the encrypted password, not the pain text required for login(). Change your code to call
$token = JWTAuth::fromUser($user);
with $user holding the plain text password comming from $request
I solve my problem adding if condition on register function after create user
if ($this->loginAfterSignUp) {
$token = $this->login($request);
}
return $this->respondWithToken($token);
as the title says..
My project was hashing passwords properly until recently I noticed that passwords of new users dont get hashed while it is supposed to be as I am using Hash::make and I used Hash on the top of the controller. Please Help...
here is my User controller
I am using laravel 5.6 if this would help...
namespace App\Http\Controllers\Auth;
use App\User;
use Hash;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
class RegisterController extends Controller
{
use RegistersUsers;
protected $redirectPath = '/admin';
protected function validator(array $data)
{
return Validator::make($data, [
'f_name' => 'required|string|max:255',
'user_id' => 'required|string|max:255|unique:person',
'm_name' => 'required|string|max:255',
'g_name' => 'required|string|max:255',
's_name' => 'required|string|max:255',
'address' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:person',
'field_of_study'=> 'string|max:255',
'gender' => 'required|boolean',
'b_date' => 'required|date|max:255',
'type' => 'required|integer|max:3',
'job_title' => 'string|max:255',
'orgnaization' => 'required|string|max:255',
'sector' => 'boolean',
'mobile' => 'required|string|min:10',
'password' =>'required|string|min:10',
]);
}
protected function create(array $data)
{
return User::create([
'f_name' => $data['f_name'],
'user_id' => $data['user_id'],
'm_name' => $data['m_name'],
'g_name' => $data['g_name'],
's_name' => $data['s_name'],
'address' => $data['address'],
'field_of_study' => $data['field_of_study'],
'gender' => $data['gender'],
'b_date' => $data['b_date'],
'type' => $data['type'],
'job_title' => $data['job_title'],
'orgnaization' => $data['orgnaization'],
'mobile' => $data['mobile'],
'sector' => $data['sector'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
public function register(Request $request)
{
if($user=User::create($request->all()))
{
return redirect('Admin')->with('message', 'done');
}
else
{
return redirect()->back()->with('error', 'error');
}
}
}
and here is my model
protected $fillable = [
'f_name','m_name','g_name','s_name','address','user_id','field_of_study','gender','b_date','type','job_title','orgnaization','mobile','sector', 'email', 'password',
];
protected $hidden = [
'password',
];
use
if ($user = $this->create($request->all()))
instead of
if($user=User::create($request->all()))
You're not calling your controller function, you're just doing User::create. that's why none of your data is being hashed
Maybe this code help you:
$inputData = $request->all();
$inputData['password'] = bcrypt($request->password);
User::create($inputData);
I'm trying to make a login with laravel however, when I use Auth :: Attempt ........ always return false. I have reviewed the code several times, but still can not find the error. could guide me please ?? thanks :)
Model:
<?php
namespace App\Models;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class Users extends Model implements AuthenticatableContract, CanResetPasswordContract
{
use Authenticatable, CanResetPassword;
protected $table = 'users';
}
controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Validator;
use App\Http\Controllers\Controller;
use App\Http\Requests;
use App\Models\Users as user;
class UserController extends Controller
{
public function PreLogin(Request $request){
$validator = Validator::make($request->all(),[
'EmailLogin' => 'require|email',
'PasswordLogin' => 'require|min:6'
]);
if($validator->fails()){
return response()->json([
'success' => false,
'error' => $validator->errors()->toArray()
]);
}else{
return $this->Login($request);
}
}
private function Login(Request $request){
if(Auth::attempt(['email' => $request->EmailLogin, 'password' => $request->PasswordLogin])){
return response()->json([
'success' => true
]);
}else{
return response()->json([
'success' => false,
'error' => 'not login'
]);
}
}
}
auth.php:
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\Users::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
use auth middleware on your route on which you are using Auth :: Attempt
I'm trying to make a login after making the correct validation of the data sent.
validation works correctly, however when I try to login, always returns false. that could have wrong?
thank you very much.
usercontroller:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Validator;
use App\Http\Controllers\Controller;
use App\Http\Requests;
use App\Modals\Users as user;
class UserController extends Controller
{
public function index()
{
return view('home');
}
/**
* #param Request $request
* #return \Illuminate\Http\JsonResponse
*/
public function NewUser(Request $request)
{
$validator= Validator::make($request->all(),[
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:1',
'cpassword'=> 'required||same:password',
]);
if($validator->fails()){
return response()->json([
'success' => false,
'error' => $validator->errors()->toArray()
]);
}else{
return $this->CreateUser($request);
}
}
/**
* #param Request $request
* #return \Illuminate\Http\JsonResponse
*/
private function CreateUser(Request $request){
$user = new User; // was $user = new NewUser();
$user->name = $request->name;
$user->email = $request->email;
$user->password = $request->password; // was $user->passwosrd = $requestt->password
$user->remember_token = $request->_token;
$user->save();
if (Auth::attempt(['email' => $request->email, 'password' => $request->password]))
{
return response()->json([
'success' => true
]);
}else
{
return response()->json([
'success' => false,
'error' => 'not login'
]);
}
}
auth.php
<?php
return [
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Modals\Users::class,
],
'users' => [
'driver' => 'database',
'table' => 'users',
],
],
];
modal:
<?php
namespace App\Modals;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class Users extends Model implements AuthenticatableContract, CanResetPasswordContract
{
use Authenticatable, CanResetPassword;
protected $table = 'users';
}
Try this:
$user = new User; // was $user = new NewUser();
$user->name = $request->get('name');
$user->email = $request->get('email');
$user->password = \Hash::make($request->get('password'));
$user->remember_token = $request->get('_token'); //but why are you storing this?
$user->save();
if (Auth::attempt(['email' => $request->get('email'), 'password' => $request->get('password')]))
{
return response()->json([
'success' => true
]);
}else{
return response()->json([
'success' => false,
'error' => 'not login'
]);
}