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
Related
This is my web.php code
Route::get('/register',[AuthController::class, 'load_register']);
Route::post('/register',[AuthController::class, 'register']);
Route::get('/',[AuthController::class, 'login']);
Route::get('/login',[AuthController::class, 'login']);
Route::post('/login',[AuthController::class, 'userLogin'])->name('userLogin');
Route::get('/logout',[AuthController::class, 'logout'])->name('logout');
Route::get('/admin/dashboard',[AuthController::class, 'adminDashboard']);
Route::get('/dashboard',[AuthController::class, 'dashboard']);
this is my AuthController code
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AuthController extends Controller
{
function load_register(){
return view('form');
}
function register(Request $request){
// echo 'yes';
// dd();
$request->validate([
'name' => 'required|min:2',
'email' => 'required|email|unique:users',
'password' => 'required|min:8',
'password_confirmation' => 'required|same:password'
]);
$user = new User();
$user->name = $request['name'];
$user->email = $request['email'];
$user->password = $request['password'];
$user->save();
return redirect()->back();
}
public function login(){
return view('login');
}
public function userLogin(Request $request){
$credential = $request->only('email','password');
if(Auth::attempt($credential)){
if(Auth::user()->is_admin == 1){
return redirect('admin/dashboard');
}
else{
return redirect('dashboard');
}
}
else{
echo 'Invalid';
}
}
public function adminDashboard(){
return view('admin.dashboard');
}
public function dashboard(){
return view('student.dashboard');
}
}
I have created their view pages respectively. I want to redirect them.
is_admin is a boolean property I have created in users migration and it is by default 0 and for admin I have changed it to 1 in order to identify it is admin credentials or not.
but when I try to log in as an admin or user it always echo Invalid.
Please if there is anyone who can guide me.
Thanks.
I upgraded:
"tymon/jwt-auth": "0.5.*",
from a very old version, and it seems like the API has changed. I managed to fix the login, using:
public function login(Request $request)
{
$credentials = $request->only(['username', 'password']);
$validator = Validator::make($credentials, [
'username' => 'required',
'password' => 'required',
]);
if($validator->fails()) {
throw new ValidationHttpException($validator->errors()->all());
}
if (!$token = auth()->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
$user = auth()->user();
$user->ip_address = $request->ip();
if ($request->device_token)
$user->device_token = $request->device_token;
$user->save();
$data['token'] = $token;
$data['email'] = $user->email;
return response()->json($data);
}
So my login work, but all API's that required the token - fail now.
Example of API that fail:
class UserController extends Controller
{
public function __construct()
{
// $this->middleware('auth:api', ['except' => ['login']]);
}
public function enterWorld(Request $request)
{
$token = $request->input('token');
$user = JWTAuth::toUser($token);
return $user;
}
Any idea how to convert the token from the request to the user with the new API?
I couldn't find any docs about it.
I tried:
return response()->json(auth()->user());
but in this API it return empty array. only in login it works.
Try the following:
$user = JWTAuth::setRequest($request)->user();
You may also explicitly set the guard when using the following syntax:
// pass the guard in to the auth() helper.
return response()->json(auth('jwt')->user());
I am new in laravel. I have created login and signup form using auth command.
I have activated the email verification for login. Also I have created the social login for Gmail,Fb etc. using the socialite based on below link.
https://www.tutsmake.com/laravel-6-google-login-tutorial-with-socialite-demo-example/
Now I don't require email verification for those user who login through social but mandatory for manual signup.
My Homecontroller
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware(['auth', 'verified']);
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
return view('frontend.index');
}
public function seedr()
{
$users=DB::table('users')->get();
return view('backend.seedr',['users'=>$users]);
}
}
My SocialController
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator,Redirect,Response,File;
use Socialite;
use App\User;
class SocialController extends Controller
{
public function redirect($provider)
{
//echo $provider;die;
return Socialite::driver($provider)->redirect();
}
public function callback($provider)
{
$getInfo = Socialite::driver($provider)->user();
$user = $this->createUser($getInfo,$provider);
auth()->login($user);
return redirect()->to('/home');
}
function createUser($getInfo,$provider){
$user = User::where('provider_id', $getInfo->id)->first();
if (!$user) {
//$mytime = Carbon::now();
$currenttime=date("Y-m-d h:i:s a", time());
$user = User::create([
'name' => $getInfo->name,
'email' => $getInfo->email,
'provider' => $provider,
'provider_id' => $getInfo->id,
]);
//die;
}
return $user;
}
}
You probably have a column email_verified_at that stores the date when the email address was verified, by default it's null which means the user is not verified. In your SocialController#createUser set it to the current date:
$user = User::create([
'name' => $getInfo->name,
'email' => $getInfo->email,
'provider' => $provider,
'provider_id' => $getInfo->id,
'email_verified_at' => now()
]);
You can use markEmailAsVerified()
$user = User::create([
'name' => $getInfo->name,
'email' => $getInfo->email,
'provider' => $provider,
'provider_id' => $getInfo->id,
]);
$user->markEmailAsVerified();
Do NOT use it as the #Raftel mentioned! When you add email_verified_at to your $fillable variable, then hacker could break your whole Email Verification by sending a hidden input (e.g. <input type="hidden" name="email_verified_at" value="<?php echo now() ?>"/ >...
You can use undocumented method on eloquent models called forceFill() instead: https://www.mike-griffiths.co.uk/blog/laravels-forcefill-and-forcecreate/
AuthController.php code
<?php
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use JWTAuth;
use App\User;
use JWTAuthException;
class AuthController extends Controller
{
private $user;
public function __construct(User $user)
{
$this->user = $user;
}
public function register(Request $request)
{
$this->validate($request, [
'email'=> 'required|email|unique:users',
'first_name'=> 'required|max:120',
'password' => 'required|min:4'
]);
$user = $this->user->create([
'name' => $request->get('name'),
'email' => $request->get('email'),
'password' => bcrypt($request->get('password'))
]);
$user->save();
if(!$user){
return response()->json(['status'=>false,'message'=>'User not created']);
}
else {
return response()->json(['status'=>true,'message'=>'User created successfully','data'=>$user]);
}
}
public function login(Request $request)
{
$this->validate($request, [
'email'=> 'required',
'password'=> 'required'
]);
$credentials = $request->only('email','password');
$token = null;
try {
$token = $this->jwtauth->attepmt($credentials);
if(!$token)
{
return response()->json(['invalid email or password'], 422);
}
}
catch (JWTAuthException $ex)
{
return response()->json(['failed to create token'], 500);
}
return response()->json(compact('token'));
}
public function getAuthUser(Request $request){
$user = JWTAuth::toUser($request->token);
return response()->json(['result' => $user]);
}
}
api.php routes
Route::post('register', 'api\AuthController#register');
Route::post('login', 'api\AuthController#login');
Route::group(['middleware' => 'jwt.auth'], function () {
Route::get('user', 'api\AuthController#getAuthUser');
});
*Im sure that there is something little wrong im my code because the "getAuthUser" method is working and cheking if there is a token or no . I'll be thankful if anyone helped me *
So, which one of the methods is giving you error?
Since you did specify that "getAuthUser" was working fine; And because of the kind of error you're getting I'm going to assume you're talking "register" and "login".
Anyway, that kind of error happens when you try to access a route with the incorrect kind of request. You must use a "POST" request, instead of a "GET" if you are trying to access /register and /login
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