Laravel won't send response after a successful create of an account - php

I can save the data to the database just fine. And then I right after the creation I'll login that current user with the email. But it will always be sending a request. What might be the problem here?
class RegisterController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = '/home';
private $loginProxy;
public function __construct(LoginProxy $loginProxy)
{
$this->loginProxy = $loginProxy;
$this->middleware('guest')->except('logout');
}
function apiRegisterUser(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6',
]);
if ($validator->fails()) {
return response()->json(array('code' => 406, 'error' => $validator->messages()), 406);
} else {
// Log::channel('abuse')->info('user');
$user = User::create(['name' => $request['name'],
'email' => $request['email'],
'password' => Hash::make($request['password']),
'referral_code' => str_random(10)
]);
$user->updateLastRoute(1);
$credentials = $this->loginProxy->attemptLogin($request['email'], $request['password']);
return response()->json($this->successResponse(200, "Login successfull", $credentials), 200);
}
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
]);
}
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}

use auth()->attempt() function i m not sure about loginProxy
but auth()->attempt() this should work
$credentials = [
"email" => $request['email'],
"password" => $request['password']
];
if (auth()->attempt($credentials)) {
return response()->json($this->successResponse(200, "Login successfull", $credentials), 200);
}

Related

Laravel 5 how to check User exists in my other table

How to check if user exists in my table or redirect back with a message using Laravel 5.6?
Type error: Argument 1 passed to Illuminate\Auth\SessionGuard::login() must be an instance of Illuminate\Contracts\Auth\Authenticatable, instance of Illuminate\Http\RedirectResponse given, called in C:\wamp\www\zainsurgalt\vendor\laravel\framework\src\Illuminate\Foundation\Auth\RegistersUsers.php on line 35
protected function create(array $data)
{
$isEmailExists = Niigem::where('email', $data['email'])->count();
if($isEmailExists){
User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
else{
return Redirect::back()->withErrors(['msg', 'The Message']);
}
}
I Added my Create method here
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Niigem;
use Validator;
use Illuminate\Support\Facades\Redirect;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
use RegistersUsers;
protected $redirectTo = '/home';
public function __construct()
{
$this->middleware('guest');
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
protected function create(array $data){
$validator = Validator::make($data, [
'name' => 'required|string',
'email' => 'required|string|email|exists:niigems',
'password' => 'required|string',
]);
if ($validator->fails()) {
return Redirect::back()
->withErrors($validator)
->withInput();
}
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
You need to return something when the user is created.
protected function create(array $data)
{
$isEmailExists = Niigem::where('email', $data['email'])->count();
if($isEmailExists){
User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
return ........ you need to return something here
} else {
return Redirect::back()->withErrors(['msg', 'The Message']);
}
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|max:255|unique:users|exists:niigems',
'password' => 'required|min:6|confirmed',
]);
}
protected function create(array $data)
{
User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
I see your are trying to create a new user if they exist in the niigem table. To do it the Laravel way, you have to validate using Laravel's validation class. So, this should work:
protected function create(array $data)
{
$validator = Validator::make($data, [
'name' => 'required|string',
'email' => 'required|string|email|exists:niigem',
'password' => 'required|string',
]);
if ($validator->fails()) {
return Redirect::back()
->withErrors($validator)
->withInput();
}
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
Another way is:
Niigem::firstOrCreate(['email' => 'dummy#domain.com'], ['name'=> $data['name'], 'password' => bcrypt($data['password'])]);
Please use this query you can use both condition as per your need:
$user = Niigem::where('email', '=', Input::get('email'))->first();
if ($user === null) {
// user doesn't exist
}
if ($user !== null)
{
// user doesn't exist
}

Argument 1 passed t be an instance of Illuminate\Http\Request, array given

Why am I getting the following error?
Argument 1 passed to App\Http\Controllers\Controller::validate() must be an instance
of Illuminate\Http\Request, array given, called in
app/Http/Controllers/Admin/Auth/AuthController.php on line 72 and defined
Functions:
protected function loginValidation($request)
{
$rules = array(
'fname' => 'required|max:255',
'lname' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
);
$this->validate( $request , $rules);
}
protected function getLoginCredentials(Request $request)
{
$validator = $this->loginValidation(Request::all());
var_dump($validator); die();
if($validator->passes())
{
return[
'email' => Request::input('email'),
'password' => Request::input('password'),
'type' => 1
];
return true;
}else{
return redirect()->back()->withErrors();
}
}
Updated Code:
public function validate($request, $rules)
{
$rules = array(
'fname' => 'required|max:255',
'lname' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
);
$this->validate( $request , $rules);
}
protected function getLoginCredentials(Request $request)
{
$validator = $this->validate($request, $rules);
if($validator->passes())
{
return[
'email' => Request::input('email'),
'password' => Request::input('password'),
'type' => 1
];
return true;
}else{
return redirect()->back()->withErrors();
}
}
Error:
Declaration of App\Http\Controllers\Admin\Auth\AuthController::validate() should be compatible with App\Http\Controllers\Controller::validate(Illuminate\Http\Request $request, array $rules, array $messages = Array, array $customAttributes = Array)
Change to
$validator = $this->loginValidation($request);
With this you pass an instance of Request to the validate function
you are passing an array to the first argument of the validate function which i guess should be an instance of Request
$this->validate( $request , $rules);
Updated
protected function loginValidation($request)
{
$rules = array(
'fname' => 'required|max:255',
'lname' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
);
$this->validate( $request , $rules);
}
protected function getLoginCredentials(Request $request)
{
$validator = $this->loginValidation($request);
var_dump($validator); die();
if($validator->passes())
{
return[
'email' => Request::input('email'),
'password' => Request::input('password'),
'type' => 1
];
return true;
}else{
return redirect()->back()->withErrors();
}
}

Call to a member function passes() on null

I do have a feeling that I need to use Auth:: or something here to link to passes. Am I correct
Issue Line
if($validator->passes())
`
getLoginCredentials
protected function getLoginCredentials(Request $request)
{
$validator = $this->loginValidation($request);
if($validator->passes())
{
return[
'email' => Request::input('email'),
'password' => Request::input('password'),
'type' => 1
];
}else{
return redirect()->back()->withErrors();
}
}
loginValidation
protected function loginValidation($request)
{
$rules = array(
'email' => 'required|email',
'password' => 'required',
);
$this->validate( $request , $rules);
}
I think the actual problem is in the loginValidation method that should return an object. Please, see my code below. I've also changed getLoginCredentials a bit as Request shouldn't be called statically.
protected function getLoginCredentials(Request $request)
{
$validator = $this->loginValidation($request);
if ($validator->passes()) {
return [
'email' => $request->input('email'),
'password' => $request->input('password'),
'type' => 1
];
} else {
return redirect()->back()->withErrors();
}
}
loginValidation
protected function loginValidation(Request $request)
{
$rules = [
'email' => 'required|email',
'password' => 'required',
];
return Validator::make($request->all(), $rules);
}

Auth::attempt fails with PHPUnit TESTING

I have a really strange behavior and I do not see where it could come from. I built an authentication system with Laravel documentation. When I save a User and try to login from the application, it works fine. However when I do the same thing in my AuthControllerTest, the Auth::attempt fails.
AuthControllerTest.php
<?php
use tests\helpers\Factory;
class AuthControllerTest extends ApiTester
{
use Factory;
public function setUp()
{
parent::setUp();
Artisan::call('migrate');
Route::enableFilters();
Session::start();
}
/*
This test fails
I have a 401 instead of a 200 HTTP response code
*/
/** #test */
public function it_should_log_in_user()
{
User::create([
'email' => 'testing#testing.com',
'password' => 'testing'
]);
$credentials = [
'email' => 'testing#testing.com',
'password' => 'testing'
];
//dd(User::count() // I have 1 record
$this->getJson('login', 'POST', $credentials);
$this->assertResponseOk();
}
/** #test */
public function it_should_throws_exception_if_login_fails()
{
User::create([
'email' => 'testing#testing.com',
'password' => 'testing'
]);
$this->getJson('login', 'POST', [
'email' => 'testing#testing.com',
'password' => 'test'
]);
$this->assertResponseStatus(401);
}
/** #test */
public function it_should_log_out_user()
{
$user = User::create([
'email' => 'testing#testing.com',
'password' => 'password'
]);
$this->be($user);
$this->getJson('logout', 'POST');
$this->assertResponseStatus(204);
}
/**
* Generate Alert mock
* #return array
*/
protected function getStub()
{
return [
];
}
}
AuthController.php
<?php
use Arato\Transformers\UserTransformer;
use controllers\ApiController;
class AuthController extends ApiController
{
protected $userTransformer;
function __construct(UserTransformer $userTransformer)
{
$this->userTransformer = $userTransformer;
}
public function login()
{
$rules = [
'email' => ['required', 'email'],
'password' => ['required', 'alphaNum']
];
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return $this->respondUnauthorized();
}
$userData = [
'email' => Input::get('email'),
'password' => Input::get('password')
];
if (Auth::attempt($userData)) {
return $this->respond([
'data' => $this->userTransformer->transform(Auth::user())
]);
} else {
return $this->respondUnauthorized();
}
}
public function logout()
{
Auth::logout();
return $this->respondNoContent();
}
}
Thank you
Remember that the password is encrypted, so you need to get the password directly from the User instance, like:
$user = User::create([
'email' => 'testing#testing.com',
'password' => Hash::make('testing')
]);
$credentials = [
'email' => $user->email
'password' => $user->password
];

BadMethodCallException Method [ register] does not exist

I'm trying to get my registration page to show, the controller logic seems ok but I keep getting this:
BadMethodCallException
Method [ register] does not exist.
here is my controller logic:
<?php
class UserController extends BaseController {
public function register()
{
if(Sentry::check()){
return Redirect::to('myaccount');
}
return View::make("user.register")->with("title", "Avenue - Register")->with("page_title", "Register");
}
public function postRegister()
{
$rules = array(
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|confirmed',
'password_confirmation' => 'required'
);
$input = Input::get();
$validation = Validator::make($input, $rules);
if ($validation->fails()) {
return Redirect::to('register')->with_input()->with_errors($validation);
}
$user = Sentry::createUser(array(
'first_name' => Input::get('first_name'),
'last_name' => Input::get('last_name'),
'email' => Input::get('email'),
'password' => Input::get('password'),
'metadata' => array(
'phone' => Input::get('phone'),
'date-of-birth' => Input::get('date-of-birth'),
'nationality' => Input::get('nationality'),
'gender' => Input::get('gender'),
'category' => Input::get('category'),
),
));
Mail::send('emails.welcome', $data, function($message)
{
$message->to(Input::get('email'))->subject('Welcome to Avenue254!');
});
}
public function getLogin()
{
if(Sentry::check()){
return Redirect::to('myaccount');
}
return View::make("user.login")->with("title","Avenue254 - Login")->with("page_title","Login");
}
public function postLogin()
{
$rules = array(
'email' => 'required|email',
'password' => 'required',
);
$input = Input::get();
$validation = Validator::make($input, $rules);
if ($validation->fails())
{
return Redirect::to_route('login')->with_errors($validation->errors)->with_input();
}
$credentials = array( 'email'=> Input::get('email'), 'password'=>Input::get('password') );
if (Sentry::authenticate($credentials, false))
{
return Redirect::to('myaccount');
}
else
{
return Redirect::to('login')->with("error", "There is problem with login please try again");
}
}
public function getMyaccount()
{
if(!Sentry::check()){
return Redirect::to('login')->with("error", "Please login to access your account");
}
$user = Sentry::getUser();
return View::make("users.myaccount")->with("title","Avenue254" - "My Account")->with("page_title","My Account")->with('user',$user);
}
public function postProfile()
{
$user = Sentry::getUser();
$rules = array(
'email' => 'required|email|unique:users,email,'.$user['id'],
);
$input = Input::get();
$validation = Validator::make($input, $rules);
if ($validation->fails()) {
return Redirect::to('myaccount')->with_input()->with_errors($validation);
}
$user_data = array(
'email' => Input::get('email'),
'metadata' => array(
'first_name' => Input::get('first_name'),
'last_name' => Input::get('last_name'),
'phone' => Input::get('phone'),
'date-of-birth' => Input::get('date-of-birth'),
),
);
if ($user->update($user_data))
{
return Redirect::to('myaccount')->with('success', 'Your information has been updated successfully.');
}
else
{
return Redirect::to('myaccount')->with('error', 'Something went wrong!.');
}
}
}
and my routes:
Route::get('register', array('as' => 'getregister', 'uses' => 'UserController#
register'));
Route::get('myaccount', array('as' => 'myaccount', 'uses' => 'UserController#
myaccount'));
Route::post('register', array('as' => 'postregister', 'uses' =>
'UserController#postRegister'));
Whenever I try to route to register I get this error, I have tried everything unsuccessfully. What could I be doing wrong?

Categories