1
1
package com .naturalprogrammer .spring5tutorial .services ;
2
2
3
+ import java .util .UUID ;
4
+
3
5
import javax .annotation .PostConstruct ;
6
+ import javax .mail .MessagingException ;
4
7
5
8
import org .apache .commons .logging .Log ;
6
9
import org .apache .commons .logging .LogFactory ;
15
18
import com .naturalprogrammer .spring5tutorial .commands .UserCommand ;
16
19
import com .naturalprogrammer .spring5tutorial .domain .User ;
17
20
import com .naturalprogrammer .spring5tutorial .domain .User .Role ;
21
+ import com .naturalprogrammer .spring5tutorial .mail .MailSender ;
18
22
import com .naturalprogrammer .spring5tutorial .repositories .UserRepository ;
19
23
import com .naturalprogrammer .spring5tutorial .utils .MyUtils ;
20
24
@@ -35,12 +39,18 @@ public class UserServiceImpl implements UserService {
35
39
36
40
private PasswordEncoder passwordEncoder ;
37
41
private UserRepository userRepository ;
42
+ private MailSender mailSender ;
43
+ private String applicationUrl ;
38
44
39
45
public UserServiceImpl (UserRepository userRepository ,
40
- PasswordEncoder passwordEncoder ) {
46
+ PasswordEncoder passwordEncoder ,
47
+ MailSender mailSender ,
48
+ @ Value ("${applicationUrl}" ) String applicationUrl ) {
41
49
42
50
this .userRepository = userRepository ;
43
51
this .passwordEncoder = passwordEncoder ;
52
+ this .mailSender = mailSender ;
53
+ this .applicationUrl = applicationUrl ;
44
54
}
45
55
46
56
@ PostConstruct
@@ -74,8 +84,30 @@ public void signup(UserCommand userCommand) {
74
84
User user = userCommand .toUser ();
75
85
user .setPassword (passwordEncoder .encode (user .getPassword ()));
76
86
user .getRoles ().add (Role .UNVERIFIED );
87
+ user .setVerificationCode (UUID .randomUUID ().toString ());
77
88
78
89
userRepository .save (user );
79
- MyUtils .afterCommit (() -> MyUtils .login (user ));
90
+ MyUtils .afterCommit (() -> {
91
+
92
+ MyUtils .login (user );
93
+ try {
94
+
95
+ sendVerificationMail (user );
96
+
97
+ } catch (MessagingException e ) {
98
+
99
+ log .warn ("Sending verification mail to "
100
+ + user .getEmail () + " failed" , e );
101
+ }
102
+ });
103
+ }
104
+
105
+ private void sendVerificationMail (User user ) throws MessagingException {
106
+
107
+ String verificationLink = applicationUrl + "/users/" +
108
+ user .getVerificationCode () + "/verify" ;
109
+
110
+ mailSender .send (user .getEmail (), MyUtils .getMessage ("verifySubject" ),
111
+ MyUtils .getMessage ("verifyBody" , verificationLink ));
80
112
}
81
113
}
0 commit comments