I added registration, and I don't want to using laravels hash but mysql Hash (because I want existing users to still be able to connect).
So i do it step by step and for now I just try to register and then login without any hashing. The credentials are correct in my table but I get
"message":"The given data was invalid.","errors":{"email":["These credentials do not match our records."]}
I tried setting it in LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
public function username()
{
return 'email';
}
public function password()
{
return 'email';
}
public function setPasswordAttribute($password){
$this->attributes['password'] = $password;
}
public function Login(Request $request)
{
if(Auth::attempt(['email' => $request->email, 'pwd' => $request->password, 'password' => $request->password])){
$user = Auth::user();
$username = $user->nom;
return response()->json([
'status' => 'success',
'user' => $username,
]);
} else {
return response()->json([
'status' => 'error',
'user' => 'Unauthorized Access'
]);
}
}
}
I guess I should overwrite another function, but can't find out which one.
Could you please give me some help?
Altough what you're trying to achieve is considered unsecure, to remove Laravel's hashing for password, you need to add this to your User model :
public function setPasswordAttribute($password){
$this->attributes['password'] = $password;
}
and not in your controller, and be sure to remove the brcypt() methods in your RegisterController
To add your MySQL own hashing methods, update your controller to insert a RAW query while creating a user upon registration
Related
I am facing an issue when trying to login and register a user using Twitter. Google is working except for Twitter. I cant seem to figure it out.
Temporary identifier passed back by server does not match that of stored temporary credentials. Potential man-in-the-middle.
<?php
namespace App\Http\Controllers;
use Exception;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;
class TwitterController extends Controller
{
protected $redirectTo = '/home';
public function redirectToProvider($provider)
{
return Socialite::driver($provider)->redirect();
}
public function handleProviderCallback($provider)
{
$user = Socialite::driver($provider)->user();
$authUser = $this->findOrCreateUser($user, $provider);
Auth::login($authUser, true);
return redirect($this->redirectTo);
}
public function findOrCreateUser($user, $provider)
{
$authUser = User::where('provider_id', $user->id)->first();
if ($authUser) {
return $authUser;
}
return User::create([
'name' => $user->getName(),
'username' => $user->getName(),
'email' => $user->getEmail(),
'provider' => $provider,
'provider_id' => $user->getId()
]);
}
}
We are trying to setup the Facebook social connect on our Laravel application, but it seems like we have an issue on session creation.
Here is the code for the Controller :
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Laravel\Socialite\Facades\Socialite;
use App\Services\SocialAuthService;
class SocialAuthController extends Controller
{
public function redirect()
{
return Socialite::driver('facebook')->redirect();
}
public function callback(SocialAuthService $service)
{
$user = $service->createOrGetUser(Socialite::driver('facebook')->stateless()->user());
auth()->login($user);
return redirect()->intended('/');
}
}
And the code for the service :
<?php
namespace App\Services;
use Laravel\Socialite\Contracts\User as ProviderUser;
use Myproject\Users\User;
use Myproject\Users\SocialLogin;
class SocialAuthService
{
public function createOrGetUser(ProviderUser $providerUser)
{
$account = SocialLogin::where('provider', '=', 'facebook')
->where('provider_user_id', '=', $providerUser->getId())
->first();
if ($account) {
return $account->user;
}
$user = User::where('email', '=', $providerUser->email)->first();
if (!$user) {
$fullname = explode(' ', $providerUser->getName());
$user = User::create([
'email' => $providerUser->getEmail(),
'firstname' => $fullname[0],
'lastname' => $fullname[1],
'password' => md5(rand(1, 9999)),
]);
}
$account = new SocialLogin([
'provider_user_id' => $providerUser->getId(),
'provider' => 'facebook'
]);
$account->user()->associate($user);
$account->save();
return $user;
}
}
And finally the Model :
<?php
namespace Myproject\Users;
use Illuminate\Database\Eloquent\Model;
use Myproject\Users\User;
class SocialLogin extends Model
{
protected $table = 'social_logins';
protected $fillable = ['user_id', 'provider_user_id', 'provider'];
public function user()
{
return $this->belongsTo(User::class);
}
}
When we're trying to connect via Facebook, the information is correctly insert in Database, and the callback URL set on Facebook Developers correspond to what we have in our .env, so the redirection is correctly done but at the end we don't have any session created for the user.
I think the issue comes from cross-domain, here are the interesting parts of our .env file :
APP_URL=https://www.website.com
APP_DOMAIN=website.com
SESSION_DOMAIN=.website.com
CACHE_DRIVER=redis
SESSION_DRIVER=redis
SESSION_LIFETIME=120
FACEBOOK_REDIRECT=https://www.website.com/callback/facebook
GOOGLE_REDIRECT=https://www.website.com/auth/google/callback
And our routing on web.php :
Route::domain('{subdomain}.{domain}')->middleware('locale')->group(function () {
Route::get('/callback/facebook', 'Auth\SocialAuthController#callback');
Route::get('/redirect/facebook', 'Auth\SocialAuthController#redirect');
});
I really think the issue is located on routing or SESSION_DOMAIN, but we tried to :
delete the session domain
routing outside the middleware locale, in a middleware auth
It still doesn't affect the login.
I need to use md5() instead of bcrypt() for storing passwords. But when I just do this:
protected function create(array $data)
{
return Account::create([
'username' => $data['username'],
'email' => $data['email'],
'password' => md5($data['password']),
'datetoday' => Carbon::now(),
'lastip' => request()->ip(),
'confirmation' => bcrypt($data['password']),
]);
}
When I try to login it says the credentials are wrong.
Using md5() over bcrypt() is not recommended.
However you can manually authenticate user. Override login() method in LoginController
public function login(Request $request)
{
$user = User::where('username', $request->username)
->where('password',md5($request->password))
->first();
Auth::login($user);
return redirect('/');
}
You have to create new service provider.
app/providers/md5hashprovier.php
namespace App\Providers;
class MD5HashProvider extends \Illuminate\Hashing\HashServiceProvider
{
public function boot()
{
\App::bind('hash', function () {
return new \App\Classes\MD5Hasher;
});
}}
Next you have to create the MD5Hasher class. I'd suggest to locate it to
app/classes/MD5Hasher.php
class MD5Hasher extends BcryptHasher
{
public function check($value, $hashedValue, array $options = array())
{
$user = User::wherePassword(md5($value))->first();
return $user ? true : false
}
}
and register your new service provider to config/app.php in providers array
\App\Providers\MD5HashProvider::class,
This would enable auth with md5 password
Using MD5 is not a good idea anymore.
To get rid of the old MD5 records you can use the second trick here: http://john.cuppi.net/migrate-from-md5-to-bcrypt-password-hashes/
I have used Laravel Authentication (Quickstart). But I need to check the status of the user (approved/pending). If not approved, then an error will be shown in the login page. I need to know in which file I have to make the change and what is the change. Currently I am working on Laravel 5.3.
You can create a Laravel Middleware check the link for additional info
php artisan make:middleware CheckStatus
modify your middleware to get
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class CheckStatus
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
//If the status is not approved redirect to login
if(Auth::check() && Auth::user()->status_field != 'approved'){
Auth::logout();
return redirect('/login')->with('erro_login', 'Your error text');
}
return $response;
}
}
then add your middleware to your Kernel.php
'checkstatus' => \App\Http\Middleware\CheckStatus::class,
and finally add the middleware to your route
Route::post('/login', [
'uses' => 'Auth\AuthController#login',
'middleware' => 'checkstatus',
]);
I hope it helps
I found a simple solution for this. Artisan create App\Http\Controllers\Auth\LoginController, in this default controller just add this code if you have some conditions to login, for example I have a field state, you posibbly have status, email_status or other.
// Custom code for Auth process
protected function credentials( Request $request )
{
$credentials = $request->only($this->username(), 'password');
$credentials['state'] = 1;
return $credentials;
}
upper answer saves me
if (Auth::attempt(['email'=>$input['email'],'password'=>$input['password'], 'user_status'=>1 ]))
this will check the status
Just Add following method in my LoginController works like charm
protected function authenticated(Request $request, $user)
{
if ($user->yourFirldName != "Active") {
Auth::logout();
return redirect('/login')->with('error', 'Looks Like Your status is InActive');
}
}
I don't agree with upper answer, which will lead to your application performance is very low, and also don't recommend to modify the Laravel's source code.
So you can rewrite getCredentials function to your app\Http\Controllers\Auth\AuthController.php file like this:
<?php
//app\Http\Controllers\Auth\AuthController.php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Http\Request;
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
//you need add this function
protected function getCredentials(Request $request)
{
$data = $request->only($this->loginUsername(), 'password');
$data['is_approved'] = 1;
return $data;
}
}
then you can use Laravel Authentication (Quickstart) directly.
Hope this will help.
The pinned answer is the best approach.
Just a note: if you are using Laravel 5.8+ you need use:
//Default Auth routes
Auth::routes();
//Override and add middleware
Route::post('/login', [
'uses' => 'Auth\LoginController#login',
'middleware' => 'checkstatus',
]);
Follow the steps...
First add a column in your user table (suppose is_approved)
In App/Http/Controllers/Auth/LoginController file
public function authenticate()
{
if (Auth::attempt(['email' => $email, 'password' => $password, 'is_approved'=>1])) {
// Authentication passed...
return redirect()->intended('dashboard');
}
}
Hope this will help
Auth/LoginController
Though it is a long time from the question created date. You can go this way.
Go to Auth/LoginController and add this line.
protected function credentials(Request $request)
{
return [
'email' => $request->email,
'password' => $request->password,
'status' => 1,
];
}
For this to work you have to have a column named 'status' in users table. 1 is for active and 0/2 is for inactive user.
Hope this will work for you.
public function login(Request $request){
if ($request->isMethod('post')) {
$data= $request->all();
$roles=[
'email' => 'required|email|max:255',
'password' => 'required',
];
$customessage=[
'email.required' =>'Email is required',
'email.email' => 'Email is not vaild',
'password.required' => 'Password is required',
];
$this->validate($request,$roles,$customessage);
if(Auth::guard('admin')->attempt(['email'=>$data['email'],'password'=>$data['password'],'status'=>1])) {
return redirect('admin/dashboard');
} else {
Session::flash('error_message','You are not Active by Admin');
return redirect()->back();
}
}
return view('admin.admin_login');
}
Hi I'm new to laravel and I'm using the laravel5.2 version.
Actually I have this registration form too. But no problem in registration.
My question is that I'm looking for a simple and understandable code in login. I've seen it somewhere while googling but I think that one is not laravel5.2.
I just get the reference code in some examples and test it into my login app. I'm using a repositories on it. I've got some errors. It says
Whoops, looks like something went wrong.
1/1 FatalErrorException in EloquentUserProvider.php line 126: Class '\App\User' not found
I'm not sure why the error says app user not found. Here is my code below
<?php
namespace App\Repositories;
use App\Repositories\Contracts\loginRepositoryInterface;
use Illuminate\Http\Request;
use App\Users;
use DB;
use Session;
use Auth;
class loginRepository implements loginRepositoryInterface{
protected $request;
//Initialize request instance
public function __construct(Request $request){
$this->request = $request;
}
public function loginAuth(){
//validate login
$validator = app('validator')->make($this->request->all(), [
'emailAddress' => 'email|required',
'password' => 'required']);
//if validator fails then return response error
if($validator->fails())
return redirect()->route('get.login')->withErrors($validator)->withInput();
try{
$pwd = $this->request->get('password');
$sha1 = sha1($pwd);
$userdata = array(
'emailAddress' =>$this->request->get('emailAddress'),
'password' =>$sha1
);
if(Auth::attempt($userdata)){
return redirect()->intended('get.dashboard');
}else{
return redirect()->route('get.login')->withErrors($validator)->withInput();
}
}catch(\Exception $e){
return redirect()->route('get.login')->withErrors(["error"=>"Could not add details! Please try again."])->withInput();
}
}
//postCreate
public function postCreate($screen){
switch($screen){
case 'auth':
return $this->loginAuth();
break;
}
}
//getLoginView
public function getCreate(){
return view('login');
}
}
In method public function loginAuth()
My routes
//postLogin
Route::post('/login/{screen}', [
'as' => 'post.login.auth',
'uses' => 'loginController#postCreate'
]);
//getLoginView
Route::get('/login', [
'as' => 'get.login',
'uses' => 'loginController#getCreate'
]);
Can some one help me on this?
Thanks.
Make sure you have the \App\User model in app/User.php from the looks of the code you posted above, you seem to have \App\Users not \App\User