Login when successfully updated the data of the user in Laravel - laravel

RegisterController.php
I added here an update function so that when the user wants to login with Facebook, he/she will be redirected to a form and then fill the fields so that their information will be stored in the Database.
protected function create(array $data)
{
if ($data['userEmail']) {
return User::where('email', $data['userEmail'])
->update([
'phone_number' => $data['phone_number'],
'address' => $data['address'],
'country' => $data['country'],
'city' => $data['city'],
'zip_code' => $data['zip_code'],
'state' => $data['state'],
'is_online' => true,
]);
} else {
return User::create([
'full_name' => $data['full_name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'phone_number' => $data['phone_number'],
'address' => $data['address'],
'country' => $data['country'],
'city' => $data['city'],
'zip_code' => $data['zip_code'],
'state' => $data['state'],
'is_online' => true,
]);
}
}
The error when the IF statement returns true is this
"Type error: Argument 1 passed to
Illuminate\Auth\SessionGuard::login() must implement interface
Illuminate\Contracts\Auth\Authenticatable, integer given, called in
C:\xampp\htdocs\esoftwaredeals\vendor\laravel\framework\src\Illuminate\Foundation\Auth\RegistersUsers.php
on line 35".
However, if it returns false, there will be no error and a new user is created and will automatically redirect to the "/my-account" page which is where I wanted to redirect when the user successfully updated their information.

You need to return User instance from the create() method:
protected function create(array $data)
{
if ($data['userEmail']) {
$user = User::where('email', $data['userEmail'])->first();
$user->update([
'phone_number' => $data['phone_number'],
'address' => $data['address'],
'country' => $data['country'],
'city' => $data['city'],
'zip_code' => $data['zip_code'],
'state' => $data['state'],
'is_online' => true,
]);
} else {
$user = User::create([
'full_name' => $data['full_name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'phone_number' => $data['phone_number'],
'address' => $data['address'],
'country' => $data['country'],
'city' => $data['city'],
'zip_code' => $data['zip_code'],
'state' => $data['state'],
'is_online' => true,
]);
}
return $user;
}
Also, you should use the updateOrCreate() method to keep the code maintainable. For example:
protected function create(array $data)
{
$data['password'] = bcrypt($data['password']);
return User::updateOrCreate(
array_only($data, ['email', 'full_name']),
array_except($data, ['email', 'full_name'])
);
}

An update query returns the number of rows that where affected by the update query.So when the update user is successful it will return 1.
The create method returns the saved model instance. So this is causing the issue in your code.
You can use find and save method provided by eloquent and return the user object in if statement and it will work.
$user = User::where('email', $email)->first();
$user->firstname = $firstname;
$user->lastname = $lastname;
$user->save();
return $user;
Try like this and it should work.

$user = User::find($usuario->ID);
$user->rol_id = 1;
$user->save();
}
}
}
return view('dashboard.index')->with(compact('cantReferidosDirectos', 'cantReferidosIndirectos', 'cantReferidosActivos', 'fechaProxActivacion', 'new_member',
'cantventas', 'cantventasmont', 'fullname', 'rangos', 'cantAllUsers', 'rankingComisiones', 'rankingVentas', 'permiso','noticias', 'contTicket', 'moneda',
'nombreRol'
));
}
/**
* Permite actualizar las informacion de los usuarios
*
* #access public
* #return view
*/
public function ActualizarTodo()
{
$comisiones = new ComisionesController;
$comisiones->ObtenerUsuarios();
$todousers = $this->generarArregloUsuario(Auth::user()->ID);
foreach ($todousers as $user ) {
if ($user['rol'] != 0) {
$activacion = new ActivacionController;
$activacion->activarUsuarios($user['ID']);
}
}
Arguments
"compact(): Undefined variable: fechaProxActivacion"
Como soluciono este error

Related

Laravel auth - Two step registeration

I do not know English much.
I want to register a member with 2 steps but I get an error
I am getting error different from type 1
Error : SessionGuard::login() must be an instance of
protected function create(array $data)
{
if ($data['type'] == 0){
$user = User::create([
'type' => 0,
'name' => $data['name'],
'gender' => $data['gender'],
'email' => $data['email'],
'phone' => $data['phone'],
'password' => Hash::make($data['password']),
]);
$user->assignRole('User');
return $user;
} else {
// Redirect to 2 step form.
}
}
Step 2 Form:
<form>
... bla bla bla
</form>
Step 2 create function :
protected function create(array $data)
{
$user = User::create([
'type' => 1,
'name' => $data['name'],
'gender' => $data['gender'],
'email' => $data['email'],
'phone' => $data['phone'],
'password' => Hash::make($data['password']),
]);
}
Help me please...

JwtAuth is not generating tokens in Backpack Laravel

I am using backpack laravel. Though I am also using Backpack's own authentication, yet I need to maintain a different customer table for App usage. For the customer table, I am using JWTAuth for token generation, but token generation gets failed each time.
public function register(Request $request)
{
$checkEmail = Customer::where('email', $request->email)->first();
if ($checkEmail) {
$response = [
'email_already_used' => true,
];
return response()->json($response);
}
$payload = [
'password' => \Hash::make($request->password),
'email' => $request->email,
'first_name' => $request->first_name,
'last_name' => $request->last_name,
'auth_token' => '',
];
try {
$user = new \App\Models\Customer($payload);
if ($user->save()) {
$token = self::getToken($request->email, $request->password); // generate user token
if (!is_string($token)) {
return response()->json(['success' => false, 'data' => 'Token generation failed'], 201);
}
$user = \App\Models\Customer::where('email', $request->email)->get()->first();
$user->auth_token = $token; // update user token
$user->save();
$response = [
'success' => true,
'data' => [
'id' => $user->id,
'auth_token' => $token,
'first_name' => $user->first_name,
'last_name' => $user->last_name,
'email' => $user->email,
],
];
} else {
$response = ['success' => false, 'data' => 'Couldnt register user'];
}
} catch (\Throwable $e) {
echo ($e);
$response = ['success' => false, 'data' => 'Couldnt register user.'];
return response()->json($response, 201);
}
return response()->json($response, 201);
}
I believe there might be some issue with guards.
Do I need to specify something in app/config.php for this?

Auth::attempt value always false

I have some problem when I want to make login, I got an issue for my Auth::attempt always false value, Is am I got something wrong in my code?
Controller :
public function register(Request $register)
{
$validator = Validator::make($register->all(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
]);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors()], 401);
} else {
$name = $register->input('name');
$email = $register->input('email');
$pwd = $register->input('password');
$c_pwd = $register->input('c_password');
// Crypting password & c_password to md5
$md5_pwd = md5($pwd);
$md5_c_pwd = md5($c_pwd);
// Salt password & c_password
$password = crypt($md5_pwd, "asd");
$c_password = crypt($md5_c_pwd, "asd");
$data = new User();
if ($password == $c_password) {
$user = User::create([
'name' => $name,
'email' => $email,
'password' => $password,
]);
$success['token'] = $user->createToken('SSOApp')->accessToken;
return response()->json([
'success' => true,
'token' => $success,
'user' => $user
]);
} else {
return response()->json(['error' => "Password doesn't match"], 401);
}
}
}
public function login()
{
$email = request('email');
$pwd = request('password');
$md5 = md5($pwd);
$password = crypt($md5, "asd");
if (Auth::attempt(['email' => $email, 'password' => $password])) {
$user = Auth::user();
$success['token'] = $user->createToken('SSOApp')->accessToken;
return response()->json([
'success' => true,
'token' => $success,
'user' => $user
]);
} else {
return response()->json([
'success' => false,
'message' => 'Invalid Email or Password',
], 401);
}
}
I assume you messed up with Laravel Default Password Hashing System
public function register(Request $register)
{
$validator = Validator::make($register->all(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
'c_password' => 'required|same:password',
]);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors()], 401);
} else {
$name = $register->input('name');
$email = $register->input('email');
$pwd = $register->input('password');
$c_pwd = $register->input('c_password');
// $data = new User();
$user = User::create([
'name' => $name,
'email' => $email,
'password' => bcrypt($password . 'salt'),
]);
$success['token'] = $user->createToken('SSOApp')->accessToken;
return response()->json([
'success' => true,
'token' => $success,
'user' => $user
]);
}
}
public function login()
{
$email = request('email');
$pwd = request('password');
if (Auth::attempt(['email' => $email, 'password' => $password . 'salt'])) {
$user = Auth::user();
$success['token'] = $user->createToken('SSOApp')->accessToken;
return response()->json([
'success' => true,
'token' => $success,
'user' => $user
]);
} else {
return response()->json([
'success' => false,
'message' => 'Invalid Email or Password',
], 401);
}
}
Try this code. I don't know what happened to your code about the password you tried to encrypt it in attempt.
public function login(LoginRequest $request) {
if(!Auth::attempt([
'email' => $request->email,
'password' => $request->password,
'active' => true
])) {
return response()->json('Email or Password is incorrect', 500);
}
$this->user = Auth::user()->load('roles');
return $this->createUserAccessTokenResponse();
}
protected function createUserAccessTokenResponse() {
return response()->json([
'status' => 'success',
'data' => [
'token' => $this->user->createToken($this->user->name)->accessToken,
'user' => $this->user
],
], 200);
}
your problem is that laravel by default hashes the password. so when you do Auth::attempt it's going to hash the password you provided. And the result is what you get, it will always false.
Instead, you need to Other Authentication Methods.
Auth::login($user);
// Login and "remember" the given user...
Auth::login($user, true);
Above is the easiest way to fix your code.
It's recommended to hash your password rather than encrypting the password.
Hashing password in laravel is also
Hash::make($password);
And then you can use Auth::attempt to log in your user.
Laravel Auth uses the bcrypt hashing when saving password via model you may use either of the 2 method
$account->password = bcrypt("YOUR_PASSWORD"); or $account->password = Hash::make("YOUR_PASSWORD");
Then if you're dealing with the auth attempt function, just simply call the method like this
if($account = Auth::attemp(['email' => "YOUR_EMAIL#DOMAIN.COM", 'password' => "YOUR_PASSWORD"])){
//success login, do your extra job here
}else{
//invalid credentials here
}
Instead of using md5 or crypt use \Hash::make() it is much secure
I refactored your code and it does the same thing
You only need to rename your c_password to password_confirmation
Source
Below code does the same thing that your code do
public function register(Request $register)
{
$this->validate($register, [
'name' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed',
]);
$user = User::create([
'name' => $register->input('name'),
'email' => $register->input('email'),
'password' => $register->input('password'),
]);
$success['token'] = $user->createToken('SSOApp')->accessToken;
return response()->json([
'success' => true,
'token' => $success,
'user' => $user,
]);
}
public function login(Request $request)
{
$request->merge(['password' => \Hash::make($request->input('password'))]);
if (Auth::attempt($request->only(['email', 'password']))) {
$user = Auth::user();
$success['token'] = $user->createToken('SSOApp')->accessToken;
return response()->json([
'success' => true,
'token' => $success,
'user' => $user,
]);
}
return response()->json([
'success' => false,
'message' => 'Invalid Email or Password',
], 401);
}
when you hashing password using crypt it has a key to unlock it that's why there is a decrypt but when you use Hash::make() it doesn't have a key to break or unlock it, it will check it's algorithm to see if given password is matching the algorithm that already exists in the database that's why crypt is not safe and Hash::make is much much more safe

custom table in user model laravel

I'm using oauth2 and my table users is "coUsers" . I added this in my User Model
App\User
protected $table = 'coUsers';
public function getAuthPassword()
{
return $this->pass;
}
AuthController
public function login(Request $request)
{
$request->validate([
'usuario' => 'required|string|email',
'clave' => 'required|string',
//'remember_me' => 'boolean'
]);
$credentials = [
'usuario' => $request->get('usuario'),
'password' => $request->get('clave'),
];
if(!Auth::attempt($credentials)){
return response()->json([
'message' => 'Unauthorized'
], 401);
}
$user = $request->user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
if ($request->remember_me)
$token->expires_at = Carbon::now()->addWeeks(1);
$token->save();
return response()->json([
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'expires_at' => Carbon::parse($tokenResult->token->expires_at)->toDateTimeString()
]);
}
public function firstLogin(Request $request)
{
$request->validate([
'usuario' => 'required|string|email|unique:users',
'clave' => 'required|string',
'nuevaClave' => 'required|string'
]);
$user = User::where('usuario', $request['usuario'])
->where('clave', $request['clave'])
->first();
$user->clave = bcrypt($request['nuevaClave']);
$user->first_login = false;
$user->save();
return response()->json([
$user->toArray()
]);
}
Auth login works OK, but I want to use User::where in firstLogin.... I get this error:
Illuminate\Database\QueryException: SQLSTATE[42703]: Undefined column: 7 ERROR: column "usuario" does not exist
LINE 1: select count() as aggregate from "users" where "usuario" = ...
^ (SQL: select count() as aggregate from "users" where "usuario" = xxxxx#gmail.com) in file \vendor\laravel\framework\src\Illuminate\Database\Connection.php on line 669
Look in the users table instead of using the table that I indicated in the model.
You may change 'usuario' => 'required|string|email|unique:users', to 'usuario' => 'required|string|email|unique:coUsers', in your firstLogin method
You may also change this 'unique:users' in validator method inside your App\Http\Controllers\Auth\RegisterController
'email' => ['required', 'string', 'email', 'max:255', 'unique:users']
to
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:coUsers'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}

How can i pass only one message for all fields

This is code of register function which generate error of success and failure.
public function register(Request $request) {
$validator = Validator::make($request->all(),
[
'user_type' => 'required',
'fname' => 'required',
'lname' => 'required',
'dob' => 'required',
'phone' => 'required',
'gender' => 'required',
'uname' => 'required',
'email' => 'required|email',
'password' => 'required',
'c_password' => 'required|same:password',
]);
if ($validator->fails()) {
return response()->json(['failed'=>$validator->errors()], 401); }
$input = $request->all();
$input['password'] = bcrypt($input['password']);
$user = User::create($input);
$success['token'] = $user->createToken('AppName')->accessToken;
$success['status'] = true;
$success['data'] = [$user];
$success['message'] ="User created successfully!";
// return response()->json([
// "message" => " record created"
// ], 201);
return response()->json($success, $this->successStatus);
}
This is my output
1.All error message show in one line..This is my main point..But i want to actually this message of This image...How can i do that?
2.Second thing in API if any user put same email id api give json error not laravel error..
Try this:
return response()->json(['status'=> False, 'msg' => 'This is not successful'], 401);
You can pass custom json in response instead of validator response.
For checking if email exists update the validation like this:
'email' => 'required|email|unique:users,email',
where users is your table name and email is your column name
You just need to replace your code
if ($validator->fails()) {
return response()->json(['failed'=>$validator->errors()], 401);
with
if ($validator->fails()) {
return response()->json(['status'=> 'False', 'msg' => 'This is not sccessfully'], 401);

Resources