Laravel manual auth - Never works - php

I am trying to make Auth for an API Rest manually, but the response for Auth::attempt is always false.
Route
Route::group(["prefix"=>"api"], function(){
Route::post('/login', [
'as' => 'checkLogin',
'uses' => 'LoginCtrl#checkLogin'
]);
});
Controller
class LoginCtrl extends Controller
{
public function checkLogin(Request $request){
$input = $request->all();
if(Auth::attempt(['username' => $input['user'], 'password' => $input['password']])){
$data = ["response"=>true,"access_token"=>"test"];
}else{
$data = ["response"=>false,"access_token"=>"none"];
}
return response()->json($data);
}
}
I have userd Hash::make to encrypt the password on the user creation.
My model is:
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
protected $table = "usuarios";
protected $username = 'username';
protected $fillable = [
'name', 'username', 'password'
];
protected $hidden = [
//'password', 'remember_token',
];
public $timestamps = false;
public function access_token(){
return $this->hasOne('App\AccessToken');
}
}
What am I doing wrong?
EDIT
$user = new User();
$user->username = "myFreshUsername";
$user->password = Hash::make('userPwd');
$user->save();
Thats my user creation. If this helps I didn't launch `php artisan make:auth', may this order be necessary?

of course it always false because you did not use correct way to get the json in your request using laravel
the correct way is
$input = $request->json()->all();
not
$input = $request->all();
so your controller would be like this
class LoginCtrl extends Controller
{
public function checkLogin(Request $request){
$input = $request->json()->all();
if(Auth::attempt(['username' => $input['user'], 'password' => $input['password']])){
$data = ["response"=>true,"access_token"=>"test"];
}else{
$data = ["response"=>false,"access_token"=>"none"];
}
return response()->json($data);
}
}

Related

I am getting the error: Indirect modification of overloaded property App\User::$profile has no effect

I have a relationship between two models in my application: Users and Profile. The User model has a hasOne relationship with the profile model. When I try to run an update method from my Profile Controller I get the error: Indirect modification of overloaded property App\User::$profile has no effect.
This is my update method:
public function update(Request $request, $id)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email',
'facebook' => 'required|url',
'youtube' => 'required|url'
]);
$user = Auth::user();
//dd($user);
if($request->hasFile('avatar'))
{
$avatar = $request->avatar;
$avatar_new_name = time() . $avatar->getClientOriginalName();
$avatar->move('uploads/avatars', $avatar_new_name);
$user->profile->avatar = 'uploads/avatars/' . $avatar_new_name ;
$user->profile->save();
}
$user->name = $request->name;
$user->email = $request->email;
$user->profile->facebook = $request->facebook;
$user->profile->youtube = $request->youtube;
$user->profile->about = $request->about;
$user->save();
$user->profile->save();
if($request->has('password'))
{
$user->password = bcrypt($request->password);
$user->save();
}
Session::flash('success', 'Account profile updated.');
return back();
}
This is my User.php file:
<?php
namespace App;
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', 'admin'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function profile()
{
return $this->hasOne('App\Profile');
}
public function posts()
{
return $this->hasMany('App\Post');
}
}
This is my Profile.php file:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
protected $fillable = [
'user_id', 'avatar', 'youtube', 'facebook', 'about'
];
}
How do I fix this error?
You need to create a new Profile instance, save it to the database and then call the following method to setup the relationship. At present you are trying to assign properties to something which doesn't exist.
Do the following
$profile = new Profile();
$profile->myvar = 'value';
$profile->save();
Then associate (one of these will work but I haven't tested the code)
$user->profile()->save($profile);
$user->profile()->associate($profile);
You have to make a relational object of $user. You may try with this.
$user = User::where('id', Auth::user()->id)->with('profile')->first();
Instead of $user = Auth::user();
Please replace your update function with this and try again
public function update(Request $request, $id)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email',
'facebook' => 'required|url',
'youtube' => 'required|url'
]);
$user = User::where('id', Auth::user()->id)->first();
if($user) {
$user->name = $request->name;
$user->email = $request->email;
if($request->has('password'))
{
$user->password = bcrypt($request->password);
}
}
if( $user->save() ) {
$profile = Profile::where('user_id', Auth::user()->id)->first();
$profile->facebook = $request->facebook;
$profile->youtube = $request->youtube;
$profile->about = $request->about;
if($request->hasFile('avatar'))
{
$avatar = $request->avatar;
$avatar_new_name = time() . $avatar->getClientOriginalName();
$avatar->move('uploads/avatars', $avatar_new_name);
$profile->avatar = 'uploads/avatars/' . $avatar_new_name ;
}
}
if($profile->save()) {
Session::flash('success', 'Account profile updated.');
} else {
Session::flash('error', 'Failed to update.');
}
return back();
}

User Authentication in Lumen

I'm trying to enable basic user authentication username, and password into my Lumen application.
In app.php file, the following has been uncommented as explained in https://lumen.laravel.com/docs/5.4/authentication
$app->withFacades();
$app->routeMiddleware([
'auth' => App\Http\Middleware\Authenticate::class,
]);
$app->register(App\Providers\AuthServiceProvider::class);
My Route looks like this:
$app->post('auth/register', ['uses' => 'Auth\AuthController#postRegister']);
My Controller looks like this:
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Repositories\UserRepository;
use Illuminate\Http\Request;
use Auth;
use App\User;
class AuthController extends Controller {
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
}
public function postRegister(Request $request, UserRepository $userRepository)
{
$this->validate($request, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
$user = $userRepository->store($request);
Auth::login($user);
return ['result' => 'success'];
}
}
I have been getting a combination of weird and wonderful errors, currently I'm getting:
ReflectionException in BoundMethod.php line 155:
Class App\Repositories\UserRepository does not exist
I've done some extensive google searching, but there doesn't seem to be many documented uses of user auth in Lumen so looking for a pointer as to what I've missed here.
My initial error: I was looking for a method of logging in a user, what I should have been looking for was authentication. Thinking about what I actually needed to achieve I came up with the below functions:
Create user
Delete user
Verify user
With that in mind I ended up with something like the below:
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
//Required to hash the password
use Illuminate\Support\Facades\Hash;
class AuthController extends Controller {
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
}
public function validateRequest(Request $request) {
$rules = [
'email' => 'required|email|unique:users',
'password' => 'required|min:6'
];
$this->validate($request, $rules);
}
//Get the input and create a user
public function store(Request $request) {
$this->validateRequest($request);
$user = User::create([
'email' => $request->get('email'),
'password'=> Hash::make($request->get('password'))
]);
return response()->json(['status' => "success", "user_id" => $user->id], 201);
}
//delete the user
public function destroy($id) {
$user = User::find($id);
if(!$user){
return response()->json(['message' => "The user with {$id} doesn't exist"], 404);
}
$user->delete();
return response()->json(['data' => "The user with with id {$id} has been deleted"], 200);
}
//Authenticate the user
public function verify(Request $request) {
$email = $request->get('email');
$password = $request->get('password');
$user = User::where('email', $email)->first();
if($user && Hash::check($password, $user->password)) {
return response()->json($user, 200);
}
return response()->json(['message' => "User details incorrect"], 404);
}
//Return the user
public function show($id) {
$user = User::find($id);
if(!$user) {
return response()->json(['status' => "invalid", "message" => "The userid {$id} does not exist"], 404);
}
return response()->json(['status' => "success", 'data' => $user], 200);
}
//Update the password
public function update(Request $request, $id) {
$user = User::find($id);
if(!$user){
return response()->json(['message' => "The user with {$id} doesn't exist"], 404);
}
$this->validateRequest($request);
$user->email = $request->get('email');
$user->password = Hash::make($request->get('password'));
$user->save();
return response()->json(['data' => "The user with with id {$user->id} has been updated"], 200);
}
}
I'm not really sure what you want to achieve with UserRepository and Auth.
Lumen is a stateless framework, meaning that Auth::login() never will have any effect. Also, as far as I'm concerned, UserRepository is a Laravel thing. Not a Lumen thing.
Create the user with App\User::create($request->all()) and access it through the Eloquent model. You can enable Eloquent in bootstrap/app.php

Laravel - Override the resetPassword

So I have two tables of users in my database with the name Mahasiswas and Users, and I want to override the resetPassword for Mahasiswas table, because every time I reset the password for the Mahasiswas table, it automatically logged into the Users dashboard.
I put this in my route :
Route::post('password/reset', 'MhsAuth\PasswordController#postMyReset');
And this is my passwordController :
namespace App\Http\Controllers\MhsAuth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
class PasswordController extends Controller
{
use ResetsPasswords;
protected $redirectPath = '/';
protected $getGuard = 'mahasiswa';
public function __construct()
{
$this->middleware('mahasiswa');
}
public function postMyReset(Request $request)
{
return $this->resetMe($request);
}
public function resetMe(Request $request)
{
$this->validate($request, [
'token' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed|min:6',
]);
$credentials = $request->only(
'email', 'password', 'password_confirmation', 'token'
);
$broker = $this->getBroker();
$response = Password::broker($broker)->reset($credentials, function ($user, $password) {
$this->resetMyPassword($user, $password);
});
switch ($response) {
case Password::PASSWORD_RESET:
return $this->getResetSuccessResponse($response);
default:
return $this->getResetFailureResponse($request, $response);
}
}
protected function resetMyPassword($user, $password)
{
$user->password = bcrypt($password);
$user->save();
//Auth::guard($this->getGuard())->login($user);
}
}
The problem is after reset the password for Mahasiswas table, it's perform auto login to Users Dashboard, it should be in Mahasiswas Dashboard, but I just want to disable the autologin and my passwordController doesn't work as I wanted. Thanks

laravel 5 multi form data save in database

I use two different forms and connected to database it's working fine. But when I do an insert values stored as two different rows in database.
When do we have to use seeder? Is what I wrote coding proper laravel 5?
Controller file
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Requests\ListFormRequest;
use App\Http\Requests\LoginFormRequest;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;
use Response;
use App\Test;
class testController extends Controller {
public function test()
{
return view('test',array('title' => 'test'));
}
public function lockTest(ListFormRequest $test)
{ $user = new Test();
$user->firstname = Input::get('firstname');
$user->password = Input::get('password');
$user->email = Input::get('email');
$user->save();
return view('login');
}
public function login()
{
return view('login',array('title' => 'login'));
}
public function userLogin(LoginFormRequest $test1)
{
$user = new Test();
$user->lastname = Input::get('lastname');
$user->middlename = Input::get('middlename');
$user->save();
return Response::make('Sucessfully Registered!');
}
}
Route file
<?php
Route::get('/', 'testController#test');
Route::post('login', 'testController#lockTest');
Route::get('login', 'testController#login');
Route::post('userLogin', 'testController#userLogin');
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
Seeder file
<?php
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use App\Test;
class TestsSeeder extends Seeder {
public function run() {
DB::table('users')->truncate();
$qwerty = Input::all();
foreach($qwerty as $qwertySingle) {
Test::create([
'firstname' => $qwertySingle->firstname,
'password' => $qwertySingle->password,
'email' => $qwertySingle->email,
'lastname' => $qwertySingle->lastname,
'middlename' => $qwertySingle->middlename,
]);
}
DB::table('tests')->insert($qwerty);
}
}
Model file
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
use App\DB;
class Test extends Model {
protected $guarded = array();
protected $table = 'tests';
protected $fillable = ['firstname', 'password', 'email', 'lastname', 'middlename'];
}
The seeder is used when you want to populate your database with fake data, so you can test the waters of your app with thousands of dummy records.
The run method from your seeder should be something like the following, to give you some ideas:
Test::truncate();
Test::unguard();
$password = Hash::make('secret');
foreach (range(1, mt_rand(10, 20)) as $index) {
Test::create([
'firstname' => "first name {$index}",
'password' => $password,
'email' => "myemail{$index}#mydomain.com",
'lastname' => "last name {$index}",
'middlename' => "middlename {$index}",
]);
}

How to create new user in Laravel?

I created the model:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class ClientModel extends Eloquent implements UserInterface, RemindableInterface {
protected $connection = 'local_db';
protected $table = 'administrators';
protected $fillable = ['user_id'];
public function getAuthIdentifier()
{
return $this->username;
}
public function getAuthPassword()
{
return $this->password;
}
public function getRememberToken()
{
return $this->remember_token;
}
public function setRememberToken($value)
{
$this->remember_token = $value;
}
public function getRememberTokenName()
{
return 'remember_token';
}
public function getReminderEmail()
{
return $this->email;
}
}
When I try to use it like this:
ClientModel::create(array(
'username' => 'first_user',
'password' => Hash::make('123456'),
'email' => 'my#email.com'
));
It creates empty entry in DB...
I think you make it too complicated. There is no need to make it this way. By default you have User model created and you should be able simple to create user this way:
$user = new User();
$user->username = 'something';
$user->password = Hash::make('userpassword');
$user->email = 'useremail#something.com';
$user->save();
Maybe you wanted to achieve something more but I don't understand what you use so many methods here if you don't modify input or output here.
You are using create method (Mass Assignment) so it's not working because you have this:
// Only user_id is allowed to insert by create method
protected $fillable = ['user_id'];
Put this in your model instead of $fillable:
// Allow any field to be inserted
protected $guarded = [];
Also you may use the alternative:
protected $fillable = ['username', 'password', 'email'];
Read more about Mass Assignment on Laravel website. While this may solve the issue but be aware of it. You may use this approach instead:
$user = new User;
$user->username = 'jhondoe';
// Set other fields ...
$user->save();
Nowadays way :
User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
or even:
$arrLcl = [];
$arrLcl['name'] = $data['name'];
$arrLcl['email'] = $data['email'];
$arrLcl['password'] = $data['password'];
User::create($arrLcl);

Categories