Skip to content

Sign Up Assistant | Activation

The Sign Up Assistant provides a mechanism to generate activation codes that can be sent via email.

If this option is selected, the user will be required to find the confirmation email in their mailbox and activate the account by sending the code. Failure to do this will prevent the client from accessing the application.

Sending emails

SmartFoxServer 3 offers the necessary tools to send emails out of the box: the only requirement is to configure a valid SMTP server that will be used to send confirmation emails. To do so launch the AdminTool > Server Configurator > Mailer:

admin email setup

Make sure to activate the service, fill the form with your SMTP credentials and restart the server.

A simple confirmation email example

Confirmation emails are easy to create and customize: they are based on HTML templates that you can re-design as you please.

For this example we will create our own template and store it under our Extension folder inside a subfolder called SignUpEmailTemplates/.

The Sign Up Assistant will detect special placeholders in our HTML like ${username} and will automatically replace them with the actual data provided by the user. Additionally you can define any number of other placeholders following the same naming convention: ${placeholder-name} and pass along dynamic data that will populate your emails.

This is the code we will use to activate the Sign Up Assistant's mailer service:

suac.getConfig().emailResponse.isActive = true;
suac.getConfig().emailResponse.fromAddress = "webmaster@myapplication.com";
suac.getConfig().emailResponse.subject = "Thanks for signing up!";
suac.getConfig().emailResponse.template = "SignUpEmailTemplates/SignUpConfirmation.html";

We just need to provide the essential parameters such as the subject, "from address" and the template file path. Now every time a user account is successfully created an email will be sent for confirmation.

This is a simple HTML snippet we can use for the email, which will be saved as SignUpConfirmation.html under extensions/SignUpEmailTemplates/:

<html>
<body>
    <h2>Thanks for your registration, ${userName}</h2>
    <p>Please make sure to keep this email as a reminder of your access credentials:</p>
    <ul>
        <li><strong>User Name</strong>: ${userName}</li>
    </ul>
    <hr>
    <p>Thanks, The MyApplication Staff</p>
</body>
</html>

Custom email fields

Let's take a quick look at how we can add custom fields to the email which can be populated with runtime values. Suppose we have several Zones in our server, running different games, and we want to customize the confirmation email with the right game title, based on the Zone name. Also we want to add a special warning for users with age < 18 years saying that they will not be able to use the in-game purchase service.

private final class MyPostProcessPlugin implements ISignUpAssistantPlugin
{
    private final String zoneName;

    public MyPostProcessPlugin(String zoneName)
    {
        this.zoneName = zoneName;
    }

    @Override
    public void execute(User user, ISFSObject params, SignUpConfiguration config) throws SignUpValidationException
    {
        // By default we just insert a line break
        String message = "<br />";

        // If age below 18 we show a message
        int age = params.getInt("age");
        if (age < 18) 
            message = "<p>Since your age is below 18, in-game purchases will not be available</p>";

        var customMailFields = new HashMap<String, String>();
        customMailFields.put("${ageComment}", message);
        customMailFields.put("${gameWelcome}", "Welcome to the " + zoneName + " game.");

        // Pass the new fields to the Component's configuration
        config.emailResponse.customEmailFields = customMailFields;  
    }
}

We assign this class to the postProcessPlugin property in the configuration to execute it after the user data has been written to the database:

suac.getConfig().postProcessPlugin = new MyPostProcessPlugin(getParentZone().getName());

In the execute() method of our class we are provided with three object references:

  • user: the reference to the user that has sent the request
  • params: the response SFSObject that will be sent back to the user
  • config: the component's configuration object

We can easily populate the customEmailFields property in the configuration object with a Map of strings where each key represents the placeholder in the HTML that we want to process. Also notice that the params object can be populated with custom values to be sent back to the client, if needed.

Adding the activation code in the sign up process

Let's see how we can better secure the registration process by adding the activation code. Before looking at the code we will need to update our database table with two additional fields, one for the activation code and one which will tell us if the user has properly activated his account.

Field name Type Length index
id integer -- primary, autoincrement
username varchar 30 --
password varchar 30 --
email varchar 30 --
age integer -- --
country varchar 30 --
act_code varchar 32 --
active varchar 1 --

The new field called act_code will hold the activation code, which is a string of fixed length (32 chars). Instead, the active field works like a flag and tells the system if the account has been activated or not. By convention this field will only contain one of two characters: "Y" or "N", and will be set to "N" by default.

Again we will need a bit of configuration code in our Extension to tell the Sign Up Assistant where to find those fields in the database.

suac.getConfig().activationCodeField = "act_code";
suac.getConfig().userIsActiveField = "active";

Please note:

By default the activationCodeField is set to null which means that no activation is required during the sign up process.

We're almost ready to test the activation process, but before we go ahead we have to modify the confirmation email so that it also contains the activation code. This is done by adding an extra placeholder in the HTML called ${activationCode}:

<html>
<body>
    <h2>Thanks for your registration, ${userName}</h2>
    <p>Please make sure to keep this email as a reminder of your access credentials:</p>
    <ul>
        <li><strong>User Name</strong>: ${userName}</li>
        <li><strong>Activation Code</strong>: ${activationCode}</li>
    </ul>
    <hr>
    <p>Thanks, The MyApplication Staff</p>
</body>
</html>

User account activation

At this point the new user can sign up a new account and receive the confirmation and activation code to their email address. But how does the client send the code back to the server to complete the process?

The operation is similar to the code we have used for the Submit operation. The user will be shown on screen an input field where to copy and paste the activation code. The application will then send the data as follows:

// Define SignUp extension command
private string CMD_ACTIVATE = "$SignUp.Activate";
/**
* Send activation data.
*/
private void sendSignUpData()
{
    var sfso = new SFSObject();
    sfso.PutShortString("act_code", tf_activation.text);

    sfs.Send(new ExtensionRequest(CMD_ACTIVATE, sfso));
}
/**
* Process extension response.
*/
private void OnExtensionResponse(ApiEvent evt)
{
    var cmd = (string) evt.Params["cmd"];
    var sfso = (SFSObject) evt.Params["params"];

    if (cmd == CMD_ACTIVATE)
    {
        if (sfso.GetBool("success"))
            Console.WriteLine("Thanks, your account has been activated");
        else
            Console.WriteLine("Activation error:" + (string)evt.Params["errorMessage"]);
    }
}

This time we're sending a single parameter, the activation code, by using as key the name of the field that holds the code in the database. The server will then reply with a success parameter if the operation was successful or send a detailed error message.

Resending the Activation code

There can be cases in which the User might want to request the activation code again, possibly because the first email wasn't received. In this case the client application can send a specific request to trigger a new email send from the server.

// Define SignUp extension command
private string CMD_RESEND_EMAIL = "$SignUp.ResendEmail";
/**
* Request a new email with the activation code.
*/
private void sendSignUpData()
{
sfs.Send(new ExtensionRequest(CMD_RESEND_EMAIL));
}

This particular request does not return any data from the server and it can only be invoked a limited amount of times for each user. By default a maximum of 3 re-send requests can be called, although the setting can be customized from the configuration of the SignUp Assistant component.

The request can also be sent at a later moment, after the sign up process. When this is the case we will also need to send the original email address used for signing up:

// Define SignUp extension command
private string CMD_RESEND_EMAIL = "$SignUp.ResendEmail";
/**
* Request a new email with the activation code.
*/
private void sendSignUpData()
{
    var sfso = new SFSObject();
    sfso.PutShortString("email", "me@myself.com");

    sfs.Send(new ExtensionRequest(CMD_RESEND_EMAIL, sfso));
}

Attention:

The email key used in the example here must correspond to the value set for SignUpConfiguration.emailField on the server side. The default value is "email".

Wrapping up

In this chapter we have seen how we can send confirmation emails using HTML templates and how to add an activation code for the sign up process. We can now see how to activate and use the Password Recovery feature provided by the Sign Up Assistant.

Choose your next destination: