Lumen - authentication with remember me option - authentication

Following the Lumen doc (http://lumen.laravel.com/docs/authentication), I'm successfully authenticating my website users with the following code :
if( Auth::attempt($request->only('email', 'password') ) ) {
// success
}
But I can't get the remember me functionnality working properly. This is my code :
$remember = (bool) $request->input('remember');
if( Auth::attempt($request->only('email', 'password'),$remember ) ) {
// success
}
And my database "users" table has a column named remember_token, which is a varchar(100) NULL (mysql).
The users are still being authenticated successfully but the remember_token is not filled (always null) and my users are not remembered.
How can I make it work?

Related

Can't handle HTTP multiple attribute values in Perl

I'm facing with a really strange issue. I interfaced a SAML authentication with OTRS which is an ITSM written in Perl and the Identity Provider sends the attributes as follow :
LoginName : dev-znuny02
mail : test2#company.dev
Profile : company.autre.idp.v2()
Profile : company.autre.mcf.sp(dev)
givenName : MyName
sn : Test2
I handle these with a module called Mod_Auth_Mellon and as you can see the attribute Profile is multivaluated. In short I retrieve all of these values with the following snippet :
sub new {
my ( $Type, %Param ) = #_;
# allocate new hash for object
my $Self = {};
bless( $Self, $Type );
$Self->{ConfigObject} = $Kernel::OM->Get('Kernel::Config');
$Self->{UserObject} = Kernel::System::User->new( %{$Self} );
# Handle header's attributes
$Self->{loginName} = 'MELLON_LoginName';
$Self->{eMail} = 'MELLON_mail';
$Self->{Profile_0} = 'MELLON_Profile_0';
$Self->{Profile_1} = 'MELLON_Profile_1';
$Self->{gName} = 'MELLON_givenName';
$Self->{sName} = 'MELLON_sn';
return $Self;
}
sub Auth {
my ( $Self, %Param ) = #_;
# get params
my $lname = $ENV{$Self->{loginName}};
my $email = $ENV{$Self->{eMail}};
my $profile0 = $ENV{$Self->{Profile_0}};
my $profile1 = $ENV{$Self->{Profile_1}};
my $gname = $ENV{$Self->{gName}};
my $sname = $ENV{$Self->{sName}};
...
}
I can handle all the values of the attributes except the attribute Profile. When I take a look to the documentation, they said :
If an attribute has multiple values, then they will be stored as MELLON_<name>_0, MELLON_<name>_1, MELLON_<name>_2
To be sure, I activated the diagnostics of the Mellon module and indeed I receive the information correctly :
...
MELLON_LoginName : dev_znuny02
MELLON_LoginName_0 : dev_znuny02
MELLON_mail : test2#company.dev
MELLON_mail_0 : test2#company.dev
MELLON_Profile : company.autre.idp.v2()
MELLON_Profile_0 : company.autre.idp.v2()
MELLON_Profile_1 : company.autre.mcf.sp(dev)
...
When I try to manipulate the MELLON_Profile_0 or MELLON_Profile_1 attributes in the Perl script, the variable assigned to it seems empty. Do you have any idea on what can be the issue here ?
Any help is welcome ! Thanks a lot guys
PS : I have no control on the Identity Provider so I can't edit the attributes sent
I didn't managed to make it work but I found a workaround to prevent users who don't have the Profile attribute value from logging into the application:
MellonCond Profile company.autre.mcf.sp(dev)
according the documentation :
You can also utilize SAML attributes to control whether Mellon authentication succeeds (a form of authorization). So even though the IdP may have successfully authenticated the user you can apply additional constraints via the MellonCond directive. The basic idea is that each MellonCond directive specifies one condition that either evaluates to True or False.

Xero Oauth2 Node Examples

I am doing some expermenting with the xero API, however i cant seem to get past the Connect to Xero returning an error
"Sorry, something went wrong
Go back and try again.
If the issue continues, check out our Status Page."
I have setup my App in the xero dev center
I have tried these 2 repos
https://github.com/XeroAPI/xero-node-oauth2-app
https://github.com/XeroAPI/node-oauth2-example
Both yeld the same result just an error page, no information in console/dev tools
Any help would be amazing as im completely stuck with this
So that looks like the error you get when either API keys and/or callback urls are not setup correctly.
Have you swapped in all your api keys & callback urls to the .env (environment) files?
Create a .env file in the root of your project & replace the 3 variables
Create an .env file in the root of your project using touch .env or edit the sample prefix off sample.env and change out with your /myapps credentials of the app you just made.
CLIENT_ID=...
CLIENT_SECRET=...
REDIRECT_URI=...
Here is the library that is used successfully with ouath2.0 tokenization. The token is expired in 30 mints. After that, we need to refresh the token with old token objects.
First set up an app in developer.xero.com.
Add Company Name and Redirect URL while creating the app.
Setup environment configuration in your file.
X_CLIENT_ID=CD43E78278ED4BE68F35F155C3E708F7
X_CLIENT_SECRET=IuP5TrE70JoyYiezMRM2KwvcHFYoLy3qRbD3NFlOkYLN0Asy
X_REDIRECT_URL=https://baseredirecturl.com/xero/default/redirect
Step-1: Here is the code for creating a token and refresh token.
public function actionConnectXero()
{
$session = Yii::$app->session;
$request = Yii::$app->request;
if (empty($request->get('code'))) {
// If we don't have an authorization code then get one
$authUrl = $this->provider->getAuthorizationUrl([
'scope' => 'offline_access openid email profile accounting.settings accounting.transactions accounting.contacts accounting.reports.read projects accounting.journals.read'
]);
//offline_access openid email profile accounting.settings accounting.transactions accounting.contacts accounting.reports.read projects accounting.journals.read
$session->set('oauth2state', $this->provider->getState());
$this->redirect($authUrl);
// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($request->get('state')) || ($request->get('state') !== $session->get('oauth2state'))) {
$session->remove('oauth2state');
exit('Invalid state');
} else {
// Try to get an access token (using the authorization code grant)
$token = $this->provider->getAccessToken('authorization_code', [
'code' => $request->get('code')
]);
$session->set('access_token', $token);
//If you added the openid/profile scopes you can access the authorizing user's identity.
$identity = $this->provider->getResourceOwner($token);
echo "<pre>";
print_r($identity);
//Get the tenants that this user is authorized to access
$tenants = $this->provider->getTenants($token);
print_r($tenants);
$session->set('tenantId', $tenants[0]->tenantId);
exit;
}
}
Step-2: Redirect to URL.
public function actionRedirectXero()
{
$request = Yii::$app->request;
$codeStr = explode("?", $request->getUrl());
$token = $this->provider->getAccessToken('authorization_code', [
'code' => $request->get('code')
]);
$tenants = $this->provider->getTenants($token);
$exits = XeroConfigs::find()->where(['created_by' => Yii::$app->user->identity->id])->one();
$xeroConf = $exits ? XeroConfigs::findOne($exits->id) : new XeroConfigs();
$xeroConf->access_token = $token;
$xeroConf->refresh_token = $token->getRefreshToken();
$xeroConf->expiry = $token->getExpires();
$xeroConf->tenant_id = isset($tenants[0]) ? $tenants[0]->id : 0;
$xeroConf->token_object = serialize($token);
$xeroConf->created_by = Yii::$app->user->identity->id;
$xeroConf->save();
$this->redirect('/xero/default/get-xero-data?'.$codeStr[1]);
}
Step-3: Get data from xero. I just save and get contacts. for more examples, you can check the package documentation.
public function actionGetXeroData(){
$configs = XeroConfigs::find()->where(['created_by' => Yii::$app->user->identity->id])->one();
if($configs->expiry < time()){
$newAccessToken = $this->provider->getAccessToken('refresh_token', [
'grant_type' => 'refresh_token',
'refresh_token' => $configs->refresh_token
]);
$tenants = $this->provider->getTenants($newAccessToken);
$xeroConf = XeroConfigs::findOne($configs->id);
$xeroConf->access_token = $newAccessToken;
$xeroConf->refresh_token = $newAccessToken->getRefreshToken();
$xeroConf->expiry = $newAccessToken->getExpires();
$xeroConf->tenant_id = isset($tenants[0]) ? $tenants[0]->id : 0;;
$xeroConf->token_object = serialize($newAccessToken);;
$xeroConf->updated_at = Carbon::now()->toDateTimeString();
$xeroConf->created_by = Yii::$app->user->identity->id;
$xeroConf->save();
$configs = XeroConfigs::find()->where(['created_by' => Yii::$app->user->identity->id])->one();
}
$tokenObj = unserialize($configs->token_object);
$tenants = $this->provider->getTenants($tokenObj);
$xero = new \XeroPHP\Application($tokenObj, $tenants[0]->tenantId);
$contact = new Contact($xero);
$contact->setName('Hassan Raza')
->setAccountNumber('0245541574185741')
->setContactID('852986')
->setGUID('52552548-5585-8715-8888-871222554154')
->setBankAccountDetail('0245541574185741')
->setTaxNumber('55545352')
->setContactStatus('ACTIVE')
->setSkypeUserName('hassan_raza2010')
->setTrackingCategoryName('Manager')
->setFirstName('Hassan')
->setLastName('Raza')
->setEmailAddress('hassan#xero.com');
$response = $contact->save();
dd($response->getResponseBody());

How to insert data in database after payment successful through instamojo

I have integrated instamojo payment api with my website on PHP.
I can also insert data into my database before payment api is called.
Now how can i insert data into my database after my payment is successful !
Thanks
You have to save this code as php file in your host and then set this file URL as web hook URL for Product/Payment link in Instamojo. You can also check whether this works on Web hook checking page in Instamojo.
<?php
/*
Basic PHP script to handle Instamojo RAP webhook.
*/
$data = $_POST;
$mac_provided = $data['mac']; // Get the MAC from the POST data
unset($data['mac']); // Remove the MAC key from the data.
$ver = explode('.', phpversion());
$major = (int) $ver[0];
$minor = (int) $ver[1];
if($major >= 5 and $minor >= 4){
ksort($data, SORT_STRING | SORT_FLAG_CASE);
}
else{
uksort($data, 'strcasecmp');
}
// You can get the 'salt' from Instamojo's developers page(make sure to log in first): https://www.instamojo.com/developers
// Pass the 'salt' without <>
$mac_calculated = hash_hmac("sha1", implode("|", $data), "<YOUR_SALT>");
if($mac_provided == $mac_calculated){
if($data['status'] == "Credit"){
// Payment was successful, mark it as successful in your database.
// You can acess payment_request_id, purpose etc here.
}
else{
// Payment was unsuccessful, mark it as failed in your database.
// You can acess payment_request_id, purpose etc here.
}
}
else{
echo "MAC mismatch";
}
?>

OpenFire: In an IQHandler, how to get the authenticated user that sent it?

I want to implement an IQHandler, but I want to make sure that only authenticated users can send IQ Packets to it. I want to make sure that the JID I get from Packet.getFrom() is the authenticated user that sent it.
I need this so that no one can just create an IQ Packet and set the "from" attribute to a user id other than their own. Can someone help me with this?
Try this:
ClientSession session = sessionManager.getSession(sender);
if(session.getStatus() == Session.STATUS_AUTHENTICATED) {
//YOUR STUFF HERE
}
UPDATE:
Looking closer at the source. It appears that the IQRouter already does this for you. If you are not authenticated the server response with an error stating just that.
public void route(IQ packet) {
if (packet == null) {
throw new NullPointerException();
}
JID sender = packet.getFrom();
ClientSession session = sessionManager.getSession(sender);
try {
// Invoke the interceptors before we process the read packet
InterceptorManager.getInstance().invokeInterceptors(packet, session, true, false);
JID to = packet.getTo();
if (session != null && to != null && session.getStatus() == Session.STATUS_CONNECTED &&
!serverName.equals(to.toString())) {
// User is requesting this server to authenticate for another server. Return
// a bad-request error
IQ reply = IQ.createResultIQ(packet);
reply.setChildElement(packet.getChildElement().createCopy());
reply.setError(PacketError.Condition.bad_request);
session.process(reply);
Log.warn("User tried to authenticate with this server using an unknown receipient: " +
packet.toXML());
}
else if (session == null || session.getStatus() == Session.STATUS_AUTHENTICATED || (
isLocalServer(to) && (
"jabber:iq:auth".equals(packet.getChildElement().getNamespaceURI()) ||
"jabber:iq:register"
.equals(packet.getChildElement().getNamespaceURI()) ||
"urn:ietf:params:xml:ns:xmpp-bind"
.equals(packet.getChildElement().getNamespaceURI())))) {
handle(packet);
}
else {
IQ reply = IQ.createResultIQ(packet);
reply.setChildElement(packet.getChildElement().createCopy());
reply.setError(PacketError.Condition.not_authorized);
session.process(reply);
}
// Invoke the interceptors after we have processed the read packet
InterceptorManager.getInstance().invokeInterceptors(packet, session, true, true);
}

FOSUserBundle: Custom password / Migration from old DB structure

I want to move to Symfony2, because I am totally impressed by its modernity and good programming.
Now I am taking a users table from my old system, with 10,000 users, and I don't want to anger them by making them set a new password....so I want them to be able to login with their old password
Here is pseudo-code of how my users table looks like with 3 major fields concerning login/signup:
id, int(10) unsigned NOT NULL
username varchar(40) NOT NULL
passhash varchar(32) NOT NULL
secret varchar(20) NOT NULL
on signup, the data gets generated this way:
$secret = mksecret ();
$passhash = md5 ($secret . $password_formfield . $secret);
on login, the data gets checked the following way:
if ($row['passhash'] != md5 ($row['secret'] . $password_formfield . $row['secret']))
{
//show login error
}
So how do I handle it best in FOSUserBundle, without having to edit too many files?
You need to create a custom password encoder:
<?php
use Symfony\Component\Security\Core\Encoder\BasePasswordEncoder;
class MyPasswordEncoder extends BasePasswordEncoder
{
public function encodePassword($raw, $salt)
{
return md5($salt.$raw.$salt);
}
public function isPasswordValid($encoded, $raw, $salt)
{
return $this->comparePasswords($encoded, $this->encodePassword($raw, $salt));
}
}
And configure it in security.yml:
services:
my_password_encoder:
class: MyPasswordEncoder
security:
encoders:
FOS\UserBundle\Model\UserInterface: { id: my_password_encoder }
As long as User::getSalt() returns secret and User::getPassword() returns passhash you should be good to go.
It is very easy to do with FOSUserBundle. This is the code for it:
$userManager = $this->get('fos_user.user_manager');
foreach ($items as $item) {
$newItem = $userManager->createUser();
//$newItem->setId($item->getObjId());
// FOSUserBundle required fields
$newItem->setUsername($item->getUsername());
$newItem->setEmail($item->getEmail());
$newItem->setPlainPassword($item->getPassword()); // get original password
$newItem->setEnabled(true);
$userManager->updateUser($newItem, true);
}