How can i login using email address in zend? - zend-framework

I have the situtation like , Admin should login as User from Admin End. I have user email address which is username for my site.
I am using following code in login page.
...
$users = new Default_Model_DbTable_Users();
$auth = Zend_Auth::getInstance();
$auth = Zend_Auth::getInstance();
$authAdapter = new Zend_Auth_Adapter_DbTable($users->getAdapter(),'customers');
$authAdapter->setIdentityColumn('email')->setCredentialColumn('password');
$authAdapter->setIdentity($username)->setCredential(base64_encode($password));
$authAdapter->getDbSelect()->where('status = 1');
$result = $auth->authenticate($authAdapter);
.....
Now I have to use only email address to login. I can check whether ADMIN do the user login from admin end. Is it possible to login using email address ?. Kindly advice on this

If you would like to allow admin to log in as any user from the admin panel, you don't have to use Zend_Auth::authenticate() to check any credentials against the database. All you really need to do is set up the identity like you do for a normal user login.
From admin you might do something like this:
$user = getUserInfoFromDatabase(); // get the user object used for Zend_Auth identity
$auth = Zend_Auth::getInstance()->getStorage()->write($user);
// redirect admin to user frontend
The only important thing is that whatever you write() to the storage, must be the EXACT same object/data you write to storage from your user login code.
It doesn't matter how the data gets there, as long as it is what your application requires to check identity.
Since your admin has already been authenticated and has permission to access a user account, you don't need to use Zend_Auth::authenticate() to validate the user email/password, you can skip that step and simply assign the identity for the admin directly to the session.
You may need to use separate session namespaces for admin and users if you are not already.
Hope that helps, let me know if I can clarify anything. The part where you set the identity is probably short after $result = $auth->authenticate($authAdapter); in your code, probably inside if ($result == true)

Related

Keycloak : implement "reset password" (as admin) flow same as "forgot password" (as user)

I would like to implement this authentication flow in Keycloak:
A user creates an account by typing only his email
The user is logged in and can access my service
2'. At the same time, an email is sent to him, allowing him to "finalize" his account
The user leaves his session -> to reuse my service, he must click in the received email
By clicking in the received email, the user defines his first password
The user is then logged in automatically (without going through a login page).
The objective of this flow is to be the simplest, to hook users who are not used to webapps.
The implementation I would do:
Create an account without password request: I customize the Keycloak Registration flow by disabling the Password Validation and Profile Validation rules
Programmatically, in my webapp, at the first connection of a user, via the REST Admin API, I trigger the email action UPDATE_PASSWORD
I get something that works, but:
A. The link received by email redirects to an intermediary page confirming the execution of actions ("Perform the following action (s)") - (similar to Keycloak Implement Reset password flow same as forgot password flow)
B. The user is then redirected to a login page, and not directly connected to the application.
When, as a normal user, I trigger a reset password request (through 'forget password' feature), the process is the one I want: by clicking on the email link, I go directly to the page allowing me to enter and confirm a new password, then I'm authenticated.
My question: Do you see a way to implement this 'simplified' flow?
My keycloak version : 11.0.2
Thank you !
I could remove the "info.ftl" page display, customizing the "ExecuteActionsActionTokenHandler", as explained here :
action-token-spi
You have to create a file :
src/main/resources/META-INF/services/org.keycloak.authentication.actiontoken.ActionTokenHandlerFactory
containing the name of the class you want to use instead :
com.example.ExecuteActionTokenHandlerFactory
Then you create that class com.example.ExecuteActionTokenHandlerFactory with the following code :
public class ExecuteActionTokenHandlerFactory extends ExecuteActionsActionTokenHandler {
#Override
public Response handleToken(ExecuteActionsActionToken token, ActionTokenContext<ExecuteActionsActionToken> tokenContext) {
AuthenticationSessionModel authSession = tokenContext.getAuthenticationSession();
String redirectUri = RedirectUtils.verifyRedirectUri(tokenContext.getUriInfo(), token.getRedirectUri(),
tokenContext.getRealm(), authSession.getClient());
if (redirectUri != null) {
authSession.setAuthNote(AuthenticationManager.SET_REDIRECT_URI_AFTER_REQUIRED_ACTIONS, "true");
authSession.setRedirectUri(redirectUri);
authSession.setClientNote(OIDCLoginProtocol.REDIRECT_URI_PARAM, redirectUri);
}
token.getRequiredActions().stream().forEach(authSession::addRequiredAction);
UserModel user = tokenContext.getAuthenticationSession().getAuthenticatedUser();
// verify user email as we know it is valid as this entry point would never have gotten here.
user.setEmailVerified(true);
String nextAction = AuthenticationManager.nextRequiredAction(tokenContext.getSession(), authSession, tokenContext.getClientConnection(), tokenContext.getRequest(), tokenContext.getUriInfo(), tokenContext.getEvent());
return AuthenticationManager.redirectToRequiredActions(tokenContext.getSession(), tokenContext.getRealm(), authSession, tokenContext.getUriInfo(), nextAction);
}
}
Actually it is the same implementation as the upper class, except we removed the following part :
if (tokenContext.isAuthenticationSessionFresh()) {
...
}
which means that if the user did not have a session, which happens when the user is reseting his password, he is redirected to that "info.ftl" page.
As a workaround for problem A, I customize info.ftl template page. I add an ugly inline script to click on the link, redirecting automatically to the update password page.
<#import "template.ftl" as layout>
(...)
<#elseif actionUri?has_content>
<p><a id="yolo" href="${actionUri}">${kcSanitize(msg("proceedWithAction"))?no_esc}</a></p>
<script>document.getElementById('yolo').click()</script>
(...)
It'll do the job until I found a cleaner solution.
At the moment, B problem remains.

how to login in magento admin using coding

Hi magento geeks i need your help,
i'm adding product from backend code in my magneto server, i want to set admin session when product creating then only it will we shown in both front and back end now its working fine for setting admin session id manually.
now i want to set admin session according to admin login based, of-course i will give admin username and password since i will get current logged in user id.
what i want is login magento admin using coding.
any help would be great!
Finally i found solution for this question
Mage::getSingleton('core/session', array('name' => 'adminhtml'));
// supply username
$user = Mage::getModel('admin/user')->loadByUsername('Admin_name_to_login'); // user your admin username
if (Mage::getSingleton('adminhtml/url')->useSecretKey()) {
Mage::getSingleton('adminhtml/url')->renewSecretUrls();
}
$session = Mage::getSingleton('admin/session');
$session->setIsFirstVisit(true);
$session->setUser($user);
$session->setAcl(Mage::getResourceModel('admin/acl')->loadAcl());
Mage::dispatchEvent('admin_session_user_login_success',array('user'=>$user));
if ($session->isLoggedIn()) {
echo "Logged in";
}
else{
echo 'Not Logged';
}
?>

Getting current user ID in page tab

I'm trying to find the ID of the user visiting my page tab (without having to make him authentify before using the page)
I've tried several methods:
$requete_fb = $facebook->api('/me');
$me = $facebook->api('me', array('fields' => 'username'));
$request = $facebook->getSignedRequest();
$uid = $facebook->getUser();
But all of them did not work (getUser returns me 0, the others PhP errors.)
So how can I do that? I'm not trying to break the TOS, I'm trying to fetch basic information (the locale).
Any other way to do it?
It is not possible to get a user_id without the user's permission:
The user_id and oauth_token will only be passed if the
user has authorized your app.
However the locale is available in the user object. Please see Signed Request for more information.

zend facebook auth overwriting local login storage

I have an app with a local login system. What I am trying to do is allow the user to connect their facebook account to their account. I am using Zend Auth for my main local login and a facebook auth by Michael Krotscheck.
I can connect with facebook fine but because I am using Zend_Auth the facebook data is over writing the main local login storage. All I need is the users email and facebook id and insert them into my users table.
The code below shows how it all works, I do not know another alternative than using Zend Auth for the facebook login. Anybody had the same issues? Advice would be very helpful.
$auth = Zend_Auth::getInstance();
$adapter = $this->_getFacebookAdapter();
$result = $auth->authenticate($adapter);
if ($result->isValid()) {
$toStore = array('identity' => $auth->getIdentity());
// for facebook
$msgs = $result->getMessages();
$toStore['properties'] = (array) $msgs['user'];
$toStore['provider'] = "facebook";
$auth->getStorage()->write($toStore);
$this->_helper->FlashMessenger('Successful authentication');
//return $this->_redirect('/index/index');
// Check if the User is in our dB
//$users = new My_Model_Users();
//$userTrue = $users->checkUserExists($userId,$providerName);
Zend_Debug::dump($toStore);
Zend_Debug::dump($this->_helper->user());
} else {
$this->_helper->FlashMessenger('Failed authentication');
$this->_helper->FlashMessenger($result->getMessages());
//return $this->_redirect('/index/index');
}
J
After more trawling stackoverflow I found a solution.
Multiple Instances (2) of Zend_Auth
Basically created my own Auth class and removed the singleton pattern in Zend_Auth, this allowed me to create another instance.
J

Login using facebook connect question

I want to implement facebook connect on my site. I have used the oauth api to obtain a permissions request for the app.
However, I am having the following problem.
If a user signs into my site for the first time using facebook connect, i need to create a new username / password for him (on my site) to be able to surf my site and have all the session variables set. However, what should i use as the username / password ?
I understand that a facebook user can change his email address.
How do i handle users who are logging in using facebook connect for the second or third time (who are already members of my site) ? I need not create a user for them on my site as its already created when he logged in for the first time. Do i check for email address to see if the facebook user's email address exists in the database ? Also, comes the same problem that a facebook user can change his email address.
What is the one thing that does not change for a facebook user that i can use for his username ? Also, what do i use for his password ? Also, i understand that if i use username/password from available app data, then using normal mechanism a user can login to my site too. How do i prevent this security hole ?
Please help.
I use the information that facebook send in the callback (facebook unique user id or normal id)and then check if the user is on my database, if not i insert him but i leaving blank the othe rstuff like password or user email (also you can request that info too check the line 418 in the php api and add "'req_perms' => 'email',")because i can retrive that data when they connect again and then set the sessions like allways.
if the users change teh email just check that on every login and update the data.
example:
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'cookie' => true,
));
$session = $facebook->getSession();
$me = null;
// Session based API call.
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
}
// login or logout url will be needed depending on current user state.
if ($me) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
if ($me) {
if (!isset($_SESSION["usr_id"])){
$_SESSION["usr_id"] =$me['id'];
$_SESSION["usr_name"]=$me['name'];
// or do your sql verification and then set the sessions
}
}
/////////////////////////////////////////////
Facebook offers user's unique ID. You can recognize user with this information.