How to authenticate user with firebase sdk - codeigniter

I am using this SDK and following this documentation. Now I am trying to create and authenticate user in firebase db. How can I do that.I am doing the project in Codeigniter and in my controller I did this:
public function register()
{
$firebase = (new Firebase\Factory())->create();
$tokenHandler = $firebase->getTokenHandler();
$uid = 'a-uid';
$claims = ['foo' => 'bar']; // optional
// Returns a Lcobucci\JWT\Token instance
$customToken = $tokenHandler->createCustomToken($uid, $claims);
echo $customToken; // "eyJ0eXAiOiJKV1..."
$idTokenString = 'eyJhbGciOiJSUzI1...';
// Returns a Lcobucci\JWT\Token instance
$idToken = $tokenHandler->verifyIdToken($idTokenString);
$uid = $idToken->getClaim('sub');
echo $uid; // 'a-uid'
}
and I call the function It gave me this error:
Type: Kreait\Firebase\Exception\ServiceAccountDiscoveryFailed
Message: Kreait\Firebase\ServiceAccount\Discovery\FromEnvironmentVariable: The environment variable "FIREBASE_CREDENTIALS" is not set. Kreait\Firebase\ServiceAccount\Discovery\FromEnvironmentVariable: The environment variable "GOOGLE_APPLICATION_CREDENTIALS" is not set. Kreait\Firebase\ServiceAccount\Discovery\FromGoogleWellKnownFile: The well known file is not readable or invalid
Filename: E:\xampp\htdocs\firebasedb\vendor\kreait\firebase-
php\src\Firebase\ServiceAccount\Discoverer.php
Line Number: 48
Can anyone help me with this issue? Any kind of help are appreciated. Thanks.
EDIT
Okay I solve this problem with default .json file path like this:
$serviceAccount = ServiceAccount::fromJsonFile(JSON_FILE_PATH.'google-service-account.json');
$firebase = (new Factory)
->withServiceAccount($serviceAccount)
->create();
Now can I register a new user from web-app? Can anyone Help please. I have been stopped in this problem since long. Helps are highly appreciated.

You Set JSON Key environment variables
FIREBASE_CREDENTIALS GOOGLE_APPLICATION_CREDENTIALS ?
try reading this Firebase Admin SDK for PHP Setup

From the documentation https://firebase-php.readthedocs.io/en/latest/authentication.html#authenticate-with-admin-privileges
There two crucial points to note.
Many use cases for verifying ID tokens on the server can be accomplished by using Security Rules for the Firebase Realtime Database and Cloud Storage. See if those solve your problem before verifying ID tokens yourself.
The ID token verification methods included in the Firebase Admin SDKs are meant to verify ID tokens that come from the client SDKs, not the custom tokens that you create with the Admin SDKs Check out https://firebase.google.com/docs/auth/users/#auth_tokens
About Users:
From https://firebase-php.readthedocs.io/en/latest/user-management.html
You have a sample
$request = \Kreait\Auth\Request\CreateUser::new()
->withUnverifiedEmail('user#example.com')
->withPhoneNumber('+15555550100')
->withClearTextPassword('secretPassword')
->withDisplayName('John Doe')
->withPhotoUrl('http://www.example.com/12345678/photo.png');
$createdUser = $auth->createUser($request);
Please Note:
By default, Firebase Authentication will generate a random uid for the new user. If you instead want to specify your own uid for the new user, you can include in the properties passed to the user creation method:
$properties = [
'uid' => 'some-uid',
// other properties
];
$request = \Kreait\Auth\Request\CreateUser::new()
->withUid('some-uid')
// with other properties
;

I had same problem with Laravel in my case, here is the solution:
First save the .json credentials file you got from Firebase project into the root of your Laravel app on the same level as .env file.
The json file looks like you-file-firebase-adminsdk-0000-9845985498a.json
Then open the .env file and create a new environment variable and paste the json credential file name.
FIREBASE_CREDENTIALS=../you-file-firebase-adminsdk-0000-9845985498a.json

Related

Acessing auth user attribute

I am in the guzzle controller making a request to an external api.
I wanna use an id from the user who is logged in.
I have been doing the request with a static id, but now i want it dynamically.
I tried like this:
$science = Auth::user()->science_id;
$client = new Client(['headers' => ['Accept' => 'application/json']]);
$request = $client->get(
'https://url_to_the_api/'.$science.'/degree',
[
'auth' => ['client', 'secret'],
]
);
$data = $request->getBody()->getContents();
return $data;
And i have the error
500(internal server error)
and this message:
"Trying to get property 'science_id' of non-object"
What am i missing?
Thanks for your time
If you are using it in web app then make sure you first check if user is already authenticated by using auth middleware or manually by using Auth::check() function.
Or
If you are trying to hit this by api that will not work here because session will not be maintained in that case. That's why JWT tokens were introduced to maintain the state of an application.
I've solved it like this:
$science = auth('api')->user()->science_id;
Thanks for the help!

How to Check if Session is set in Laravel 5.7

<?php
$request = request();
// if (empty($request)) return false; .// That does not work
$loggedUserAccessGroups = $request->session()->get('loggedUserAccessGroups');
$logged_user_ip = $request->session()->get('logged_user_ip');
In my Laravel 5.7 application, I want to check if the user has the right access level in the session. It works ok but I made automatic tests and got the error:
local.ERROR: Session store not set on request.
I added checks to see if the session is set and it fails to return false.
Which is the correct way? Thanks!
You may also use the global session PHP function to retrieve and store data in the session as outlined here:
// Retrieve a piece of data from the session with the global session helper...
$loggedUserAccessGroups = session('loggedUserAccessGroups');
$logged_user_ip = session('logged_user_ip');
// Store a piece of data in the session...
session(['key' => 'value']);
For more information look at the section of The Global Session Helper in the official documentation.

Parse.com Cloud Code - Why is useMasterKey() required for creating and saving objects

I'm trying to create and save a new object when a new account is created. I'm using the following code.
Parse.Cloud.afterSave(Parse.User, function(request) {
var userDataObjectId = request.object.get("userDataObjectId");
if(!userDataObjectId) {
console.log("NEW USER");
var userData = new Parse.Object("UserData");
userData.save(null, {
success: function(userData) {
console.log("SUCCEEDED SAVING USERDATA");
},
error: function(userData, error) {
}
});
}
});
I get the "NEW USER" log output but the only way to make sure the UserData object is saved is to add Parse.Cloud.useMasterKey().
I don't understand why the Master key is necessary to create and save an object that I haven't put any Class Level Permissions on, and when even clients can create and save objects without any issue!
I haven't seen anything related to the master key being required for creating and saving objects of normal classes. Could anybody clear this up for me please? Thanks a lot!
EDIT: Following Russel's instructions, I got the following output in the userData save error.
##################################################
# Alert #
##################################################
# #
# Error: 209 invalid session token #
# #
# [ OK ] #
# #
##################################################
I searched for this particular error and tried reinstalling the app (Android) like suggessted in some of the SO posts. This didn't help. Also I already had "Require Revocable Sessions" option enabled, if that's relevant.
A user cannot change User objects other than its own. In this case, there is no logged in user (currentUser), so you can't save it directly and therefore must useMasterKey.
Have a look at signup in the Android guide: https://parse.com/docs/android/guide#users-signing-up

Magento "Forgot Password" email sent in wrong language

I have a Magento site with multiple languages. I have setup the language packs and everything seems to translate properly on the website. Also the transactional e-mails are sent in the correct language EXCEPT for the "Forgot Password" e-mail which is always sent in German. Here's what I did:
Installed language packs and made sure all templates and folder structures are correct. Example: /app/locale/nl_NL/template/email/
Under System » Transactional Emails: I applied the template, chose the locale and saved.
Then I went to System » Configuration » Sales Emails, I switched to each language from the "Current Configuration Scope" dropdown, and I chose the templates I created in Transactional Emails for each language (each store view).
After looking around online for a solution, it seems others had this problem too and someone mentioned that Magento is picking the "Forgot Password" template from the first locale folder found in /app/locale/. In my case I had: de_DE, en_US, fr_FR, nl_NL. So It picks the template from the German de_DE pack.
NOTE: Also, in the backend under "Configuration" there's a tab on the left called "LOCALE PACKS" which only has "Locale de_DE" under it, even though I have other language packs which don't show up here. Not sure if this is relevant.
Site: http://site1.cp1.glimworm.com/magento/
Magento Community version: 1.7.0.2
Locale packs:
Mage_Locale_en_US
Locale_Mage_community_de_DE
Locale_Mage_community_fr_FR
Mage_Locale_nl_NL
Any idea how I can get the correct email template from the corresponding language to be sent as opposed to always German? Any help will be greatly appreciated! I can provide more info as well.
I have same problem in magento v1.5. After a long research i found this solution and its working for me.
Mage/Customer/Model/Customer.php
in this file i have make some changes as following.
find this line of code
if (!$storeId)
{
$storeId = $this->_getWebsiteStoreId($this->getSendemailStoreId());
}
and replace with
$storeId = ($storeId == '0')?$this->getSendemailStoreId():$storeId;
if ($this->getWebsiteId() != '0' && $storeId == '0')
{
$storeIds = Mage::app()->getWebsite($this->getWebsiteId())->getStoreIds();
reset($storeIds);
$storeId = current($storeIds);
}
I had the same problem, and it looks like user2282917's solution works with a little modify:
You should edit the sendPasswordResetConfirmationEmail function in the Customer.php not the sendNewAccountEmail. Try to replace the code there, and it will working.
Overwrite the forgotPasswordPostAction controller on the AccountController.php.
You need to set the correct store id so that the locale will be used.
/**
* Forgot customer password action
*/
public function forgotPasswordPostAction()
{
$email = (string) $this->getRequest()->getPost('email');
if ($email) {
if (!Zend_Validate::is($email, 'EmailAddress')) {
$this->_getSession()->setForgottenEmail($email);
$this->_getSession()->addError($this->__('Invalid email address.'));
$this->_redirect('*/*/forgotpassword');
return;
}
/** #var $customer Mage_Customer_Model_Customer */
$customer = $this->_getModel('customer/customer')
->setWebsiteId(Mage::app()->getStore()->getWebsiteId())
->loadByEmail($email);
if ($customer->getId()) {
try {
$newResetPasswordLinkToken = $this->_getHelper('customer')->generateResetPasswordLinkToken();
$customer->changeResetPasswordLinkToken($newResetPasswordLinkToken);
// Add store ID so that correct locale will be set
$customer->setStoreId(Mage::app()->getStore()->getId());
$customer->sendPasswordResetConfirmationEmail();
} catch (Exception $exception) {
$this->_getSession()->addError($exception->getMessage());
$this->_redirect('*/*/forgotpassword');
return;
}
}
$this->_getSession()
->addSuccess( $this->_getHelper('customer')
->__('If there is an account associated with %s you will receive an email with a link to reset your password.',
$this->_getHelper('customer')->escapeHtml($email)));
$this->_redirect('*/*/');
return;
} else {
$this->_getSession()->addError($this->__('Please enter your email.'));
$this->_redirect('*/*/forgotpassword');
return;
}
}
In the below file
Mage/Customer/Model/Customer.php
In sendPasswordResetConfirmationEmail function() change the
$storeId = $this->getStoreId();
to
$storeId = Mage::app()->getStore()->getStoreId();
Thanks
In our case... We found that when a Customer Account was created by Admin the "email send from" option was not saved and only used for the first account creation email. Any subsequent email sent are sent from the default store view of the website the customer was allocated.
The real problem is how, when the customer store id is identified when none is set.
The method sendPasswordResetConfirmationEmail (Magento 1.9.1) when the store id is 0 (admin or not set), defaults to _getWebsiteStoreId which will return the first store id associated to that website.
The problem is that Magento assumes the first store id associated with the website id is the default store... We found this is not the case when a Sort Order is set against the store record.
Simply put make sure your default store assocaited with a web site is also specified with a sort order of 0.
Hope this link will be usefull to you
In link they have used New Password but Instead of New Password Use Forgot Password template In step 4
Thanks..
The password reset email is send in Mage_Customer_Model_Customer::_sendEmailTemplate(). Here the emailtemplate is loaded. If it was loaded in admin in "Systemn > Transactional Emails" and configured to be used, your template will be used.
Else the default template is loaded from file in Mage_Core_Model_Email_Template::sendTransactional. This is done using $this->loadDefault($templateId, $localeCode); The template ist loaded using
$templateText = Mage::app()->getTranslator()->getTemplateFile(
$data['file'], 'email', $locale
);
Here locale folders are checked in following order:
Specified locale
Locale of default store
en_US locale
The first matched locale is chosen. As Mage::app() doesn't know about the store which was passed with the emailtemplate, the default defaultstore is loaded, which is german in your case. It has nothing to do with the order of the locale folders.
So in your case I suggest to check if your emailtemplate is selected in admin configuration in "System > Config > Customerconfiguration > Password Options" or use Mage::getStoreConfig(Mage_Customer_Model_Customer::XML_PATH_REMIND_EMAIL_TEMPLATE, $storeId) if it is set for your store.
The reason for why you are receiving the email templates in another language than the one expected is dependent of the language in which you first created your account. Try to check this to be in your own language when you first created the account.
Check this under Customers> Account Information to see how your account was created.
/Kalif

Problem getting codeigniter library for google reader to work when trying to log in and get feed data

I'm trying to getting this http://www.forgottenexpanse.com/projects/ci_reader CodeIgniter library for interacting with Google Reader to work.
When following the examples on the page, this works fine:
$this->load->library('reader');
$shared_items = $this->reader->shared_items('12006118737470781753');
foreach ($shared_items['items'] as $entry) {
echo $entry['title'];
}
But when trying to grab non-public data by loging in:
$this->load->library('reader');
$credentials = array('email' => 'me#gmail.com', 'password' => 'mypassword');
$this->reader->initialize($credentials);
$shared_items = $this->reader->shared_items();
foreach ($shared_items['items'] as $entry) {
echo $entry['title'];
}
I get a bunch of warnings related to line 454 of libraries/Reader.php, like this one:
Message: simplexml_load_string(): Entity: line 128: parser error : StartTag: invalid element name
I'm hoping someone has an idea what might be happening here.
Thanks much!
The library you point to still uses the SID cookie to authenticate with Reader. That was deprecated a few months ago. The new preferred authentication schemes are either OAuth or ClientLogin with an authentication token; both are described at http://code.google.com/p/google-reader-api/wiki/Authentication.
In this particular case, you'll have to modify the _login function to get the Auth token out of the ClientLogin response. Once you have it, you'll also need to modify the _fetch function to include it as the Authorization header (instead of adding the cookie).

Resources