DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Improving Backend Performance Part 1/3: Lazy Loading in Vaadin Apps
  • Multi-Threaded Geo Web Crawler In Java
  • Moving PeopleSoft ERP Data Between Databases With Data Mover Scripts
  • Understanding Multi-Leader Replication for Distributed Data

Trending

  • Engineering LLMOps: Building Robust CI/CD Pipelines for LLM Applications on Google Cloud
  • Building an Image Classification Pipeline With Apache Camel and Deep Java Library (DJL)
  • Java in a Container: Efficient Development and Deployment With Docker
  • The Developer's Guide to Context-Aware AI: When Your Code Documentation Becomes Intelligent
  1. DZone
  2. Data Engineering
  3. Databases
  4. Creating Account Activation Links for User Registration in Vaadin Applications

Creating Account Activation Links for User Registration in Vaadin Applications

In this article, I'll show you how to generate activation links that you can send to the users so that they can complete the registration process.

By 
Alejandro Duarte user avatar
Alejandro Duarte
DZone Core CORE ·
Mar. 19, 21 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
6.9K Views

Join the DZone community and get the full member experience.

Join For Free

In a previous article, I explained how to implement a sign-up view to register new users within the application. In this article, I'll show you how to generate activation links that you can send to the users so that they can complete the registration process.


Generating a Random Activation Code

The general idea for implementing account activation codes is to generate a random string and store it in the database. You use that string to create a link to your application and send it to the user, for example via e-mail (covered in the next article). When the user clicks the link, you compare the string (or code) with the one you stored in the database, and if they match, you activate the user. So, you need to store two things per user:

  • a hard-to-guess random code, and,
  • a boolean that indicates whether the user has activated the account or not.

For example:

Java
 




x
9


 
1
@Entity
2
public class User extends AbstractEntity {
3

          
4
    ...
5
    private String activationCode;
6
    private boolean active;
7
  
8
    ...
9
}



The activation code can be generated in the constructor:

Java
 




x


 
1
public User(String username, String password, Role role) {
2
  ...
3
  this.activationCode = RandomStringUtils.randomAlphanumeric(32);
4
}



Implementing the Logic to Activate Users/Accounts

In the service layer, you need a method to activate a user if the codes match. You can query the database and search for a user with the given code, and if it exists, you update the active flag and save it back to the database:

Java
 




x


 
1
@Service
2
public class AuthService {
3
  
4
    public class AuthException extends Exception { }
5
  
6
    ...
7

          
8
    public void activate(String activationCode) throws AuthException {
9
        User user = userRepository.getByActivationCode(activationCode);
10
        if (user != null) {
11
            user.setActive(true);
12
            userRepository.save(user);
13
        } else {
14
            throw new AuthException();
15
        }
16
    }
17

          
18
}


You should either make sure that the activation codes are unique or query the user by user name plus activation code. I'll let that as an exercise.

Implementing the Authentication Logic

You also need to update the authentication logic. You cannot authenticate a user unless it is active:

Java
 




xxxxxxxxxx
1


 
1
    public void authenticate(String username, String password) throws AuthException {
2
        User user = userRepository.getByUsername(username);
3
        if (user != null && user.checkPassword(password) && user.isActive()) {
4
            VaadinSession.getCurrent().setAttribute(User.class, user);
5
            createRoutes(user.getRole());
6
        } else {
7
            throw new AuthException();
8
        }
9
    }



Defining the Activation Link (URL)

For now, and to make testing simpler, we'll send the URL to the standard output. You need to concatenate the URL of the activation view (implemented in the next step) and pass the activation code as a parameter:

Java
 




x
5
10
4


 
1
    public void register(String email, String password) {
2
        User user = userRepository.save(new User(email, password, Role.USER));
3
        String text = "http://localhost:8080/activate?code=" + user.getActivationCode();
4
        System.out.println(text);
5
    }



Implementing the Activation View

Finally, you have to create the activation view mapped to the URL used in the previous step:

Java
 




xxxxxxxxxx
1
32


 
1
@Route("activate")
2
public class ActivationView extends Composite implements BeforeEnterObserver {
3

          
4
    private VerticalLayout layout;
5

          
6
    private final AuthService authService;
7

          
8
    public ActivationView(AuthService authService) {
9
        this.authService = authService;
10
    }
11

          
12
    @Override
13
    public void beforeEnter(BeforeEnterEvent event) {
14
        try {
15
            Map<String, List<String>> params = event.getLocation().getQueryParameters().getParameters();
16
            String code = params.get("code").get(0);
17
            authService.activate(code);
18
            layout.add(
19
                    new Text("Account activated."),
20
                    new RouterLink("Login", LoginView.class)
21
            );
22
        } catch (AuthService.AuthException e) {
23
            layout.add(new Text("Invalid link."));
24
        }
25
    }
26

          
27
    @Override
28
    protected Component initContent() {
29
        layout = new VerticalLayout();
30
        return layout;
31
    }
32
}


This view reads the parameters to get the activation code and attempts to activate the user.

Summary

We learned how to generate a random code that can be used in a URL to activate an account. In the next article, I'll show you how to send that URL via email.

Links application Database Vaadin

Opinions expressed by DZone contributors are their own.

Related

  • Improving Backend Performance Part 1/3: Lazy Loading in Vaadin Apps
  • Multi-Threaded Geo Web Crawler In Java
  • Moving PeopleSoft ERP Data Between Databases With Data Mover Scripts
  • Understanding Multi-Leader Replication for Distributed Data

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook