Zend_Auth login using either username or email as identityColumn - zend-framework

I'm using Zend_Auth with a "Database Table Authentication". What I want to do is allow the user to login with either a username or email address as the "identityColumn". How would I allow both. I'm stuck.

Extend and implement your own Auth Adapter and use query like "WHERE username = ? or email = ?" to get Auth result :)

Authenticate twice (if needed) with 2 different Zend_Auth_Adapter_DbTable objects and add some logic to determine if the login is username or email by guessing if what type of login user provided so that you save one query for most of the cases.

I know this is not the cleanest Zend_Auth implementation, but it works. The only problem comes if someone registers with an different email address as a username, but of course you can prevent this in your registration form. Hope it helps.
// if the entered value validates as an email address then use the 'email' field
// if not, use the 'username' field
$validator = new Zend_Validate_EmailAddress();
if ($validator->isValid($form->getValue('password'))) {
$identityField = 'email';
} else {
$identityField = 'username';
}
$authAdapter = new Zend_Auth_Adapter_DbTable(
$dbAdapter,
'users',
$identityField,
'password',
'SHA1(?)'
);
$authAdapter->setIdentity($form->getValue('username'))
->setCredential($form->getValue('password'));

Related

Pre-condition not working

I'm trying to create a simple 'signup' method.
-- Creates a new account
public signup: String * String ==> ()
signup(username, password) == (
-- create user
dcl user: User := new User(username, password);
-- add user
users := users union {user};
)
pre (let u in set users in u.username <> username);
The problem I'm having is with the pre-condition. How can I write the pre-condition 'username is unique'? (ie there is no user in users where user.username = username)
Note: users is a set of User
Edit: pre (username not in set users.username) is what makes most sense to me, but this doesn't even compile.
It looks like you need a "forall". Your precondition wants to say that "for all of the users' usernames, the new user's name is not equal to them". An alternative would be to generate the set of existing usernames with a set comprehension, and then say the new username is not in that set.
Let us know if the syntax for the above isn't obvious.

How to check if email exist in data base yii2 basic

How I can check if an email exist in the data base in yii2 basic , I connect the database with the framework,but need help ,how to check this (its needed for the forgot password (form) )
assuming the the email you are looking for is in $email_to_check and the ActiveRecord is YourClass should be somethings like this
$model = YourClass::find()->where(['email'=> $email_to_check]);
If (isset($model)) {
// then your email exists
}
could be
$modelUser = User::find()->where(['email'=> $email_to_check]);
If (isset($modelUser)) {
// then the User with your email exists
}

Why does the Spring Social plugin occasionally return an empty email on the User class?

I have a Grails project (v2.4.2) that is making use of the spring-security-facebook:0.17 plugin to authenticate via Spring Security. At first sight, all seems well. However, there is a large set of users that for some unknown reason I cannot access their email address. I am using spring social to grab the email. I have permission and it is set in the scope. Here is a code snippet where I authenticate a new user:
log.info("Create domain for facebook user $token.uid")
//Use Spring Social Facebook to load details for current user from Facebook API
log.info("create: FacebookAuthToken: $token")
log.info("created FacebookAuthToken.FacebookAccessToken = ${token.accessToken}")
Facebook facebook = new FacebookTemplate(token.accessToken.accessToken)
org.springframework.social.facebook.api.User fbProfile = facebook.userOperations().getUserProfile()
// Check if email is actual granted because in production some are coming back null
boolean isEmailGranted=false
List<Permission> permissions = facebook?.userOperations()?.getUserPermissions()
String permissionString = "["
for (int i=0;i<permissions.size();i++) {
permissionString += "["+ permissions[i].getName() + ":" + permissions[i].getStatus()+"]"
if (permissions[i].getName()=="email" && permissions[i].isGranted())
isEmailGranted=true
}
permissionString += "]"
log.info("create: Facebook Permissions = " + permissionString)
def grailsWebRequest = WebUtils.retrieveGrailsWebRequest()
def flash = grailsWebRequest.flashScope
if (!isEmailGranted) {
log.warn("create: Unable to subscribe facebook user because email priviledge was not granted.")
flash.message = 'Login to Facebook failed. We must have access to your email address in order to proceed with login.'
throw new InsufficientAuthenticationException("Facebook email not accessible")
}
log.info("created: ")
String email = fbProfile.getEmail()
String firstName = fbProfile.getFirstName()
String lastName = fbProfile.getLastName()
String fullName = fbProfile.getName()
String username = firstName
String password = token.accessToken.accessToken
if (!email) {
log.error("create: Permission was granted to use facebook email but the value is null.")
flash.message = 'Login to Facebook failed. We are temporarily unable to access your email although permission has been granted'
throw new InsufficientAuthenticationException("Facebook email not accessible for unknown reason")
}
Why would I receive an empty email when permission has been granted? Is there a preferred method for handling this behavior (other than failing the authentication and making up a fake email address). Many thanks!
The documentation for the 'email' field of the 'user' object ( https://developers.facebook.com/docs/reference/api/user/ ) clarifies the expected behaviour here, which is:
"this field will not be returned if no valid email address is available"
There is a detailed explanation about different situations where an email won't be sent. Please check it out:
https://developers.facebook.com/bugs/298946933534016/
I hope it helps.

Joomla JUser getinstance Questions

I am attempting to make an authentication plugin. JUser::getInstance() takes one input, and it is supposed to be the id. Is there any way to get an instance of a User using some other indentifier? such as username, email etc.
Probably there isnt any such method. But yes if you are sure that username or email are unique then you can modify your file user.php in libraries/joomla/user/ and add a method there.
getInstanceByEmail($email)
{
$query = "select id from jos_users where email=".email;
// use the code to get the id;
return getInstance($id);
} // this is just a sample code of how it can be achieved
Since Joomla's own authentication is done by checking the user's username (and password of course), it has to be unique. And yes you can do something like what #Rixius suggested.
Here's my version:
// Get a database object
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('id, password');
$query->from('#__users');
$query->where('username=' . $db->Quote($credentials['username']));
$db->setQuery($query);
$result = $db->loadObject();
$user = JFactory::getUser();
if ($result)
{
$user = JUser::getInstance($result->id);
}

Use default credentials in order to call DirectoryEntry

I am working in a Login page and teh logic is like ->
try
{
DirectoryEntry LDAPLogin = new DirectoryEntry(ConfigurationSettings.AppSettings ["LDAPPath"].ToString(), Usuario, Txt_Contrasenia.Text.ToString());
if (LDAPLogin.NativeGuid != LDAPLogin.Name)
ValidarGrupo();
}
catch (Exception exc)
{
Label_Info.Text = "Sus credenciales no son validas: " + Usuario.ToString() + " " + exc.Message;
}
If the user enters the rights credentials I call a method ValidarGrupo that implements a lookup in the AD for a group of the user
I would like to replace the username and password with UseDefaultCredentials in order to avoid that the user has to enter the username and password and the Login pages use the credentials of the user that is login on the machine.
I would like to replace the username
and password with
UseDefaultCredentials in order to
avoid that the user has to enter the
username and password and the Login
pages use the credentials of the user
that is login on the machine.
So you basically want to check whether the currently logged in user is valid?
I believe you can just simply create the DirectoryEntry without specifying any username/password - in that case, System.DirectoryServices will automatically use the current user credentials:
string ldapPath = ConfigurationSettings.AppSettings ["LDAPPath"];
DirectoryEntry LDAPLogin = new DirectoryEntry(ldapPath);
That should be enough, I believe!