HTTP basic auth is not working - php

I am creating an api with Laravel 4.1. For authentication I wanted to use Laravel Basic auth. Every time I fill the input fields, it doesn't let me in. It just clear the input and popup the form again. I am not sure what I am doing wrong. I am not using migration for creating users table. This is just a basic route:
Route::get('admin', function()
{
return "authenticated";
})->before('auth.basic');
This is my filter:
Route::filter('auth.basic', function()
{
return Auth::basic('username');
});
This is my User Model:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'pivot');
/**
* #var array
*/
protected $guarded = array('id', 'created_at', 'updated_at', 'is_admin');
protected $fillable = array('username', 'password', 'name_first', 'name_middle', 'name_last', 'email', 'address', 'city', 'state', 'zip_code', 'country', 'phone', 'title', 'profile_image', 'status');
/**
* #var array
*/
public static $rules = array();
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return $this->email;
}
}

Why don't you try
Route::get('admin', array( 'before' => 'auth.basic' ,function()
{
return "authenticated";
}));
Your passwords need to be hashed in your database.

Related

Middleware for 2 step authorization

I am beginner in Laravel. I make my application in Laravel 8 and spatie/laravel-permission.
Actually i have persimmons: individual|company
Route::group(['prefix' => '', 'middleware' => ['role:individual|company']], function () {
Route::get('/cms-historia-przesylek-nadanych', 'Account\SendPackageController#index')->name('cms-history-send-packages')->middleware('company');
Route::get('/cms-przesyleka-nadana/{id}', 'Account\SendPackageController#show')->name('cms-view-send-package')->middleware('company');
Route::get('/cms-przesyleka-nadana-zwrot/{id}', 'Account\SendPackageController#returnBackPackage')->name('cms-view-send-package-return')->middleware('company');
Route::post('/cms-przesyleka-nadana-zwrot/zamow-paczke/{id}', 'Account\SendPackageController#orderPackage')->name('cms-view-send-package-return-order')->middleware('company');
Route::get('/cms-pobierz-przesyleke-nadana/{id}', 'Account\SendPackageController#getPdf')->name('cms-get-send-package')->middleware('company');
Route::get('/cms-historia-przesylek-odebranych', 'Account\ReceivedPackageController#index')->name('cms-history-received-packages')->middleware('company');
Route::get('/cms-przesyleka-odebrana/{id}', 'Account\ReceivedPackageController#show')->name('cms-view-received-package')->middleware('company');
Route::get('/cms-pobierz-przesyleke-odebrana/{id}', 'Account\ReceivedPackageController#getPdf')->name('cms-get-received-package')->middleware('company');
Route::get('/cms-dwu-stopniowa-weryfikacja', 'Account\TwoStepVerificationController#index')->name('cms-two-step-verification');
});
And this is my USER.php:
<?php
namespace App\Models;
use App\Traits\ScopeActiveTrait;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;
class User extends Authenticatable
{
use Notifiable,
ScopeActiveTrait,
HasRoles,
SoftDeletes,
HasSlug;
/**
* Get the options for generating the slug.
*/
public function getSlugOptions() : SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom(['company_name', 'id'])
->slugsShouldBeNoLongerThan(250)
->saveSlugsTo('slug');
}
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'email',
'password',
'enable',
'company_id',
'surname',
'email_verified_at',
'description',
'is_company',
'package1',
'package2',
'package3',
'sms',
'phone',
'street',
'building_number',
'city',
'postal_code',
'revicer_default_inpost_parcel',
'shipping_default_inpost_parcel',
'file_name',
'nip',
'company_name',
'remember_token',
'subdomain',
'lng',
'lat',
'show_map',
'ofert_type',
'discount_value1',
'discount_value2',
'discount_value3',
'discount_value4',
'discount_value5',
'is_two_step_authorization',
'two_step_authorization_token',
];
protected $dates = [
'created_at',
'updated_at',
'deleted_at'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
'company_id' => 'integer',
'enable'=>'boolean',
'isCompany'=>'boolean',
'show_map'=>'boolean',
];
/* User Login history */
public function loginHistory()
{
return $this->hasMany('App\Models\UserLoginHistory');
}
/* User images */
public function images()
{
return $this->hasManyThrough('App\Models\UploadFile', 'App\Models\User', 'id', 'file_id');
}
public function mainImage()
{
return $this->images()->where('file_type', 'DZ_ADMIN');
}
/* Admin Avatar */
public function getAvatar()
{
return $this->images()->where('file_type', 'DZ_ADMIN')->orderBy('order', 'ASC')->first();
}
public function isCompany(): bool
{
return $this->is_company == 1;
}
}
When I have is_two_step_authorization = 1.- then I need run new middleware for 2 step authorization,.
How can I make it?
is_two_step_authorization = 0 - 2 factorial authorization is disabled. is_two_step_authorization = 1 - Two-factor authentication is enabled.
I think use this tutorial: https://www.itsolutionstuff.com/post/laravel-8-two-factor-authentication-with-smsexample.html but this middleware work always for route with middleware 2fa.
In my case, selected routs may require 2-step security (if the user has chosen so in the settings) or not (the user has disabled security).
How can I change the code from the tutorial to get it?
You need to update the middleware from the tutorial in order to only redirect to 2fa index if the logged user has is_two_step_authorization on. Of course you may need other checks, or to ensure that the user is logged in and so on, but just for this specific usecase, this line of code should do the trick.
app/Http/Middleware/Check2FA.php
public function handle(Request $request, Closure $next)
{
if ($request->user()->is_two_step_authorization && !Session::has('user_2fa')) {
return redirect()->route('2fa.index');
}
return $next($request);
}
Tweak the code from that example...
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Session;
class Check2FA
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle(Request $request, Closure $next)
{
if ($request->user()->is_two_step_authorization == 1) {
return redirect()->route('2fa.index');
}
return $next($request);
}
If the requested user has the property of is_two_step_authorization with value one only then it will redirect to the 2fa page, otherwise not

How to check if a user's "email" exists in database in api.php file in Laravel? And get response in React Native app

I have a mobile app where a user enters their email address and phone number, I am trying to check whether the email already exists in the database by making an axios post request to my laravel application in the api file where I have created a '/check-email'/ route but all I'm receiving is a promise rejection error.
This is my post route in api.php:
// Check Email
Route::post('/check-email', function (Request $request) {
$request->validate([
'email' => 'required|email',
]);
$user = User::where('email', $request->email)->first();
if ($user === null) {
return response()->json(['status' => 'success']);
}
});
And my User model:
class User extends Authenticatable
{
use HasApiTokens;
use HasFactory;
use HasProfilePhoto;
use Notifiable;
use TwoFactorAuthenticatable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'email',
'password',
'ttlock_username',
'ttlock_password',
'push_token',
'os'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
'two_factor_recovery_codes',
'two_factor_secret',
'ttlock_username',
'ttlock_password',
'push_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* The accessors to append to the model's array form.
*
* #var array
*/
protected $appends = [
'profile_photo_url',
];
public function bookings()
{
return $this->hasMany(Booking::class);
}
public function firstPromoFree()
{
return $this->hasOne(UsedPromoCode::class)->where('promo_code', 'PODONUS');
}
public function devices()
{
return $this->hasMany(PushNotification::class, 'user_id');
}
}
And my React Native function which calls the post route, passing in the email state:
function checkEmailUser() {
axios
.post(BASE_PATH + '/api/check-email', {
email: email,
})
.then(response => {
console.log(response.data);
if (response.data.success) {
setEmailChecked(true);
console.log('Email is available');
} else {
setEmailChecked(false);
Alert.alert('A user with this email already exists');
}
});
}
I'm sure this is pretty close to being right but can't quite figure it out. Any help would be greatly appreciated!!

Laravel JWT - Getting Unauthenticated with the valid login token

I am working on a simple JWT authentication system. User will get a token from login and when he passes the token, the user information will be given as the response. I have followed the procedure from: https://jwt-auth.readthedocs.io/en/develop/laravel-installation/ .
When I pass email and password to the login method I am able to get a token. But when I pass the token (to the me function) it returns 'Unauthorized'.
User Model:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
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 [];
}
}
```````
api.php (Route)
`````
Route::group([
'middleware' => 'api',
'prefix' => 'auth'
], function ($router) {
Route::post('login', 'AuthController#login');
Route::post('logout', 'AuthController#logout');
Route::post('refresh', 'AuthController#refresh');
Route::post('me', 'AuthController#me');
});
````
AuthController
```
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use App\User;
class AuthController extends Controller
{
/**
* Create a new AuthController instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login']]);
}
/**
* Get a JWT via given credentials.
*
* #return \Illuminate\Http\JsonResponse
*/
public function login()
{
$credentials = request(['email', 'password']);
if (! $token = auth()->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
//return response()->json(User::all());
}
/**
* Get the authenticated User.
*
* #return \Illuminate\Http\JsonResponse
*/
public function me()
{
return response()->json(auth()->user());
//return response()->json("hellllo");
}
/**
* Log the user out (Invalidate the token).
*
* #return \Illuminate\Http\JsonResponse
*/
public function logout()
{
auth()->logout();
return response()->json(['message' => 'Successfully logged out']);
}
/**
* Refresh a token.
*
* #return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
return $this->respondWithToken(auth()->refresh());
}
/**
* Get the token array structure.
*
* #param string $token
*
* #return \Illuminate\Http\JsonResponse
*/
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60
]);
}
}
```

Get user avatar attribute from post relation

In Laravel 5.8, I have a custom attribute to recover the avatar via Gravatar. This is an attribute in the User model.
/**
* #return string
*/
public function getAvatarAttribute()
{
return sprintf('%s%s%s', 'https://secure.gravatar.com/avatar/', md5(strtolower(trim($this->email))), '?s=200');
}
I have a belongsTo/hasMany relationship in the Post/User model.
Post model:
/**
* #return BelongsTo
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
User model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* #var string
*/
protected $table = 'users';
/**
* #var array
*/
protected $fillable = [
'username',
'email',
'password',
'api_token',
];
/**
* #var array
*/
protected $hidden = [
'password',
'remember_token',
'api_token',
];
/**
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
'admin' => 'boolean',
];
/**
* #return string
*/
public function getRouteKeyName()
{
return 'username';
}
/**
* #return HasMany
*/
public function posts(): HasMany
{
return $this->hasMany(Post::class);
}
/**
* #return string
*/
public function getAvatarAttribute()
{
return sprintf('%s%s%s', 'https://secure.gravatar.com/avatar/', md5(strtolower(trim($this->email))), '?s=200');
}
}
I pass the post by the URL of the route:
Route::get('post/{post}', 'BlogController#post');
I would like to retrieve the avatar attribute via post. Only, I recover a null. And I do not understand where it comes from.
public function post(Post $post)
{
dd($post->user); // user model without appends attributes
dd($post->user->avatar); // null
}
I found the problem, I used User from Illuminate (Illuminate\Foundation\Auth\User) instead my User model.

User model error after Laravel update (Class User contains 3 abstract method)

After I update my laravel using composer update, I got this
"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException",
"message":"Class User contains 3 abstract methods and must therefore be declared abstract or implement the remaining methods (Illuminate\\Auth\\UserInterface::setRememberToken, Illuminate\\Auth\\UserInterface::getRememberTokenName, Illuminate\\Auth\\Reminders\\RemindableInterface::getReminderEmail)",
"file":"D:\app\\models\\User.php",
"line":54
error when authenticating.
This error happened because of the latest commit.
You can check the upgrade documentation here, to fix this issue.
As stated, add the following to your User.php model class:
public function getRememberToken()
{
return $this->remember_token;
}
public function setRememberToken($value)
{
$this->remember_token = $value;
}
public function getRememberTokenName()
{
return 'remember_token';
}
This is what worked for me by adding the below to app/User
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 [];
}
Example app/User
<?php
namespace App;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable implements JWTSubject
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* Get the identifier that will be stored in the subject claim of the JWT.
*
* #return mixed
*/
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 [];
}
}

Categories