set user id based on pk when logged in through facebook - facebook

I am able to login/logout on my web app using facebook. But the problem is when the user needs to update his profile on my application, he can't. It would say that he is restricted to view his own page. The only way for this to happen is that user identity is probably not set. But I am not sure how to correct this. When I tried Yii::app()->user->user_id the Id is actually correct id, which is the pk in user model. So how is it that he cannot get to update his own page?
in my facebookUserIdentity:
public function authenticate()
{
if($this->getIsAccessTokenValid() && $this->setFBUser())
{
$this->_user = $this->getUserFromDatabase();
if($this->_user === false)
return false;
$this->setState('isUser', false);
$this->setState('isAdmin', false);
$this->setState('isShop', false);
$this->setState('isSuper', false);
$this->setState('user',$this->_user);
$this->_id = $this->_FBUser['id'];
//I've tried doing something like $this->_id = Yii::app()->user->user_id; or like $this->_user->user_id; ?
$this->_name = $this->_FBUser['name'];
return true;
}
else {
return false;
}
}
getting user from db:
protected function getUserFromDatabase()
{
$FBUser = $this->_FBUser;
if($FBUser)
{
$user = User::model()->findByAttributes (array('oauth_uid'=>$FBUser['id']));
if(!$user)
{
$user = new User;
$user->oauth_uid = $FBUser['id'];
$user->username = $FBUser['id'];
$user->first_name = $FBUser['first_name'];
//other info etc
$user->image = "https://graph.facebook.com/" . $FBUser['id'] . "/picture?type=large";
}
else
{
if ($user->oauth_permission == 'n')
{
$this->errorMessage = self::ERROR_LOGIN_DISABLE;
return false;
}
$user->last_login_date = date('Y-m-d H:i:s');
}
if($user->save())
{
return $user;
}
else
$this->errorMessage = CJSON::encode ( $user->getErrors());
return false;
}
else {
$this->errorMessage = "Failed getting facebook user data";
return false;
}
}
and lastly, the controller page rules:
public function accessRules()
{
$params=array();
$id=Yii::app()->request->getParam('id');
$params['model']=$this->loadModel($id);
return array(
//stuff
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update','RemoveImage'),
'roles'=>array('admin','super','owner'=>$params),
),
//stuff

Related

How to set expiration of newsletter confirmation link in magento 2

I have newsletter in my magento website. I have enable confirmation before subscription from admin configuration. User are getting confirmation link in mail.
But I want to set expiry of that link. Is magento provide default config ?
How can I set expiry of that link ?
I found the solution. I just did two things.
1) Add created_at field in newsletter_subscriber table.
2) Overwrite the following file
vendor/magento/module-newsletter/Model/Subscriber.php
to
Company/name/Model/Subscriber.php
Overited Subscriber.php file code
public function confirm($code) // existing function
{
$id = $this->getId();
if ($this->validateConfirmLinkToken($id, $code)) {
if ($this->getCode() == $code) {
$this->setStatus(self::STATUS_SUBSCRIBED)
->setStatusChanged(true)
->save();
$this->sendConfirmationSuccessEmail();
return true;
}
return false;
}
}
private function validateConfirmLinkToken($customerId, $code) //check validation for token
{
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$messageManager = $objectManager->get('Magento\Framework\Message\ManagerInterface');
if (empty($customerId) || $customerId < 0) {
$this->_messageManager->addError('Sorry you have not rigts to access this page');
return false;
}
if (!is_string($code) || empty($code)) {
$params = ['fieldName' => 'code'];
//$messageManager->addError('Sorry Your subscription confirmation code is not valid.');
return false;
}
$dcode = $this->getCode();
$dcreated_at = $this->getCreatedAt();
if (trim($dcode) != trim($code)) {
//$messageManager->addError('Sorry Your subscription confirmation code is mismatch.');
return false;
} elseif ($this->isConfirmationLinkTokenExpired($dcode, $dcreated_at)) {
//$messageManager->addError('Sorry Your subscription confirmation code is expired.');
return false;
}
return true;
}
public function isConfirmationLinkTokenExpired($dcode, $dcreated_at) // check expiration token
{
if (empty($dcode) || empty($dcreated_at)) {
return true;
}
$expirationPeriod = '720';
$currentTimestamp = (new \DateTime())->getTimestamp();
$tokenTimestamp = (new \DateTime($dcreated_at))->getTimestamp();
if ($tokenTimestamp > $currentTimestamp) {
return true;
}
$hourDifference = floor(($currentTimestamp - $tokenTimestamp) / (60 * 60));
if ($hourDifference >= $expirationPeriod) {
return true;
}
return false;
}
Hope it will helps to many.
Thanks.

How I check if the user is an ADMIN

Hello guys
I'm trying to create a function that allows the user to connect as admin, or simple user by creating a column in the users table called (is_adminn) as INT.
for the moment i'm doing it in a static way :
function _check_admin_login($username, $pword)
{
$target_username="firas";
$target_pass="password";
if(($username==$target_username) && ($pword==$target_pass)){
return TRUE;
}else{
return FALSE;
}
}
and then i will call it in the admin controller :
function username_check($str){
$this->load->module('store_accounts');
$this->load->module('site_security');
$error_msg = "Vous avez saisi un nom d'utilisateur ou un mot de passe incorrecte";
$pword = $this->input->post('pword', TRUE);
$result = $this->site_security->_check_admin_login($str, $pword);
if($result==FALSE){
$this->form_validation->set_message('username_check', $error_msg);
return FALSE;
}else{
return TRUE;
}
}
I did many tests like if the value of is_adminn is equal to 1 , it returns True
function _check_admin_login($username, $pword)
{
$this->load->module('store_accounts');
$this->store_accounts->fetch_data_from_db();
$is_adminn = $data['is_adminn'];
if($is_adminn==1){
return TRUE;
}else{
return FALSE;
}
}
It's easy to do what you want, first time check if the username and the password matches and after that check is the user id have the status is_admin 1.
model
public function check_admin($id){
$query = $this->db->get_where('user', array('id' => $id, 'is_admin' => 1 ));
if ($query->num_rows()>0) {
return true;
}else{
return false;
}
}
controller
$data['temp'] = $this->User_model->get_id_by_email($data['login']['email']);
$data['user'] = $this->User_model->check_login($data['login']['email'], $data['login']['password']);
if ($data['user'] && $this->Admin_model->check_admin($data['temp'][0]['id'])) {
$session_data = array(
//what you wanna store in session
);

Laravel 5.6 Error NotFoundHttpException in RouteCollection.php (line 179)

I try login facebook it's error NotFoundHttpException in RouteCollection.php (line 179)
I using Laravel 5.6
public function facebookAuthRedirect()
{
return Socialite::with('facebook')->redirect();
}
if facebook login success it's Redirect to facebook
public function facebookSuccess()
{
$provider = Socialite::with('facebook');
if (Input::has('code')){
$user = $provider->stateless()->user();
//dd($user); // print value debug.
$email = $user->email;
$name = $user->name;
$password = substr($user->token,0,10);
$facebook_id = $user->id;
//เช็คว่า email เป็น null หรือไม่
if($email == null){ // case permission is not email public.
$user = $this->checkExistUserByFacebookId($facebook_id);
if($user == null){
$email = $facebook_id;
}
}
else
{
$user = $this->checkExistUserByEmail($email);
if($user != null){
if($user->facebook_id == ""){ // update account when not have facebook id.
$user->facebook_id = $facebook_id;
$user->save();
}
}
}
if($user!=null){ // Auth exist account.
Auth::login($user);
return redirect('index/');
}
else{ // new Account.
$user = $this->registerUser($email,$name,$password,$facebook_id);
Auth::login($user);
return redirect('index/');
}
}
return redirect('/');
}
Check Email and facebook
private function checkExistUserByEmail($email)
{
$user = \App\User::where('email','=',$email)->first();
return $user;
}
private function checkExistUserByFacebookId($facebook_id)
{
$user = \App\User::where('facebook_id','=',$facebook_id)->first();
return $user;
}
Member Register
private function registerUser($email,$name,$password,$facebook_id)
{
$user = new \App\User;
$user->email = $email;
$user->name = $name;
$user->password = Hash::make($password); // Hash::make
$user->balance = 0;
$user->level = "member";
$user->facebook_id = $facebook_id;
$user->save();
return $user;
}
M Route file web.php
Route::get('login/facebook', 'Auth\LoginController#facebookAuthRedirect');
Route::get('login/facebook/callback', 'Auth\LoginController#facebookSuccess');
Clear route cache:
php artisan route:cache
and then check results

Login Page Hash issue UPDATE

I am having a issue with my login page reading a function to login
on my register page which I'm proud to say works perfect
this is my password hash code
$password = password_hash($password, PASSWORD_BCRYPT);
my login page has 2 fields
email &
password
I have re cleaned my code and solved the issue some what
functions are working
when I enter email and password it triggers
Warning! Email or Password Incorrect
plus an error at the top
Notice: Undefined index: password in C:\Program Files (x86)\Zend\Apache2\htdocs\CMS\functions\functions.php on line 249
this is line 249
$db_password = $row['password'];
/* Validate Login */
function validate_login()
{
$errors = [];
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$email = clean($_POST['email']);
$password = clean($_POST['password']);
if (empty($email)) {
$errors[] = "Email Required";
}
if (empty($password)) {
$errors[] = "Password Required";
}
if (! empty($errors)) {
foreach ($errors as $error) {
echo validation_errors($error);
}
} else {
if (login_user($email, $password)) {
redirect("../account/profile.php");
} else {
echo validation_errors("Email or Password Incorrect");
}
}
}
} // End Function
/* User Login */
function login_user($email, $password)
{
$sql = "SELECT user_pwd, uid FROM userss WHERE user_email = '" . escape($email) . "'";
$result = query($sql);
if (row_count($result) == 1) {
$row = fetch_array($result);
$db_password = $row['password'];
if (hash_algos($password) == $db_password) {
return true;
} else {
return false;
}
}
}// End Function
It looks like you are missing a closing bracket for your validate_login() function so it is defining the login_user() function only after the first function is called. Therefore as you progress through your validate_login() function you call the login_user() function before it is created since it is created after the if statement completes.
OK I just figured out the issue
if (hash_algos($password) == $db_password) {
return true;
} else {
return false;
}
changed it to this
if(password_verify($password, $db_password)){
return true;
} else {
return false;
}

Zend Gdata Calendar Event Update Not Sending Email Notification

Although the following code snippet does successfully add additional guests to a google calendar event, it is not sending them email notifications of the event. Can someone tell me if it's possible to also send an email to the new guests?
$service = Zend_Gdata_Calendar::AUTH_SERVICE_NAME; // predefined service name for calendar
$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service);
function sendInvite($eventId, $email)
{
$gdataCal = new Zend_Gdata_Calendar($client);
if($eventOld = $this->getEvent($eventId))
{
$who = $gdataCal->newwho();
$who->setEmail($email);
$eventOld->setWho(array_merge(array($who), $eventOld->getWho()));
try
{
$eventOld->save();
} catch(Zend_Gdata_App_Exception $e)
{
return false;
}
return true;
} else
return false;
}
function getEvent($eventId)
{
$gdataCal = new Zend_Gdata_Calendar($client);
$query = $gdataCal->newEventQuery();
$query->setUser('default');
$query->setVisibility('private');
$query->setProjection('full');
$query->setEvent($eventId);
try
{
$eventEntry = $gdataCal->getCalendarEventEntry($query);
return $eventEntry;
} catch(Zend_Gdata_App_Exception $e)
{
return null;
}
}
Finally figured it out.
public function sendInvite($eventId, $email)
{
$gdataCal = new Zend_Gdata_Calendar($this->client);
if($eventOld = $this->getEvent($eventId))
{
$SendEventNotifications = new Zend_Gdata_Calendar_Extension_SendEventNotifications();
$SendEventNotifications->setValue(true);
$eventOld->SendEventNotifications = $SendEventNotifications;
$who = $gdataCal->newwho();
$who->setEmail($email);
$eventOld->setWho(array_merge(array($who), $eventOld->getWho()));
try
{
$eventOld->save();
} catch(Zend_Gdata_App_Exception $e)
{
return false;
}
return true;
} else
return false;
}