Login/Password authentication in Secure Social

In another post I wrote about how to configure secure social to log in using a
social network. In this one, I am gonna walk through another common scenario,
setup a login/password based authentication. You need to understand a few things to put
everything in order. Let’s go!

If you don’t know anything about secure social, click in the link above and
spend a few minutes to read the other post about how to setup secure social :).
The first thing you have to change is the provider used in the configuration file,
usually called securesocial.conf. You need to use the userpass
entry in order to configure some aspects of your authentication.

    userpass {
    	withUserNameSupport=false
    	sendWelcomeEmail=false
    	enableGravatarSupport=true
    	signupSkipLogin=true
    	tokenDuration=60
    	tokenDeleteInterval=5
    	minimumPasswordLength=8
    	enableTokenJob=true
    	hasher=bcrypt
    }

The most strange key, at least for me, is the first one. The withUserNameSupport tells to Secure Social to use the user name instead of the email as the login for the
application. Maybe the keys about tokens are not clear right now, but wait a little and everything will be solved.

Another part that must be changed is the plugin’s file. We need to change the provider
to use the UserPass provider instead of some social provider.

    1500:com.typesafe.plugin.CommonsMailerPlugin
    9994:securesocial.core.DefaultAuthenticatorStore
    9995:securesocial.core.DefaultIdGenerator
    9996:securesocial.core.providers.utils.DefaultPasswordValidator
    9997:securesocial.controllers.DefaultTemplatesPlugin
    9998:br.com.celerate.security.CelerateUserService
    9999:securesocial.core.providers.utils.BCryptPasswordHasher
    10001:securesocial.core.providers.UsernamePasswordProvider

We used the UsernamePasswordProvider class to handle the authentication
part for us and we had to configure other plugins which do other things. For example,
we need to hash the password(BCryptPasswordHasher), maybe send a email(CommonsMailerPlugin) and validate the password sent by the user(DefaultPasswordValidator). These plugins are not necessary when you are dealing with social authentication.

Maybe you have noticed that there is a plugin which is not from SecureSocial. It is
the CelerateUserService. You need to create a class to handle the process
of create a new user in the system, verify the existence of a user in your system, etc.
We created this same class in the other post, but now it will be a little bit different.

    public class CelerateUserService extends BaseUserService {

    	public CelerateUserService(Application application) {
    		super(application);
    		// TODO Auto-generated constructor stub
    	}

    	@Override
    	public Identity doSave(Identity user) {
    		final SystemUser systemUser = new SystemUser();
    		newSystemUser(user, systemUser);
    		Identity foundUser = doFind(user.identityId());
    		if (foundUser == null) {
    			return TransactionHelper.run(new Function0<WrapIdentity>() {

    				@Override
    				public WrapIdentity apply() throws Throwable {
    					JPA.em().persist(systemUser);
    					return new WrapIdentity(systemUser);
    				}
    			});
    		}
    		return foundUser;
    	}

    	private void newSystemUser(Identity user, final SystemUser systemUser) {
    		systemUser.setEmail(user.email().get());
    		systemUser.setLastName(user.lastName());
    		systemUser.setPassword(user.passwordInfo().get().password());
    		systemUser.setFirstName(user.firstName());
    		systemUser.setProvider(user.identityId().providerId());
    		PasswordInfo passwordInfo = user.passwordInfo().get();
    		String salt = passwordInfo.salt().isDefined() ? passwordInfo
    				.salt().get() : null;
    		systemUser.setPasswordInfo(new SystemPasswordInfo(passwordInfo
    				.hasher(), salt));
    	}

    	@Override
    	public void doSave(Token token) {
    		final SignupToken newToken = SignupToken.from(token);
    		TransactionHelper.run(new Runnable() {

    			@Override
    			public void run() {
    				JPA.em().persist(newToken);
    			}
    		});
    	}

    	@Override
    	public Identity doFind(final IdentityId identityId) {
    		return TransactionHelper.run(new Function0<WrapIdentity>() {

    			@Override
    			public WrapIdentity apply() throws Throwable {
    				Option<SystemUser> user = SystemUsers
    						.findByEmail(identityId.userId());
    				return user.isDefined() ? new WrapIdentity(user.get())
    						: null;
    			}
    		});
    	}

    	@Override
    	public Token doFindToken(final String tokenId) {
    		return TransactionHelper.run(new Function0<Token>() {

    			@Override
    			public Token apply() throws Throwable {
    				return JPA.em().find(SignupToken.class, tokenId)
    						.toSecureSocialToken();
    			}
    		});
    	}

    	@Override
    	public Identity doFindByEmailAndProvider(String email,
    			String providerId) {
    		return doFind(new IdentityId(email, providerId));
    	}

    	@Override
    	public void doDeleteToken(String uuid) {
    		// TODO Auto-generated method stub

    	}

    	@Override
    	public void doDeleteExpiredTokens() {
    		// TODO Auto-generated method stub

    	}

    }

There is a lot going on in this class. Let’s start with all methods that have
token as part of the name or receive a Token as a parameter. When you
want to save a new user, Secure Social uses a two step registration process.
First the new user need to register a email. After that Secure Social will send
an email with the generated token, that is why you need to use the Typesafe
mailer plugin. Here is an example of url:(exemplo aqui) When a user tries to
follow this url, Secure Social will try to validate this token and that is why
you need to override the methods doFindToken and doSave(Token token).
You have to find a way to store this information and query it later. I opted for
save the token in my database.

Other very important method is the doFindByEmailAndProvider(String email,String providerId) method. Every time a user tries to log in your application, this method will be invoked. Now you are probably asking to yourself: where is the password? You
don’t need to worry about. Instead of leave the responsibility of checking the
hashed password in your hands, Secure Social just asks for you to load a user
based on his email. With this user loaded(Identity interface), Secure Social will
use the method passwordInfo to compare the password passed as argument
with the password loaded from the database.

It is a little bit boring, I know, but we need to configure an extra file, the router.
There we need to put all actions that are needed to handle the login/password
based authentication.

    #secure social
    GET     /login                      securesocial.controllers.LoginPage.login
    GET     /logout                     securesocial.controllers.LoginPage.logout

    # User Registration and password handling
    GET     /signup                     securesocial.controllers.Registration.startSignUp
    POST    /signup                    securesocial.controllers.Registration.handleStartSignUp
    GET     /signup/:token              securesocial.controllers.Registration.signUp(token)
    POST    /signup/:token              securesocial.controllers.Registration.handleSignUp(token)

    GET     /authenticate/:provider     securesocial.controllers.ProviderController.authenticate(provider)
    POST    /authenticate/:provider     securesocial.controllers.ProviderController.authenticateByPost(provider)
    GET     /not-authorized             securesocial.controllers.ProviderController.notAuthorized

Notice that all routes are provided by Secure Social. For example, all signup process can be handle out of the box by the framework. Secure social comes with a few predefined templates that you  can start using as your login and signup views. Even if you do not want to use these templates,  you will still want to use all controllers to handle the process.

That is it! Now you can use this Secure Social to handle both social or login/password
authentication process. In another post, I will back showing how to customize the templates and how to override the defaut behavior of the controller. Thanks for reading!