Laravel 4 user login authentication - oracle

i'm using laravel with oracle database. Now, i'm making login sections. When i was input correct username and password, result is okay. But i was input incorrect username or password, following exception occured:
Illuminate \ Database \ QueryException
oci_error() expects parameter 1 to be resource, object given (SQL: select * from test_laravel_auth where username = tugsuu and password = testsss)
My controller code:
$user = DB::table('test_laravel_auth')->where('username', '=', $input['login_username'])
->where('password', '=', $input['login_password'])
->get();
return count($user);
if($user != null){
return "SUCCESS :D";
}
return "failed";

I assume you were using [jfelder/Laravel-OracleDB] package. It is a known issue as stated on site and a fixed was already added. Try updating your packages by running composer update.
Another option is to use yajra/laravel-oci8 package to connect to Oracle.

try this
$user = DB::table('test_laravel_auth')->where('username', '=', Input::get('username'))
->where('password', '=', Input::get('password'))
->get();
if(Auth::attempt($user))
{
//here success
}
else
{
return Redirect::to('login')->with('login_errors','Invalid Login Credentials.');
}

I suggest you use first instead of get(), this will retrieve the first record (only one should be found). You could also try with firstOrFail() and create an error handler if it "fails". If it fails = login incorrect.
$user = DB::table('test_laravel_auth')->where('username', '=', Input::get('login_username'))->where('password', '=', Input::get('login_password'))->first();
if (!is_null($user))
{
Auth::login($user);
}
else
{
//failed
}

Im also using Oracle database in Laravel and this solution works for me:
if ( Auth::attempt( array( 'user_name' => Input::get( 'username' ), 'password' => Input::get( 'password' ) ) ) )
{
return Redirect::intended( 'dashboard' );
}
else
{
return Redirect::to( 'login' )->withInput( Input::except( 'password' ) );
}
My code is just same on the Laravel documentation. It doesn't require you to use queries for authentication, all you need to use is the authentication class that comes with Laravel.
What driver/package you are using? Im using the yajra/laravel-oci8 package to make Oracle work with Laravel.
You may read more about laravel-oci8 package documentation on its page: https://github.com/yajra/laravel-oci8

Related

ADLDAP openLDAP authentication - Session not stored - returning to login page

My environment is a laravel 5.8 with adldap2 in version 6.0.8 web app and an openLDAP directory.
After hours, I finally could authenticate my user against the openLDAP directory and also the database import into the users table works:
Id name username password remember_token created_at updated_at
King king $2y$10$YF9q7cYqjYnkl.We4Evwv.u/a2sddrfBA3pohgpS2vR... j4AOUHSlkHE3IQW7bsgF7pOIY8EAss6iukfnKhwi2lqXR0eTjE... NULL NULL
When I check the variable user in the function: attemptLogin -> $this->guard()->login($user, true); it is from the DB and seems to be fine. But still after I log in, I also get the message "Redirecting to http://localhost/home.", it returns to the login page and is still not logged in.
For LDAP authentication I followed mostly this example: https://jotaelesalinas.github.io/laravel-simple-ldap-auth/ even if it is a bit obsolete.
My attemptLogin function looks like this:
protected function attemptLogin(Request $request)
{
$username = Adldap::search()->users()->select('mail','uid','displayName')->findBy('cn', request()->get('username'));
$result = 1;
if($username){
if(Adldap::auth()->attempt($username->getdistinguishedName(), request()->get('password'))){
echo("success");
// Check group
$group = Adldap::search()->groups()->findOrFail('cio');
foreach ($group->getMemberNames() as $name) {
if($name === $username->getAccountName()){
echo("The user is a member of the group.");
$result = 0;
}
}
if ($result != 0){
$result = 2;
}
} else {
echo("Password wrong");
$result = 1;
}
} else {
echo(request()->get('username') . " not found");
$result = 1;
}
if($result == 0) {
// the user exists in the LDAP server, with the provided password
echo("Everything ok");
$user = \App\User::where($this->username(), $username->getAccountName())->first();
if (!$user) {
// the user doesn't exist in the local database, so we have to create one
$user = new \App\User();
$user->username = $username;
$user->password = '';
// you can skip this if there are no extra attributes to read from the LDAP server
// or you can move it below this if(!$user) block if you want to keep the user always
// in sync with the LDAP server
//dd($username->getDisplayName());
$sync_attrs = $this->retrieveSyncAttributes($username->getAccountName());
//dd($sync_attrs);
foreach ($sync_attrs as $field => $value) {
$user->$field = $value !== null ? $value : '';
}
}
$this->guard()->login($user, true);
return 0;
}
// the user doesn't exist in the LDAP server or the password is wrong
// log error
return $result;
}
Web.php
Route::get('login', 'Auth\LoginController#showLoginForm')->name('login');
Route::post('login', 'Auth\LoginController#login');
Route::post('logout', 'Auth\LoginController#logout')->name('logout');
Route::get('/home', 'HomeController#index')->name('home');
Has anyone an idea what I am missing? Or if you need more information, please tell me. It seems like the session is not stored.
Thanks in advance
Stephan
A small update after playing around some more hours. It seems like that Auth is after the successful login null. So tried different approaches I could find on the internet like changing the web.php routes or adding the protected $user variable to the LoginController.php but of course without any success.
I figured out that when I change the middleware from auth to web, I will get a session but the Auth::User() is still empty
Route::group(['middleware' => 'auth'], function () {
Route::get('/home', 'HomeController#index')->name('home');
});
After spending more and more hours, I finally found the solution in this thread: Laravel Auth:attempt() will not persist login
My issue was that I was using "echo's".
It cost me probably some days of my life

Disable hashing on Auth::attempt

I am working with an old database without hashed passwords, also this database needs to be unhashed since it is connected to a Runnable JAR.
I did everything to connect it with Laravel 5.3 and it worked, but.. When comes to login it always return false.
Here is the function code:
public function login(Request $request)
{
$this->validate($request, [
'account' => 'required|alpha_num|exists:accounts,account',
'password' => 'required|alpha_num|min:4',
]);
if(Auth::attempt(['account' => $request->account, 'password' => $request->password])){
return redirect()->route('account');
}
return redirect()->back()->withInput();
}
I came to the conclusion that Auth::attempt hashes the given password through the view and when comparing to the unhashed one in the database, returns false.
How can i fix this??
Thank you.
You will need to use another method of manual authentication.
$user = User::where('account', $request->account)
->where('password', $request->password)
->first();
if($user) {
Auth::loginUsingId($user->id);
// -- OR -- //
Auth::login($user);
return redirect()->route('account');
} else {
return redirect()->back()->withInput();
}
You just can add this to your App/User.
If you are using another driver in config/hashing.php - change bcrypt to argon/argon2i
public function getAuthPassword() {
return bcrypt($this->password);
}

Unable To Connect Laravel to MailChimp (laravel 5.4)

I have to define List ID and MailChimp API Key in my .env file. I'm sure both are fine even I am not getting any error but email in not inserting in my List I installed https://github.com/spatie/laravel-newsletter (spatie/laravel-newsletter) Package.
Here is my method
public function subscribe(Request $request)
{
$email = request('email');
Newsletter::subscribe($email);
Session::flash('subscribed', 'Successfully subscribed.');
return redirect()->back();
}
Then I check subscribe Method in Newsletter.php
it is as
public function subscribe($email, $mergeFields = [], $listName = '', $options = [])
{
$list = $this->lists->findByName($listName);
$options = $this->getSubscriptionOptions($email, $mergeFields, $options);
$response = $this->mailChimp->post("lists/{$list->getId()}/members", $options);
if (! $this->lastActionSucceeded()) {
return false;
}
return $response;
}
I print options variable it returns output as
array:3 [▼
"email_address" => "bluemoon#gmail.com"
"status" => "subscribed"
"email_type" => "html"
]
Then I print below variable $response it returns false Please Help whats wrong with this.
Thanks In advance
Not sure this will directly resolve your issue, but you need to run the following command in your terminal:
php artisan vendor:publish --provider="Spatie\Newsletter\NewsletterServiceProvider"
This creates a laravel-newsletter.php in the config directory, that's where your List ID and MailChimp API key should go.
PS: the package seems to have an issue with env so don't use it, just enter your keys as strings.

Hash::check() return false in laravel 5

I'm just starting with laravel 5, I'm doing a simple login function to check if email and password passed by user matches with the email and password stored in the database. I've been reading the documentation ([https://laravel.com/docs/5.0/hashing1) but Hash::check($content['password'], $user->{'password'}) returns false always. My code looks like this.
When I create a new user I hash the password like that:
$content = json_decode($request->getContent(), true);
$user -> password = Hash::make($content['email']);
And my login function looks like that:
public function login(Request $request)
{
$content = json_decode($request -> getContent(), true);
$user = DB::table('users')->where('email', $content['email'])->first();
if (Hash::check($content['password'], $user->{'password'}))
{
// Redirect to dashboard
}
}
Thanks in advance!!
Actually you are hashing the email instead of password while creating the user. change the code from
$user->password = Hash::make($content['email']);
To
$user->password = Hash::make($content['password']);
i came up with same issue. check database users table, password field. make the size of the field to 60 or more. this fixed mine.
The facade Hash just will encrypt your data:
Hash::make('123456');
is the same that:
$password = bcrypt('123456');
to login a user you need to use AuthController functions:
Auth::attempt(['email' => 'test#test.com' , 'password' => Hash::make('password')]);
it's a example.
If you're receiving a request, you can add this method to login:
if(Auth::attempt(['email' => $request->email, 'password' => $request->password , 'active' => 1])){
flash()->success('Successfully logged in!');
return redirect('/');
}
the attempt function will hash your password field and will compare with database data.

Oauth2-server-laravel always ask to approve/deny after login

I am newbie in Oauth2 and laravel. I am trying to implement Authorization Server in laravel with authorization code grant. I followed all implementation instruction mentioned in https://github.com/lucadegasperi/oauth2-server-laravel.
Every thing is working fine except user need to approve/deny on each login to get access code. I want to show authorization-form only once when user first time ask for authorization and not every time, similar to how Oauth2 is implemented in google.
How can I do it, any pointers?
I have implemented a solution for your issue in one of my work, here is the sample code, hope that help:
Route::get('/oauth/authorize', array('before' => 'check-authorization-params|auth', function() {
// get the data from the check-authorization-params filter
$params = Session::get('authorize-params');
// get the user id
$params['user_id'] = Auth::user()->id;
if ($params['approval_prompt'] != 'force')
{
$session = DB::table('oauth_sessions')->where('client_id', '=', $params['client_id'])
->where('owner_type', '=', 'user')
->where('owner_id', '=', $params['user_id'])
->first();
if ($session)
{
$code = AuthorizationServer::newAuthorizeRequest('user', $params['user_id'], $params);
Session::forget('authorize-params');
return Redirect::to(AuthorizationServer::makeRedirectWithCode($code, $params));
}
}
// display the authorization form
return View::make('authorization-form', array('params' => $params));
}));
If the approval_prompt is not set to force, then I will check whether if there are any sessions belong to this user and show the authorization form only if there is no saved sessions.
Notice: This code is for the 1.0 version of the package, if you're using another version, there may be some different things.
This is modification of Hieu Le answer for Laravel 5.1 and lucadegasperi/oauth2-server-laravel with league/oauth2-server 4.1.2
Route::get('/oauth/authorize', ['as' => 'oauth.authorize.get','middleware' => ['check-authorization-params', 'auth'], function() {
// display a form where the user can authorize the client to access it's data
$authParams = Authorizer::getAuthCodeRequestParams();
$authParams['client_id'] = $authParams['client']->getId();
$formParams = array_except($authParams,'client');
$authParams['user_id'] = Auth::user()->id;
if (array_get($authParams, 'approval_prompt', null) != 'force')
{
$session = DB::table('oauth_sessions')->where('client_id', '=', $authParams['client_id'])
->where('owner_type', '=', 'user')
->where('owner_id', '=', $authParams['user_id'])
->first();
if ($session)
{
$redirectUri = Authorizer::issueAuthCode('user', $authParams['user_id'], $authParams);
return Redirect::to($redirectUri);
}
}
return View::make('oauth.authorization-form', ['params'=>$formParams,'client'=>$authParams['client']]);
}]);

Resources