Laravel 4 Authentication attempt() fails - authentication

I have a problem with Laravel authentication system:
$credentials = array(
'email' => Input::get('email'),
'password' => Input::get('password'),
'active' => 1
);
if(Auth::attempt($credentials)){
echo "fine";
}else{
echo "fail";
}
Auth::attempt()always return false.
Therefore, I tried to authenticate an other way:
$user = User::where('email','=',Input::get('email'))->firstOrFail();
if ($user->active && Hash::check(Input::get('password'), $user->password)){
echo "fine";
}else{
echo "fail";
}
This one works.
Would you know what could possibly make the attempt method not working?

Your code is correct, but I think you have edited User model ( check if you still implement UserInterface and RemindableInterface for exemple)
https://github.com/laravel/laravel/blob/master/app/models/User.php

Related

Laravel 8: undefined method 'createToken' intelephense(1013)

I have a problem with PHP intelephense, the method createToken is undefined. i don't know how to fix it. but when I run it in postman it works. i don't know why vscode doesnt recognize it. i also add the use Laravel\Passport\HasApiTokens; and use HasApiTokens in user model. please help me, I'm running out of options. thank you guys
public function login(Request $request)
{
$login = $request->validate([
'email' => 'required',
'password'=> 'required',
]);
if (!Auth::attempt($login)){
return response()->json(['message' => 'error']);
}
$user = Auth::user();
$token = $user->createToken('Token Name')->accessToken;
return response()->json(['user' => $user, 'token' => $token]);
}
I encountered the same problem and solved by adding the line. For my case.
/** #var \App\Models\MyUserModel $user **/
$user = Auth::user();
I think the annotation line tell PHP intelephense that $user variable is not Illuminate\Foundation\Auth\User type but \App\Models\MyUserModel type. Please try it.
in the model User add
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens;
}
try and tell me

How can is possible to attach different roles to users in the exact moment of registration?

before starting I premise and humbly apologize: I am a neophyte regarding the use of Laravel framework. I Searched eveywhere even the documentation but without results.
My question is if it is possible to assign a role at registration time using the Laratrust library. We want for example that the first 4/5 users who register are administrators, from the fifth onwards are normal users with restricted permissions.
This is the code regarding the Controller for registration.
RegisterController.php
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\Models\User
*/
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
if(Auth::id() < 4 ){
$user->attachRole('administrator');
}
else{
$user->attachRole('user');
}
return $user;
}
This is the method that aims to register the user from the form, for some reason when I go to take the current id of the user, the condition in the if statement is bypassed, in fact in the database in the table roles i always have users that are administrators. I am thinking that maybe the real problem is Auth Class beacuse if i understood correctly this class is used when a user is already logged.
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$checklatestid = User::latest()->pluck('id')->first();
if($checklatestid < 4 ){
$user->attachRole('administrator');
//Ruolo amministratore impianto scii
}
else{
$user->attachRole('user');
//Ruolo cliente impianto scii
}
return $user;
}
If understand you correctly

how to create logged in session in yii

i tried using hybrid auth for a facebook login on my yii app, but couldn't get it to work. so decided to work on my own. i managed to get it to retrieve data and store it in my DB. but yii, still doesn't detect user as logged in. here is part of my code in my controllers/FacebookController.php
if (app()->request->isAjaxRequest) {
$user = app()->request->getParam('user');
Shared::debug($user);
// verify one last time that facebook knows this guy
if ($user['id'] === app()->facebook->getUser()) {
if (!empty($user['email']))
{
$model = User::model()->findByEmail($user['email']);
}
else if (!empty($user['username']) && empty($user['email'])) //incase we don't get an email, we use a facebook email
{
$email = $user['username'].'#facebook.com';
$model = User::model()->findByEmail($email);
}
else
{
$model = false;
}
if (!empty($model))
{
// facebook email matches one in the user database
$identity = new UserIdentity( $model->email , null );
$identity->_ssoAuth = true;
$identity->authenticate();
if ($identity->errorCode === UserIdentity::ERROR_NONE) {
print_r($identity);
app()->user->login($identity, null);
echo json_encode(array('error' => false, 'success' => url('/')));
app()->end();
}
else {
echo json_encode(array('error' => 'System Authentication Failed', 'code' => 'auth'));
app()->end();
}
}
in my code above, when i print_r($identity); the object below is echoed. and FYI, the email xxxxxx#facebook.com is stored in the DB but app()->user->isGuest() still returns true. what am i doing wrong here?
UserIdentity Object
(
[_ssoAuth] => 1
[_id:UserIdentity:private] => 19
[username] => xxxxxx#facebook.com
[password] =>
[errorCode] => 0
[errorMessage] =>
[_state:CBaseUserIdentity:private] => Array
(
)
[_e:CComponent:private] =>
[_m:CComponent:private] =>
)
http://yiiframework.com/doc/api/1.1/CWebUser#login-detail
Instead of passing a null into app()->user->login($identity, null) try passing in a duration like
$duration = 3600*24*30; //30 days
app()->user->login($identity, $duration);
I have had problems setting duration to 0. Not sure why either. But this worked for me before

Authentication with PHP SDK

I am having trouble using the PHP SDK for authentication. The effect I am trying to get is whene a user visits the site if they are loged in with FB they see "Logout" which loggs them out when clicked but if they are not logged in when they arrive they should see "You need to log in with FB" which loggs them in. The effect I am currently getting is that the site displays the "You need to log in with FB" even if the user is already logged in, whene this is clicked the user is taken to facebook.com with an error message displayed reading "An error occurred. Please try later". Im sure I must be missing something in my code but cant figure out what, I am fairly new to FB development. Please see my code below. Any help much appriciated.
<?php
require_once("facebook.php");
$user = $facebook->getUser();
$config = array();
$config[‘appId’] = xxx;
$config[‘secret’] = '{secret}';
$facebook = new Facebook($config);
$fbparams = array(
'scope' => 'read_stream, friends_likes',
'redirect_uri' => 'xxx'
);
session_start();
$loginUrl = $facebook->getLoginUrl($fbparams);
$params = array( 'next' => 'xxx' );
$logoutUrl = $facebook->getLogoutUrl($params);
if(!$user)
{
echo "<P>You need to log into FB</p>\n";
}
else
{
echo "<p style=\"margin-bottom:20px;\"><a href=\"{$logoutUrl} \">Logout</p>\n";
}
?>
Try this out
<?php
require_once("facebook.php");
$user = $facebook->getUser();
$config = array();
$config[‘appId’] = xxx;
$config[‘secret’] = '{secret}';
$facebook = new Facebook($config);
$fbparams = array(
'scope' => 'read_stream, friends_likes',
'redirect_uri' => 'xxx'
);
$loginUrl = $facebook->getLoginUrl($fbparams);
$params = array( 'next' => 'xxx' );
$logoutUrl = $facebook->getLogoutUrl($params);
<?php if ($user) { ?>
<p>Logout</p>
<?php } else { ?>
<p>Click here to View Your Stalker of the Day</p>
<?php } ?>
You can not call $facebook before creating the instance, This code should work:
<?php
session_start();
require_once("facebook.php");
$config = array();
$config[‘appId’] = xxx;
$config[‘secret’] = '{secret}';
$facebook = new Facebook($config);
$user = $facebook->getUser();
$fbparams = array(
'scope' => 'read_stream, friends_likes',
'redirect_uri' => 'xxx'
);
$loginUrl = $facebook->getLoginUrl($fbparams);
$params = array( 'next' => 'xxx' );
$logoutUrl = $facebook->getLogoutUrl($params);
if(!$user)
{
echo "<P>You need to log into FB</p>\n";
}
else
{
echo "<p style=\"margin-bottom:20px;\"><a href=\"{$logoutUrl} }\">Logout</p>\n";
}
?>
$params = array( 'next' => 'xxx' );
is deprecated SDK, use
$params = array( 'redirect_uri' => 'xxx' );
instead.

Facebook SDK 3.1 getUser most basic code not working

I had some really complicated code, and now I've made it ridiculously simple, and it doesn't work.
Currently it simply takes me back to the page with the login URL echoed out.
Code is here:
<?php
require 'facebook.php';
// Create our application instance
// (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'sd',
'secret' => 'sda',
));
// Get User ID
$user = $facebook->getUser();
if($user) {
echo $user;
} else {
$loginUrl = $facebook->getLoginUrl(array('redirect_uri'=>'http://www.facebook.com/pages/CharlesTestPage/225802194155435?sk=app_252946408094785','scope'=>'email'));
echo $loginUrl;
}
exit;
?>
Please. I have spent a whole paid work day on this now, and am at the point of crying, not only for myself but for my boss.
Cry.
Edit: OK, the weird thing is, if I have the redirect_uri set to the facebook tab, if it's not authenticated itself, then it constantly redirects in an infinite loop. However, if I remove the redire
This is what's working for me using PHP SDK 3.1.1. Try it and let us know if this works:
include('facebook.php');
session_start();
//facebook application
$config['appid' ] = "YOUR_APP_ID";
$config['secret'] = "YOUR_APP_SECRET";
$config['baseurl'] = "http://example.com/facebookappdirectory";
$config['appbaseurl'] = "http://apps.facebook.com/your-app-name";
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $config['appid'],
'secret' => $config['secret'],
'cookie' => true,
));
$user = $facebook->getUser();
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'email'
)
);
if ($user) {
try {
//get user basic description
$userInfo = $facebook->api("/$user");
$fb_access_token = $facebook->getAccessToken();
} catch (FacebookApiException $e) {
//you should use error_log($e); instead of printing the info on browser
error_log('APP ERROR: '.$e);
$user = null;
}
}
if (!$user) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
if (isset($_GET['code'])){
header("Location: " . $config['appbaseurl']);
exit;
}
Check for
if(isset($_GET['code'])){
$user = $facebook->getUser();
$access_token = $facebook->getAccessToken();
}
Facebook return userID only after the login and that code.