how to create logged in session in yii - 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

Related

How can i set expire time in otp in laravel8?

When i am trying to expiry otp, is not working but i do not know what i am doing wrong. I set expiry time with Carbon but still not working. What should i do?. It needs config in app/config or something?
This is a part of my controller code
if(!$device_serial_number)
{
return ('error');
} else {
$otp = rand(100000,999999);
// Cache::put([$otp], now()->addSeconds(20));
$otp_expires_time = Carbon::now()->addSeconds(20);
Cache::put(['otp_expires_time'], $otp_expires_time);
Log::info("otp = ".$otp);
$user = User::where('phonenumber', $request->phonenumber)->update(['otp' => $otp]);
$token = auth()->user()->createToken('Laravel Password Grant Client')->accessToken;
// Log::info($request);
// $user = User::where([['phonenumber', '=', request('phonenumber')],['otp','=', request('otp')]])->first();
return response()->json(array(
'otp_expires_at'=> $otp_expires_time,
'otp' => $otp,
'token' => $token));
This is a part of my middleware code
Log::info($request);
$user = User::where([['phonenumber', '=', request('phonenumber')],['otp','=', request('otp')],['otp_expires_time', '=', request('otp_expires_time')]])->first();
$otp_expires_time = Carbon::now()->addSeconds(20);
if($user)
{
if(!$otp_expires_time > Carbon::now())
{
return response('the time expired');
} else {
Auth::login($user, true);
return response()->json(array(
'message' => 'You are logged in',
['user' => auth()->user()]));
return response('You are logged in');
$otp = rand(1000,9999);
Cache::put([$otp], now()->addSeconds(10));
$otp_expires_time = Carbon::now('Asia/Kolkata')->addSeconds(10);
Log::info("otp = ".$otp);
Log::info("otp_expires_time = ".$otp_expires_time);
Cache::put('otp_expires_time', $otp_expires_time);
$user = User::where('email','=',$request->email)->update(['otp' => $otp]);
$user = User::where('email','=',$request->email)->update(['otp_expires_time' => $otp_expires_time]);

Lumen Google reCAPTCHA validation

I already seen some tuts and example about it and I have implemented it somehow.
Method in controller looks like this:
The logic used is just php and I would like to use more a lumen/laravel logic and not just simple vanilla php. Also I have tried and did not worked anhskohbo / no-captcha
public function create(Request $request)
{
try {
$this->validate($request, [
'reference' => 'required|string',
'first_name' => 'required|string|max:50',
'last_name' => 'required|string|max:50',
'birthdate' => 'required|before:today',
'gender' => 'required|string',
'email' => 'required|email|unique:candidates',
'g-recaptcha-response' => 'required',
]);
//Google recaptcha validation
if ($request->has('g-recaptcha-response')) {
$secretAPIkey = env("RECAPTCHA_KEY");
// reCAPTCHA response verification
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secretAPIkey.'&response='.$request->input('captcha-response'));
$response = json_decode($verifyResponse);
if ($response->success) {
//Form submission
//Saving data from request in candidates
$candidate = Candidate::create($request->except('cv_path'));
$response = array(
"status" => "alert-success",
"message" => "Your mail have been sent."
);
} else {
$response = array(
"status" => "alert-danger",
"message" => "Robot verification failed, please try again."
);
}
}
} catch(Exception $e) {
return response()->json($e->getMessage());
}
return response()->json(['id' => $candidate->id, $response]);
}
Okey. Google has an package for this:reCAPTCHA PHP client library
just: composer require google/recaptcha "^1.2"
and in your method inside controller:
$recaptcha = new \ReCaptcha\ReCaptcha(config('app.captcha.secret_key'));
$response = $recaptcha->verify($request->input('g-recaptcha-response'), $_SERVER['REMOTE_ADDR']);
if ($response->isSuccess()) {
//Your logic goes here
} else {
$errors = $response->getErrorCodes();
}
config('app.captcha.site_key') means that I got the key from from config/app.php and there from .env file.
If you have not config folder, you should create it, also create app.php file same as in laravel.

How to override this code so that it insert data properly?

This question is a follow-up of this one How to properly insert time when user leaves( user_left and user_joined got the same value)
I get data when user logged in and store in in DB.
Broadcast::channel('chat', function ($user) {
$ip = Request::ip();
$time = now();
if (auth()->check() && !session()->has('name')) {
UserInfo::storeUser();
session()->put('name',$user->name);
return [
'user_id' => $user->id,
'ip' => $ip,
'name' => $user->name,
'joined' => $time,
];
}
});
I get time when user logged out and also store in DB.
public function logout() {
$info = auth()->user()->info;
$info->left = now();
$info->save();
auth()->logout();
session()->forget('name');
session()->put('left', now());
return redirect('/');
}
UserInfo model
public static function storeUser() {
UserInfo::create([
'user_id' => Auth::id(),
'ip' => Request::ip(),
'name' => Auth::user()->name,
'joined' => now(),
]);
}
This is what I've got.
The time when user left gets inserted not in the way I would like to. The first record with the name of the current user gets the time. I would like to see the LAST record of the current user receiving that data(when Syd 12 logged out Syd 10 received Syd's 12 'left' data. The same story goes with Kate.)

AuthenticationService error in TYPO 3: "updateLoginTimestamp () must be of the type integer, null given"

I would like to implement a login at TYPO3 v8.7. Here it is so that the data comes from a foreign provider who should log in automatically with his login data of his system at TYPO3. I developed something for that.
What is wrong?
// Authentication Service
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addService(
$_EXTKEY,
'auth',
'TEST\\Tests\\Service\\AuthenticationService',
array(
'title' => 'User authentication service',
'description' => 'Authentication with username',
'subtype' => 'getUserFE, authUserFE',
'available' => true,
'priority' => 90,
'quality' => 90,
'os' => '',
'exec' => '',
'className' => 'TEST\\Tests\\Service\\AuthenticationService',
)
);
This is in ext_localconf.php
class AuthenticationService extends \TYPO3\CMS\Sv\AuthenticationService
{
function init() {
$available = parent::init();
return $available;
}
public function getUser(){
$remoteUser = $this->getRemoteUser();
$user = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
'*',
'fe_users',
'username = '.$GLOBALS['TYPO3_DB']->fullQuoteStr($remoteUser, 'fe_users') . ' AND deleted = 0'
);
return $user;
}
public function authUser($user)
{
$userData = $user[0];
foreach ($user[0] as $item => $key) {
if (is_numeric($key)) {
$result_array[$item] = (int) $key;
} else {
$result_array[$item] = $key;
}
}
$this->login = $loginData = array(
'uname' => $userData["username"],
'uident_text' => $userData['password'],
'status' => 'login'
);
$ok = $this->compareUident($result_array, $loginData);
if($ok == 1) {
return 200;
}
return 100;
}
/**
* Returns the remote user.
*
* #return string
*/
protected function getRemoteUser()
{
[...]
return $user;
}
}
Is that all right, what am I doing?
In the function remoteUser I get the username of the third party provider.
Whenever I enter the GET parameter, the AuthService is triggered. However, I get the following error message:
"updateLoginTimestamp () must be of the type integer, null given"
Unfortunately I do not find the mistake I make. Hence my question if anyone sees where this is?
The getUser() Method should Return an Array of the User reccord
which is equal to a database row of fe_users
i am Guessing there is no existing fe_user for the username you get from getRemoteUser thus its the job of the Authentication service to create/update a record for this user in the table fe_users.
so in a more step by stepp manner your service should follow the following steps
in get user:
1. get Remote Username
2. check if Remote Username exists in fe_users table
3. if not create an new entry for Remote Username in fe_users
4. select the entry of Remote Username from fe_users and return the row.

hook_node_grants not invoked in drupal-7

i use "hook_node_grants()" in my module but it never run (invoke).
note that "hook_node_access_records" is right.
function mymodule_node_grants($account, $op) {
dpm($op);
$grants = array();
if ($op == 'view' || $op == 'update') {
$grants['guser'] = array($account->uid);
}
return $grants;
}
function mymodule_node_access_records($node) {
if (!empty($node->guser)) {
$grants = array();
$grants[] = array(
'realm' => 'guser',
'gid' => user_load_by_name(array('name' => $node->guser))->uid,
'grant_view' => 1,
'grant_update' => 1,
'grant_delete' => 1,
'priority' => 1,
);
return $grants;
}
}
Perhaps this answer post will help you.
To summarize, if you are testing this code logged in as an Administrator (UserID: 1) hook_node_grants will not be invoked.
Also, looking at some of the source code that hook will not be invoked if the role of the user you are authenticated with has the bypass node access permission enabled.