Project

General

Profile

« Previous | Next » 

Revision 56991

Creating branch to split the login process

View differences:

modules/dnet-openaire-users/branches/login/deploy.info
1
{
2
  "type_source": "SVN", 
3
  "goal": "package -U source:jar", 
4
  "url": "http://svn-public.driver.research-infrastructures.eu/driver/dnet40/modules/dnet-openaire-users/trunk", 
5
  "deploy_repository": "dnet4-snapshots", 
6
  "version": "4", 
7
  "mail": "antleb@di.uoa.gr, kiatrop@di.uoa.gr, sbaltzi@di.uoa.gr", 
8
  "deploy_repository_url": "http://maven.research-infrastructures.eu/nexus/content/repositories/dnet4-snapshots", 
9
  "name": "dnet-openaire-users"
10
}
11

  
modules/dnet-openaire-users/branches/login/src/main/java/eu/dnetlib/openaire/usermanagement/VerifyToDeleteServlet.java
1
package eu.dnetlib.openaire.usermanagement;
2

  
3
import eu.dnetlib.openaire.user.utils.InputValidator;
4
import eu.dnetlib.openaire.user.utils.LDAPActions;
5
import eu.dnetlib.openaire.user.utils.VerificationActions;
6
import eu.dnetlib.openaire.usermanagement.utils.UrlConstructor;
7
import org.apache.log4j.Logger;
8
import org.springframework.beans.factory.annotation.Autowired;
9
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
10

  
11
import javax.servlet.ServletConfig;
12
import javax.servlet.ServletException;
13
import javax.servlet.http.HttpServlet;
14
import javax.servlet.http.HttpServletRequest;
15
import javax.servlet.http.HttpServletResponse;
16
import javax.servlet.http.HttpSession;
17
import java.io.IOException;
18
import java.io.PrintWriter;
19

  
20
/**
21
 * Created by sofia on 21/5/2018.
22
 */
23
public class VerifyToDeleteServlet extends HttpServlet {
24

  
25
    public void init(ServletConfig config) throws ServletException {
26
        super.init(config);
27
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
28
                config.getServletContext());
29
    }
30

  
31
    @Autowired
32
    private VerificationActions verificationActions;
33

  
34
    @Autowired
35
    private LDAPActions ldapActions;
36

  
37
    private Logger logger = Logger.getLogger(VerificationCodeServlet.class);
38

  
39
    @Override
40
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
41
        response.setContentType("text/html");
42
        PrintWriter printWriter = response.getWriter();
43

  
44
        String formUsername = request.getParameter("username").trim();
45
        String formVerificationCode = request.getParameter("verification_code").trim();
46

  
47
        try {
48
            if (InputValidator.isFilled(formUsername) && InputValidator.isFilled(formVerificationCode)) {
49
                if (verificationActions.verificationEntryExists(formUsername) && verificationActions.verificationCodeIsCorrect(formUsername, formVerificationCode)) {
50
                    if (!verificationActions.verificationCodeHasExpired(formUsername)) {
51

  
52
                        Boolean isRegistered = false;
53
                        Boolean isZombie = false;
54

  
55
                        if (ldapActions.usernameExists(formUsername)) {
56
                            logger.info("User " + formUsername + " is activated user!");
57
                            isRegistered = true;
58
                        } else if (ldapActions.isZombieUsersUsername(formUsername)) {
59
                            logger.info("User " + formUsername + " is zombie user!");
60
                            isZombie = true;
61
                        }
62

  
63
                        if (!isRegistered && !isZombie) {
64
                            request.getSession().setAttribute("message", "Username or verification code are not valid.");
65
                            response.sendRedirect("./verifyToDelete.jsp");
66
                        } else {
67
                            if (isRegistered) {
68
                                ldapActions.deleteUser(formUsername);
69
                            } else if (isZombie) {
70
                                ldapActions.deleteZombieUser(formUsername);
71
                            }
72
                            verificationActions.deleteVerificationEntry(formUsername);
73
                            response.sendRedirect(UrlConstructor.getRedirectUrl(request,"successDeleteAccount.jsp"));
74

  
75
                        }
76
                    } else {
77
                        logger.info("Verification code has expired!");
78
                        response.sendRedirect(UrlConstructor.getRedirectUrl(request, "expiredVerificationCode.jsp"));
79
                    }
80
                } else {
81
                    logger.info("Username or verification code are not valid!");
82
                    request.getSession().setAttribute("message", "Username or verification code are not valid.");
83
                    response.sendRedirect("./verifyToDelete.jsp");
84
                }
85
            } else {
86
                if (!InputValidator.isFilled(formUsername)) {
87
                    logger.info("No username");
88
                    request.getSession().setAttribute("msg_username_error", "Please enter your username.");
89
                }
90
                if (!InputValidator.isFilled(formVerificationCode)) {
91
                    logger.info("No verification code");
92
                    request.getSession().setAttribute("msg_verification_code_error", "Please enter your verification code.");
93
                }
94
                response.sendRedirect("./verifyToDelete.jsp");
95
            }
96
        } catch (Exception ldape) {
97
            logger.error("Could not remove user with username " + formUsername, ldape);
98
            response.sendRedirect(UrlConstructor.getRedirectUrl(request, "error.jsp"));
99
        }
100

  
101
        printWriter.close();
102
    }
103
}
modules/dnet-openaire-users/branches/login/src/main/java/eu/dnetlib/openaire/usermanagement/AddPasswordServlet.java
1
package eu.dnetlib.openaire.usermanagement;
2

  
3
import eu.dnetlib.openaire.user.utils.LDAPActions;
4
import eu.dnetlib.openaire.user.utils.VerificationActions;
5
import eu.dnetlib.openaire.user.utils.InputValidator;
6
import eu.dnetlib.openaire.usermanagement.utils.UrlConstructor;
7
import org.apache.log4j.Logger;
8
import org.springframework.beans.factory.annotation.Autowired;
9
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
10

  
11
import javax.servlet.ServletConfig;
12
import javax.servlet.ServletException;
13
import javax.servlet.http.HttpServlet;
14
import javax.servlet.http.HttpServletRequest;
15
import javax.servlet.http.HttpServletResponse;
16
import javax.servlet.http.HttpSession;
17
import java.io.IOException;
18
import java.io.PrintWriter;
19

  
20
/**
21
 * Created by sofia on 23/10/2017.
22
 */
23
public class AddPasswordServlet extends HttpServlet {
24

  
25
    public void init(ServletConfig config) throws ServletException {
26
        super.init(config);
27
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
28
                config.getServletContext());
29
    }
30

  
31
    @Autowired
32
    private VerificationActions verificationActions;
33

  
34
    @Autowired
35
    private LDAPActions ldapActions;
36

  
37
    private Logger logger = Logger.getLogger(AddPasswordServlet.class);
38

  
39
    @Override
40
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
41
        response.setContentType("text/html");
42
        PrintWriter printWriter = response.getWriter();
43

  
44
        HttpSession session = request.getSession();
45
        String username = (String) session.getAttribute("username");
46

  
47
        if (username == null){
48
            logger.info("Empty username in session");
49
        }
50

  
51
        String password = request.getParameter("password");
52
        String confirmPassword = request.getParameter("password_conf");
53

  
54
        if (InputValidator.isFilled(password)) {
55
            if (InputValidator.isValidPassword(password) && password.equals(confirmPassword) && username !=null) {
56
                try {
57
                    ldapActions.resetPassword(username, password);
58
                    logger.info("password added");
59
                    session.removeAttribute("username");
60
                    response.sendRedirect(UrlConstructor.getRedirectUrl(request, "success.jsp"));
61
                } catch (Exception e) {
62
                    logger.error("LDAP error in adding password", e);
63
                    response.sendRedirect(UrlConstructor.getRedirectUrl(request, "error.jsp"));
64
                }
65
            } else {
66
                if (!InputValidator.isValidPassword(password)) {
67
                    logger.info("No valid password");
68
//                    request.getSession().setAttribute("msg_invalid_password", "The password must contain a lowercase letter, a capital (uppercase) letter, a number and must be at least 6 characters long. White space character is not allowed.");
69
                }
70
                if (!password.equals(confirmPassword)) {
71
                    logger.info("No matching passwords");
72
//                    request.getSession().setAttribute("msg_pass_conf_error", "These passwords don't match.");
73
                }
74
                response.sendRedirect("./addPassword.jsp");
75
            }
76
        } else {
77
            logger.info("Empty password");
78
            request.getSession().setAttribute("msg_password_error_display", "display:block" );
79
//            request.getSession().setAttribute("msg_invalid_password", "The password must contain a lowercase letter, a capital (uppercase) letter, a number and must be at least 6 characters long. White space character is not allowed.");
80
            response.sendRedirect("./resetPassword.jsp");
81
        }
82

  
83
        printWriter.close();
84

  
85
    }
86
}
modules/dnet-openaire-users/branches/login/src/main/java/eu/dnetlib/openaire/usermanagement/RequestToDeleteAccountServlet.java
1
package eu.dnetlib.openaire.usermanagement;
2

  
3
import eu.dnetlib.openaire.user.utils.EmailSender;
4
import eu.dnetlib.openaire.user.utils.LDAPActions;
5
import eu.dnetlib.openaire.user.utils.VerificationActions;
6
import eu.dnetlib.openaire.user.utils.VerifyRecaptcha;
7
import eu.dnetlib.openaire.usermanagement.utils.UrlConstructor;
8
import org.apache.commons.validator.routines.EmailValidator;
9
import org.apache.log4j.Logger;
10
import org.springframework.beans.factory.annotation.Autowired;
11
import org.springframework.beans.factory.annotation.Value;
12
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
13

  
14
import javax.mail.MessagingException;
15
import javax.servlet.ServletConfig;
16
import javax.servlet.ServletException;
17
import javax.servlet.http.HttpServlet;
18
import javax.servlet.http.HttpServletRequest;
19
import javax.servlet.http.HttpServletResponse;
20
import javax.servlet.http.HttpSession;
21
import java.io.IOException;
22
import java.sql.Timestamp;
23
import java.util.Date;
24
import java.util.UUID;
25

  
26
/**
27
 * Created by sofia on 21/5/2018.
28
 */
29
public class RequestToDeleteAccountServlet extends HttpServlet {
30

  
31
    @Autowired
32
    private VerificationActions verificationActions;
33

  
34
    @Autowired
35
    private LDAPActions ldapActions;
36

  
37
    @Autowired
38
    private EmailSender emailSender;
39

  
40
    @Value("${oidc.home}")
41
    private String oidcHomeUrl;
42

  
43
    @Value("${google.recaptcha.secret}")
44
    private String secret;
45

  
46
    @Value("${google.recaptcha.key}")
47
    private String sitekey;
48

  
49
    private static final Logger logger = Logger.getLogger(RequestActivationCodeServlet.class);
50

  
51
    public void init(ServletConfig config) throws ServletException {
52
        super.init(config);
53
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
54
                config.getServletContext());
55
        config.getServletContext().setAttribute("sitekey", sitekey);
56

  
57
    }
58

  
59
    @Override
60
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
61
        String formEmail = request.getParameter("email").trim();
62

  
63
        String gRecaptchaResponse = request.getParameter("g-recaptcha-response");
64

  
65
        HttpSession session = request.getSession();
66
        session.setAttribute("homeUrl", oidcHomeUrl);
67

  
68
        if (formEmail == null) {
69
            request.getSession().setAttribute("message", "Error reading email.");
70
            response.sendRedirect("./requestToDeleteAccount.jsp");
71

  
72
        } else if (formEmail.isEmpty()) {
73
            request.getSession().setAttribute("message", "Please enter your email.");
74
            response.sendRedirect("./requestToDeleteAccount.jsp");
75

  
76
        } else if (!EmailValidator.getInstance().isValid(formEmail)) {
77
            request.getSession().setAttribute("message", "Please enter a valid email.");
78
            response.sendRedirect("./requestToDeleteAccount.jsp");
79

  
80
        } else if (!VerifyRecaptcha.verify(gRecaptchaResponse, secret)) {
81
            request.getSession().setAttribute("reCAPTCHA_message", "You missed the reCAPTCHA validation!");
82
            response.sendRedirect("./requestToDeleteAccount.jsp");
83

  
84
        } else {
85

  
86
            try {
87

  
88
                Boolean isRegistered = false;
89
                Boolean isZombie = false;
90

  
91
                if (ldapActions.emailExists(formEmail)) {
92
                    logger.info("User with email: " + formEmail + " is activated user!");
93
                    isRegistered = true;
94
                } else if (ldapActions.isZombieUsersEmail(formEmail)) {
95
                    logger.info("User with email: " + formEmail + " is zombie user!");
96
                    isZombie = true;
97
                }
98

  
99
                if (!isRegistered && !isZombie) {
100
                    request.getSession().setAttribute("message", "There is no user with that email.");
101
                    response.sendRedirect("./requestToDeleteAccount.jsp");
102
                } else {
103

  
104
                    String username = null;
105

  
106
                    if (isRegistered) {
107
                        username = ldapActions.getUsername(formEmail);
108
                    } else if (isZombie) {
109
                        username = ldapActions.getZombieUsersUserName(formEmail);
110
                    }
111

  
112
                    UUID verificationCode = UUID.randomUUID();
113
                    Date creationDate = new Date();
114
                    String vCode = verificationCode.toString();
115

  
116
                    Timestamp timestamp = new Timestamp(creationDate.getTime());
117

  
118
                    if (!verificationActions.verificationEntryExists(username)) {
119
                        verificationActions.addVerificationEntry(username, vCode, timestamp);
120

  
121
                    } else {
122
                        verificationActions.updateVerificationEntry(username, vCode, timestamp);
123
                    }
124

  
125
                    String resultPath = UrlConstructor.getRedirectUrl(request, "verifyToDelete.jsp");
126
                    String resultPathWithVCode = UrlConstructor.getVerificationLink(resultPath, vCode);
127

  
128
                    String verificationCodeMsg = "<p>Hello " + username + ",</p>" +
129
                            "<p> A request has been made to get a verification code to delete your OpenAIRE account. To delete your " +
130
                            "account, you will need to submit your username and this verification code in order to verify that the " +
131
                            "request was legitimate.</p>" +
132
                            "<p>" +
133
                            "The verification code is " + vCode +
134
                            "</p>" +
135
                            "Click the URL below and proceed with deleting your account." +
136
                            "<p><a href=" + resultPathWithVCode + ">" + resultPathWithVCode + "</a></p>" +
137
                            "<p>The verification code is valid for 24 hours.</p>" +
138
                            "<p>Thank you,</p>" +
139
                            "<p>OpenAIRE technical team</p>";
140

  
141
                    String verificationCodeSubject = "Request to delete your OpenAIRE account";
142

  
143
                    emailSender.sendEmail(formEmail, verificationCodeSubject, verificationCodeMsg);
144
                    logger.info("Sending verification code to user: " + formEmail);
145

  
146

  
147
                    response.sendRedirect("./verifyToDelete.jsp");
148
                }
149
            } catch (MessagingException e) {
150
                logger.error("Error in sending email", e);
151
                request.getSession().setAttribute("message", "Error sending email");
152
                response.sendRedirect("./requestActivationCode.jsp");
153
            } catch (Exception ldape) {
154
                logger.error("Could not user with email " + formEmail, ldape);
155
                response.sendRedirect(UrlConstructor.getRedirectUrl(request, "error.jsp"));
156
            }
157
        }
158
    }
159

  
160
    public String getOidcHomeUrl() {
161
        return oidcHomeUrl;
162
    }
163

  
164
    public void setOidcHomeUrl(String oidcHomeUrl) {
165
        this.oidcHomeUrl = oidcHomeUrl;
166
    }
167
}
modules/dnet-openaire-users/branches/login/src/main/java/eu/dnetlib/openaire/usermanagement/utils/UrlConstructor.java
1
package eu.dnetlib.openaire.usermanagement.utils;
2

  
3
import org.apache.log4j.Logger;
4

  
5
import javax.servlet.http.HttpServletRequest;
6
import java.util.UUID;
7

  
8
/**
9
 * Created by sofia on 8/3/2018.
10
 */
11
public class UrlConstructor {
12

  
13
    private static final Logger logger = Logger.getLogger(UrlConstructor.class);
14

  
15
    public static String getRedirectUrl(HttpServletRequest request, String jspPage) {
16

  
17
        String scheme = request.getScheme();
18
        String serverName = request.getServerName();
19
        int portNumber = request.getServerPort();
20
        String contextPath = request.getContextPath();
21

  
22
        String resultPath;
23
        if (portNumber == 80) {
24
            resultPath = scheme + "://" + serverName + contextPath + "/" + jspPage;
25
        } else {
26
            resultPath = scheme + "://" + serverName + ":" + portNumber + contextPath + "/" + jspPage;
27
        }
28

  
29
        if (jspPage.equals("error.jsp")) {
30
            request.getSession().setAttribute("error", "true");
31
        }
32
        if (jspPage.equals("success.jsp")) {
33
            request.getSession().setAttribute("success", "true");
34
        }
35
        if (jspPage.equals("successAddPassword.jsp")) {
36
            request.getSession().setAttribute("successAddPassword", "true");
37
        }
38
        if (jspPage.equals("successDeleteAccount.jsp")) {
39
            request.getSession().setAttribute("successDeleteAccount", "true");
40
        }
41
        if (jspPage.equals("expiredVerificationCode.jsp")) {
42
            request.getSession().setAttribute("expiredVerificationCode", "true");
43
        }
44
        if (jspPage.equals("registerSuccess.jsp")) {
45
            request.getSession().setAttribute("registerSuccess", "true");
46
        }
47
        if (jspPage.equals("emailSuccess.jsp")) {
48
            request.getSession().setAttribute("emailSuccess", "true");
49
        }
50

  
51
        return resultPath;
52
    }
53

  
54
    public static String getVerificationLink(String path , String verificationCode ) {
55

  
56
        return path + "?code=" + verificationCode;
57

  
58
    }
59

  
60
}
modules/dnet-openaire-users/branches/login/src/main/java/eu/dnetlib/openaire/usermanagement/ActivationCodeServlet.java
1
package eu.dnetlib.openaire.usermanagement;
2

  
3
import eu.dnetlib.openaire.user.utils.LDAPActions;
4
import eu.dnetlib.openaire.user.utils.VerificationActions;
5
import eu.dnetlib.openaire.usermanagement.utils.UrlConstructor;
6
import eu.dnetlib.openaire.user.utils.InputValidator;
7
import org.apache.log4j.Logger;
8
import org.springframework.beans.factory.annotation.Autowired;
9
import org.springframework.beans.factory.annotation.Value;
10
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
11

  
12
import javax.servlet.ServletConfig;
13
import javax.servlet.ServletException;
14
import javax.servlet.http.HttpServlet;
15
import javax.servlet.http.HttpServletRequest;
16
import javax.servlet.http.HttpServletResponse;
17
import javax.servlet.http.HttpSession;
18
import java.io.IOException;
19
import java.io.PrintWriter;
20

  
21
/**
22
 * Created by sofia on 23/10/2017.
23
 */
24
public class ActivationCodeServlet extends HttpServlet{
25

  
26
    public void init(ServletConfig config) throws ServletException {
27
        super.init(config);
28
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
29
                config.getServletContext());
30
    }
31

  
32
    @Autowired
33
    private VerificationActions verificationActions;
34

  
35
    @Autowired
36
    private LDAPActions ldapActions;
37

  
38
    @Value("${oidc.home}")
39
    private String oidcHomeUrl;
40

  
41
    private Logger logger = Logger.getLogger(ActivationCodeServlet.class);
42

  
43
    @Override
44
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
45
        response.setContentType("text/html");
46
        PrintWriter printWriter = response.getWriter();
47

  
48
        String formUsername = request.getParameter("username").trim();
49
        String formVerificationCode = request.getParameter("verification_code").trim();
50

  
51
        if (InputValidator.isFilled(formUsername) && InputValidator.isFilled(formVerificationCode)) {
52
            if (verificationActions.verificationEntryExists(formUsername) && verificationActions.verificationCodeIsCorrect(formUsername, formVerificationCode)) {
53
                if (!verificationActions.verificationCodeHasExpired(formUsername)) {
54
                    HttpSession session = request.getSession();
55
                    session.setAttribute("username", formUsername);
56
                    session.setAttribute("homeUrl", oidcHomeUrl);
57
                    try {
58
                        ldapActions.moveUser(formUsername);
59
                    } catch (Exception e) {
60
                        logger.error("LDAP error in moving user", e);
61
                        response.sendRedirect(UrlConstructor.getRedirectUrl(request, "error.jsp"));
62
                    }
63
                    response.sendRedirect(UrlConstructor.getRedirectUrl(request, "registerSuccess.jsp"));
64
                } else {
65
                    logger.info("Verification code has expired!");
66
                    response.sendRedirect(UrlConstructor.getRedirectUrl(request, "expiredVerificationCode.jsp"));
67
                }
68
            } else {
69
                logger.info("Username or activation code are not valid!");
70
                request.getSession().setAttribute("message", "Username or activation code are not valid.");
71
                response.sendRedirect("./activate.jsp");
72
            }
73
        } else {
74
            if (!InputValidator.isFilled(formUsername)) {
75
                logger.info("No username");
76
                request.getSession().setAttribute("msg_username_error", "Please enter your username.");
77
            }
78
            if (!InputValidator.isFilled(formVerificationCode)) {
79
                logger.info("No activation code");
80
                request.getSession().setAttribute("msg_activation_code_error", "Please enter your activation code.");
81
            }
82
            response.sendRedirect("./activate.jsp");
83
        }
84
        printWriter.close();
85

  
86
    }
87

  
88
    public String getOidcHomeUrl() {
89
        return oidcHomeUrl;
90
    }
91

  
92
    public void setOidcHomeUrl(String oidcHomeUrl) {
93
        this.oidcHomeUrl = oidcHomeUrl;
94
    }
95
}
modules/dnet-openaire-users/branches/login/src/main/java/eu/dnetlib/openaire/usermanagement/VerificationCodeServlet.java
1
package eu.dnetlib.openaire.usermanagement;
2

  
3
import eu.dnetlib.openaire.user.utils.VerificationActions;
4
import eu.dnetlib.openaire.user.utils.InputValidator;
5
import eu.dnetlib.openaire.usermanagement.utils.UrlConstructor;
6
import org.apache.log4j.Logger;
7
import org.springframework.beans.factory.annotation.Autowired;
8
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
9

  
10
import javax.servlet.ServletConfig;
11
import javax.servlet.ServletException;
12
import javax.servlet.http.HttpServlet;
13
import javax.servlet.http.HttpServletRequest;
14
import javax.servlet.http.HttpServletResponse;
15
import javax.servlet.http.HttpSession;
16
import java.io.IOException;
17
import java.io.PrintWriter;
18

  
19
/**
20
 * Created by kiatrop on 28/9/2017.
21
 */
22
public class VerificationCodeServlet extends HttpServlet {
23

  
24
    public void init(ServletConfig config) throws ServletException {
25
        super.init(config);
26
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
27
                config.getServletContext());
28
    }
29

  
30
    @Autowired
31
    private VerificationActions verificationActions;
32

  
33
    private Logger logger = Logger.getLogger(VerificationCodeServlet.class);
34

  
35
    @Override
36
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
37
        response.setContentType("text/html");
38
        PrintWriter printWriter = response.getWriter();
39

  
40
        String formUsername = request.getParameter("username").trim();
41
        String formVerificationCode = request.getParameter("verification_code").trim();
42

  
43
        if (InputValidator.isFilled(formUsername) && InputValidator.isFilled(formVerificationCode)) {
44
            if (verificationActions.verificationEntryExists(formUsername) && verificationActions.verificationCodeIsCorrect(formUsername, formVerificationCode)) {
45
                if (!verificationActions.verificationCodeHasExpired(formUsername)) {
46
                    HttpSession session = request.getSession();
47
                    session.setAttribute("username", formUsername);
48
                    response.sendRedirect("./resetPassword.jsp");
49
                } else {
50
                    logger.info("Verification code has expired!");
51
                    response.sendRedirect(UrlConstructor.getRedirectUrl(request, "expiredVerificationCode.jsp"));
52
                }
53
            } else {
54
                logger.info("Username or verification code are not valid!");
55
                request.getSession().setAttribute("message", "Username or verification code are not valid.");
56
                response.sendRedirect("./verify.jsp");
57
            }
58
        } else {
59
            if (!InputValidator.isFilled(formUsername)) {
60
                logger.info("No username");
61
                request.getSession().setAttribute("msg_username_error", "Please enter your username.");
62
            }
63
            if (!InputValidator.isFilled(formVerificationCode)) {
64
                logger.info("No verification code");
65
                request.getSession().setAttribute("msg_verification_code_error", "Please enter your verification code.");
66
            }
67
            response.sendRedirect("./verify.jsp");
68
            }
69

  
70
        printWriter.close();
71
    }
72
}
modules/dnet-openaire-users/branches/login/src/main/java/eu/dnetlib/openaire/usermanagement/RemindUsernameServlet.java
1
package eu.dnetlib.openaire.usermanagement;
2

  
3
import com.unboundid.ldap.sdk.LDAPException;
4
import eu.dnetlib.openaire.user.utils.EmailSender;
5
import eu.dnetlib.openaire.user.utils.LDAPActions;
6
import eu.dnetlib.openaire.user.utils.VerifyRecaptcha;
7
import eu.dnetlib.openaire.usermanagement.utils.UrlConstructor;
8
import org.apache.commons.validator.routines.EmailValidator;
9
import org.apache.log4j.Logger;
10
import org.springframework.beans.factory.annotation.Autowired;
11
import org.springframework.beans.factory.annotation.Value;
12
import org.springframework.stereotype.Component;
13
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
14

  
15
import javax.mail.MessagingException;
16
import javax.servlet.ServletConfig;
17
import javax.servlet.ServletException;
18
import javax.servlet.http.HttpServlet;
19
import javax.servlet.http.HttpServletRequest;
20
import javax.servlet.http.HttpServletResponse;
21
import javax.servlet.http.HttpSession;
22
import java.io.IOException;
23

  
24
/**
25
 * Created by kiatrop on 2/10/2017.
26
 */
27
@Component
28
public class RemindUsernameServlet extends HttpServlet {
29

  
30
    @Autowired
31
    private LDAPActions ldapActions;
32

  
33
    @Autowired
34
    private EmailSender emailSender;
35

  
36
    @Value("${oidc.home}")
37
    private String oidcHomeUrl;
38

  
39
    @Value("${google.recaptcha.secret}")
40
    private String secret;
41

  
42
    @Value("${google.recaptcha.key}")
43
    private String sitekey;
44

  
45
    private static final Logger logger = Logger.getLogger(RemindUsernameServlet.class);
46

  
47
    public void init(ServletConfig config) throws ServletException {
48
        super.init(config);
49
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
50
                config.getServletContext());
51
        config.getServletContext().setAttribute("sitekey", sitekey);
52

  
53
    }
54

  
55
    @Override
56
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
57
        String formEmail = request.getParameter("email").trim();
58

  
59
        String gRecaptchaResponse = request.getParameter("g-recaptcha-response");
60

  
61
        HttpSession session = request.getSession();
62
        session.setAttribute("homeUrl", oidcHomeUrl);
63

  
64
        if (formEmail == null) {
65
            request.getSession().setAttribute("message", "Error reading email.");
66
            response.sendRedirect("./remindUsername.jsp");
67

  
68
        } else if (formEmail.isEmpty()) {
69
            request.getSession().setAttribute("message", "Please enter your email.");
70
            response.sendRedirect("./remindUsername.jsp");
71

  
72
        } else if (!EmailValidator.getInstance().isValid(formEmail)) {
73
            request.getSession().setAttribute("message", "Please enter a valid email.");
74
            response.sendRedirect("./remindUsername.jsp");
75

  
76
        } else if (!VerifyRecaptcha.verify(gRecaptchaResponse, secret)) {
77
            request.getSession().setAttribute("message", "You missed the reCAPTCHA validation!");
78
            response.sendRedirect("./remindUsername.jsp");
79

  
80
        } else {
81

  
82
            try {
83
                String username = ldapActions.getUsername(formEmail);
84
                if (username != null && !username.isEmpty()) {
85
                    logger.info("Remind username to: "+username);
86
                    String verificationCodeMsg = "<p>Hello,</p>" +
87
                            "<p> A username reminder has been requested for your OpenAIRE account.</p>" +
88
                            "<p> Your username is " + username + ".</p>" +
89
                            "<p> Thank you, </p>" +
90
                            "<p> OpenAIRE technical team</p>";
91

  
92
                    String verificationCodeSubject = "Your OpenAIRE username";
93

  
94
                    emailSender.sendEmail(formEmail, verificationCodeSubject, verificationCodeMsg);
95

  
96
                    response.sendRedirect(UrlConstructor.getRedirectUrl(request, "emailSuccess.jsp"));
97

  
98
                } else {
99
                    request.getSession().setAttribute("message", "There is no user registered with that email.");
100
                    response.sendRedirect("./remindUsername.jsp");
101
                }
102

  
103
            } catch (LDAPException ldape) {
104
                logger.error("Could not find user with email " + formEmail, ldape);
105
                response.sendRedirect(UrlConstructor.getRedirectUrl(request, "error.jsp"));
106

  
107
            } catch (MessagingException e) {
108
                logger.error("Error in sending email", e);
109
                request.getSession().setAttribute("message", "Error sending email");
110
                response.sendRedirect(UrlConstructor.getRedirectUrl(request, "remindUsername.jsp"));
111
            }
112
        }
113
    }
114

  
115
    public String getOidcHomeUrl() {
116
        return oidcHomeUrl;
117
    }
118

  
119
    public void setOidcHomeUrl(String oidcHomeUrl) {
120
        this.oidcHomeUrl = oidcHomeUrl;
121
    }
122

  
123
}
124

  
125

  
modules/dnet-openaire-users/branches/login/src/main/java/eu/dnetlib/openaire/usermanagement/security/FrontEndLinkURIAuthenticationSuccessHandler.java
1
package eu.dnetlib.openaire.usermanagement.security;
2

  
3
import com.google.gson.Gson;
4
import org.apache.log4j.Logger;
5
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
6
import org.springframework.security.core.Authentication;
7
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
8

  
9
import javax.servlet.http.Cookie;
10
import javax.servlet.http.HttpServletRequest;
11
import javax.servlet.http.HttpServletResponse;
12
import java.io.IOException;
13

  
14
/**
15
 * Created by stefanos on 9/5/2017.
16
 */
17
public class FrontEndLinkURIAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
18

  
19
    private static final Logger logger = Logger.getLogger(FrontEndLinkURIAuthenticationSuccessHandler.class);
20

  
21
    private String frontEndURI;
22
    private String frontPath;
23
    private String frontDomain;
24

  
25
    @Override
26
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IllegalArgumentException, IOException   {
27

  
28
        OIDCAuthenticationToken authOIDC = (OIDCAuthenticationToken) authentication;
29

  
30
        try {
31

  
32
//            Cookie jwt = new Cookie("XCsrfToken", JWTGenerator.generateToken(authOIDC, "my-very-secret"));
33
            Cookie openAIREUser = new Cookie("openAIREUser",  new Gson().toJson(JWTGenerator.generateJsonToken(authOIDC)));
34
            Cookie accessToken = new Cookie("AccessToken", authOIDC.getAccessTokenValue());
35

  
36
            // Expire the cookies in four hours (4 * 3600)
37
//            jwt.setMaxAge(14400);
38
            openAIREUser.setMaxAge(14400);
39
            accessToken.setMaxAge(14400);
40

  
41
            //TODO DELETE LOG
42
            logger.info("\n////////////////////////////////////////////////////////////////////////////////////////////////\n");
43
//            logger.info("jwt: " + JWTGenerator.generateToken(authOIDC, "my-very-secret"));
44
            logger.info("access token: " + authOIDC.getAccessTokenValue());
45
            logger.info("openAIREUser: " + JWTGenerator.generateJsonToken(authOIDC));
46
            logger.info("\n////////////////////////////////////////////////////////////////////////////////////////////////\n");
47

  
48
            //TODO DELETE LOG
49
//            logger.info("\n////////////////////////////////////////////////////////////////////////////////////////////////\n");
50
//            logger.info("refresh token: " + authOIDC.getRefreshTokenValue());
51
//            logger.info("\n////////////////////////////////////////////////////////////////////////////////////////////////\n");
52

  
53

  
54
//            jwt.setPath(frontPath);
55
            openAIREUser.setPath(frontPath);
56
            accessToken.setPath(frontPath);
57

  
58
            if (frontDomain!=null) {
59
//                jwt.setDomain(frontDomain);
60
                openAIREUser.setDomain(frontDomain);
61
                accessToken.setDomain(frontDomain);
62
            }
63

  
64
//            response.addCookie(jwt);
65
            response.addCookie(openAIREUser);
66
            response.addCookie(accessToken);
67
            response.sendRedirect(frontEndURI);
68

  
69
        } catch (IOException e) {
70
            logger.error("IOException in redirection ", e);
71
            throw new IOException(e);
72
        }catch (IllegalArgumentException e) {
73
            logger.error("IllegalArgumentException in redirection ", e);
74
            throw new IllegalArgumentException(e);
75
        }
76

  
77
    }
78

  
79
    public String getFrontEndURI() {
80
        return frontEndURI;
81
    }
82

  
83
    public void setFrontEndURI(String frontEndURI) {
84
        this.frontEndURI = frontEndURI;
85
    }
86

  
87
    public String getFrontPath() {
88
        return frontPath;
89
    }
90

  
91
    public void setFrontPath(String frontPath) {
92
        this.frontPath = frontPath;
93
    }
94

  
95
    public String getFrontDomain() {
96
        return frontDomain;
97
    }
98

  
99
    public void setFrontDomain(String frontDomain) {
100
        this.frontDomain = frontDomain;
101
    }
102
}
103

  
104

  
modules/dnet-openaire-users/branches/login/src/main/java/eu/dnetlib/openaire/usermanagement/security/JWTGenerator.java
1
package eu.dnetlib.openaire.usermanagement.security;
2

  
3
import com.google.gson.JsonObject;
4
import eu.dnetlib.openaire.user.pojos.migration.MigrationUser;
5
import io.jsonwebtoken.Claims;
6
import io.jsonwebtoken.Jwts;
7
import io.jsonwebtoken.SignatureAlgorithm;
8
import org.apache.log4j.Logger;
9
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
10
import org.mitre.openid.connect.model.UserInfo;
11

  
12
import java.io.UnsupportedEncodingException;
13
import java.net.URLEncoder;
14
import java.text.ParseException;
15
import java.util.Date;
16

  
17
public class JWTGenerator {
18

  
19
    private static final Logger logger = Logger.getLogger(JWTGenerator.class);
20

  
21
    public static String generateToken(MigrationUser u, String secret) {
22
        Claims claims = Jwts.claims().setSubject(u.getUsername());
23
        claims.put("fullname", u.getFullname() + "");
24
        claims.put("userId", u.getId() + "");
25
        claims.put("email", u.getEmail() + "");
26
        claims.put("role", u.getRoleId());
27

  
28
        //expiration
29
        long nowMillis = System.currentTimeMillis();
30
        Date now = new Date(nowMillis);
31
        long ttlMillis = 1800000;
32
        long expMillis = nowMillis + ttlMillis;
33
        Date exp = new Date(expMillis);
34

  
35
        return Jwts.builder()
36
                .setClaims(claims)
37
                .setExpiration(exp)
38
                .signWith(SignatureAlgorithm.HS512, secret)
39
                .compact();
40
    }
41

  
42
    public static String generateToken(OIDCAuthenticationToken authOIDC, String secret) {
43

  
44
        try {
45

  
46
            JsonObject userInfo = authOIDC.getUserInfo().getSource();
47
            Claims claims = Jwts.claims().setSubject(authOIDC.getUserInfo().getSub());
48
            claims.put("fullname", URLEncoder.encode(authOIDC.getUserInfo().getName(), "UTF-8") + "");
49

  
50
            if (authOIDC.getUserInfo().getGivenName() == null){
51
                logger.info("User: " + authOIDC.getUserInfo().getName() + "doesn't have first name");
52
                claims.put("firstname", URLEncoder.encode(" ", "UTF-8") + "");
53
            } else {
54
                claims.put("firstname", URLEncoder.encode(authOIDC.getUserInfo().getGivenName(), "UTF-8") + "");
55
            }
56
            if (authOIDC.getUserInfo().getFamilyName() == null){
57
                logger.info("User: " + authOIDC.getUserInfo().getName() + "doesn't have first name");
58
                claims.put("lastname", URLEncoder.encode(" ", "UTF-8") + "");
59
            } else {
60
                claims.put("lastname", URLEncoder.encode(authOIDC.getUserInfo().getFamilyName(), "UTF-8") + "");
61
            }
62
            claims.put("email", authOIDC.getUserInfo().getEmail() + "");
63

  
64
//            if (userInfo.getAsJsonArray("eduPersonScopedAffiliation").toString() != null) {
65
//                claims.put("role", URLEncoder.encode(userInfo.getAsJsonArray("edu_person_scoped_affiliations").toString(), "UTF-8") + "");
66
//            }
67

  
68
            if (userInfo.getAsJsonArray("edu_person_entitlements") == null){
69
                logger.info("User: " + authOIDC.getUserInfo().getName() + "doesn't have role");
70
                claims.put("role", URLEncoder.encode(" ", "UTF-8") + "");
71
            } else {
72
                claims.put("role", URLEncoder.encode(userInfo.getAsJsonArray("edu_person_entitlements").toString(), "UTF-8") + "");
73
            }
74

  
75
            //TODO remove, We don't need it but if we are going to use it, we need to check if the user has affiliation
76
            //claims.put("edu_person_scoped_affiliations", URLEncoder.encode(userInfo.getAsJsonArray("edu_person_scoped_affiliations").toString(), "UTF-8") + "");
77

  
78
            //TODO remove
79
            //TODO THIS IS TEST
80
//            claims.put("fullname", URLEncoder.encode("Σοφία Μπαλτζή", "UTF-8") + "");
81
//            claims.put("firstname", URLEncoder.encode("Σοφία", "UTF-8") + "");
82
//            claims.put("lastname", URLEncoder.encode("Μπαλτζή", "UTF-8") + "");
83
//            claims.put("email", "sofie.mpl@gmail.com" + "");
84
//            claims.put("edu_person_scoped_affiliations", "faculty");
85

  
86
            Date exp = new Date(authOIDC.getIdToken().getJWTClaimsSet().getExpirationTime().getTime());
87
//            logger.info("expirationTime: "+ exp);
88

  
89
            //TODO DELETE LOGS
90
//            logger.info("\n////////////////////////////////////////////////////////////////////////////////////////////////\n");
91
//            logger.info("fullName: " + authOIDC.getUserInfo().getName());
92
//            logger.info("firstName: " + authOIDC.getUserInfo().getGivenName());
93
//            logger.info("lastName: " + authOIDC.getUserInfo().getFamilyName());
94
//            logger.info("email: " + authOIDC.getUserInfo().getEmail());
95
//            //logger.info("Check everything");
96
//            logger.info("locale: " + authOIDC.getUserInfo().getSource());
97
//            logger.info("role: " + userInfo.getAsJsonArray("edu_person_entitlements").toString());
98
//            //logger.info("affiliation: " + userInfo.getAsJsonArray("edu_person_scoped_affiliations").toString());
99
//            logger.info("expirationTime: " + exp);
100
//            logger.info("\n////////////////////////////////////////////////////////////////////////////////////////////////\n");
101

  
102
                return Jwts.builder()
103
                        .setClaims(claims)
104
                        .setExpiration(exp)
105
                        .signWith(SignatureAlgorithm.HS512, secret)
106
                        .compact();
107

  
108
        } catch (ParseException e) {
109
            e.printStackTrace();
110
            logger.error("JWT Parse Exception from getting Expiration Time ", e);
111
            return "error";
112
        } catch (UnsupportedEncodingException e) {
113
            e.printStackTrace();
114
            logger.error("UnsupportedEncodingException UTF-8 ", e);
115
            return "error";
116
        }
117
    }
118

  
119

  
120
     public static JsonObject generateJsonToken(OIDCAuthenticationToken authOIDC) {
121
         try {
122

  
123
            JsonObject userInfo = authOIDC.getUserInfo().getSource();
124
            JsonObject userInfo2 = new JsonObject();
125

  
126
            if (authOIDC.getUserInfo().getSub() == null) {
127
                logger.info("User doesn't have sub");
128
                userInfo2.addProperty("sub", "");
129
            } else {
130
                userInfo2.addProperty("sub", URLEncoder.encode(authOIDC.getUserInfo().getSub(), "UTF-8"));
131
            }
132
            if (authOIDC.getUserInfo().getName() == null) {
133
                logger.info("User doesn't have fullname");
134
                userInfo2.addProperty("fullname", "");
135
            } else {
136
                userInfo2.addProperty("fullname", URLEncoder.encode(authOIDC.getUserInfo().getName(), "UTF-8"));
137
            }
138
            if (authOIDC.getUserInfo().getGivenName() == null){
139
                logger.info("User: " + authOIDC.getUserInfo().getName() + "doesn't have first name");
140
//                userInfo2.addProperty("firstname", URLEncoder.encode(" ", "UTF-8") + "");
141
                userInfo2.addProperty("firstname", "");
142
            } else {
143
                userInfo2.addProperty("firstname", URLEncoder.encode(authOIDC.getUserInfo().getGivenName(), "UTF-8") + "");
144
            }
145
            if (authOIDC.getUserInfo().getFamilyName() == null){
146
                logger.info("User: " + authOIDC.getUserInfo().getName() + "doesn't have first name");
147
//                userInfo2.addProperty("lastname", URLEncoder.encode(" ", "UTF-8") + "");
148
                userInfo2.addProperty("lastname", "");
149
            } else {
150
                userInfo2.addProperty("lastname", URLEncoder.encode(authOIDC.getUserInfo().getFamilyName(), "UTF-8") + "");
151
            }
152
            userInfo2.addProperty("email", authOIDC.getUserInfo().getEmail() + "");
153

  
154
            if (userInfo.getAsJsonArray("edu_person_entitlements") == null){
155
                logger.info("User: " + authOIDC.getUserInfo().getName() + "doesn't have role");
156
//                userInfo2.addProperty("role", URLEncoder.encode(" ", "UTF-8") + "");
157
                userInfo2.addProperty("role", "");
158
            } else {
159
                userInfo2.addProperty("role", URLEncoder.encode(userInfo.getAsJsonArray("edu_person_entitlements").toString(), "UTF-8") + "");
160
            }
161

  
162
            logger.info("UserINFO: " + userInfo2.toString());
163
            return userInfo2;
164

  
165
        } catch (UnsupportedEncodingException e) {
166
            e.printStackTrace();
167
            logger.error("UnsupportedEncodingException UTF-8 ", e);
168
            JsonObject error = new JsonObject();
169
            error.addProperty("error", "UnsupportedEncodingException UTF-8 " + e);
170
            return error;
171
        }
172

  
173
     }
174

  
175
    //TODO DELETE IF IT IS NOT NECESSARY
176
    public static String generateAccessToken(OIDCAuthenticationToken authOIDC, String secret) {
177
        Claims claims = Jwts.claims().setId(authOIDC.getAccessTokenValue());
178

  
179
        //TODO DELETE LOGS
180
        logger.info("\n////////////////////////////////////////////////////////////////////////////////////////////////\n");
181
        logger.info("access token: " + authOIDC.getAccessTokenValue());
182
        logger.info("\n////////////////////////////////////////////////////////////////////////////////////////////////\n");
183

  
184
        return Jwts.builder()
185
                .setClaims(claims)
186
                .signWith(SignatureAlgorithm.HS512, secret)
187
                .compact();
188
    }
189

  
190

  
191
    public static String generateToken(UserInfo user, String secret) {
192
        try {
193

  
194
            JsonObject userInfo = user.getSource();
195

  
196
            Claims claims = Jwts.claims().setSubject(user.getSub());
197
            claims.put("email", user.getEmail() + "");
198
            claims.put("role", URLEncoder.encode(userInfo.getAsJsonArray("edu_person_entitlements").toString(), "UTF-8") + "");
199

  
200
            return Jwts.builder()
201
                    .setClaims(claims)
202
                    .signWith(SignatureAlgorithm.HS512, secret)
203
                    .compact();
204
        } catch (UnsupportedEncodingException e) {
205
            e.printStackTrace();
206
            logger.error("UnsupportedEncodingException UTF-8 ", e);
207
            return "error";
208
        }
209
    }
210

  
211
}
212

  
213

  
214

  
215

  
216
// How to add it manually
217
//        long nowMillis = System.currentTimeMillis();
218
//        //This is my token
219
//        try {
220
//            String jwt = Jwts.builder()
221
//                    .setSubject("Argiro")
222
//                    .setExpiration(new Date(nowMillis+1800000))
223
//                    .claim("fullname", "Argiro Kokogianaki")
224
//                    .claim("id", "8")
225
//                    .claim("email", "argiro@gmail.com")
226
//                    .claim("role","2")
227
//                    .signWith(
228
//                            SignatureAlgorithm.HS512,
229
//                            "my-very-secret".getBytes("UTF-8")
230
//                    )
231
//                    .compact();
modules/dnet-openaire-users/branches/login/src/main/java/eu/dnetlib/openaire/usermanagement/ForgotPasswordServlet.java
1
package eu.dnetlib.openaire.usermanagement;
2

  
3
import com.unboundid.ldap.sdk.LDAPException;
4
import eu.dnetlib.openaire.user.utils.*;
5
import eu.dnetlib.openaire.usermanagement.utils.UrlConstructor;
6
import org.apache.commons.validator.routines.EmailValidator;
7
import org.apache.log4j.Logger;
8
import org.springframework.beans.factory.annotation.Autowired;
9
import org.springframework.beans.factory.annotation.Value;
10
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
11

  
12
import javax.mail.MessagingException;
13
import javax.servlet.ServletConfig;
14
import javax.servlet.ServletException;
15
import javax.servlet.http.HttpServlet;
16
import javax.servlet.http.HttpServletRequest;
17
import javax.servlet.http.HttpServletResponse;
18
import java.io.IOException;
19
import java.sql.Timestamp;
20
import java.util.Date;
21
import java.util.UUID;
22
/**
23
 * Created by kiatrop on 28/9/2017.
24
 */
25

  
26
public class ForgotPasswordServlet extends HttpServlet {
27

  
28
    @Autowired
29
    private LDAPActions ldapActions;
30

  
31
    @Autowired
32
    private VerificationActions verificationActions;
33

  
34
    @Autowired
35
    private EmailSender emailSender;
36

  
37
    @Value("${google.recaptcha.secret}")
38
    private String secret;
39

  
40
    @Value("${google.recaptcha.key}")
41
    private String sitekey;
42

  
43
    private Logger logger = Logger.getLogger(ForgotPasswordServlet.class);
44

  
45
    public void init(ServletConfig config) throws ServletException {
46
        super.init(config);
47
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
48
                config.getServletContext());
49
        config.getServletContext().setAttribute("sitekey", sitekey);
50

  
51
    }
52

  
53
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
54

  
55
        String formEmail = request.getParameter("email").trim();
56
        String gRecaptchaResponse = request.getParameter("g-recaptcha-response");
57

  
58

  
59
        if (formEmail == null) {
60
            request.getSession().setAttribute("message", "Error reading email.");
61
            response.sendRedirect("./forgotPassword.jsp");
62
        } else if (formEmail.isEmpty()) {
63
            request.getSession().setAttribute("message", "Please enter your email.");
64
            response.sendRedirect("./forgotPassword.jsp");
65
        } else if (!EmailValidator.getInstance().isValid(formEmail)) {
66
            request.getSession().setAttribute("message", "Please enter a valid email.");
67
            response.sendRedirect("./forgotPassword.jsp");
68
        } else if (!VerifyRecaptcha.verify(gRecaptchaResponse, secret)) {
69
            request.getSession().setAttribute("message", "You missed the reCAPTCHA validation!");
70
            response.sendRedirect("./forgotPassword.jsp");
71
        } else {
72
            try {
73
                String username = ldapActions.getUsername(formEmail);
74
                if (username == null || username.isEmpty()) {
75
                    request.getSession().setAttribute("message", "There is no user registered with that email.");
76
                    response.sendRedirect("./forgotPassword.jsp");
77
                } else {
78
                    UUID verificationCode = UUID.randomUUID();
79
                    Date creationDate = new Date();
80
                    String vCode = verificationCode.toString();
81

  
82
                    Timestamp timestamp = new Timestamp(creationDate.getTime());
83

  
84
                    if (!verificationActions.verificationEntryExists(username)) {
85
                        verificationActions.addVerificationEntry(username, vCode, timestamp);
86

  
87
                    } else {
88
                        verificationActions.updateVerificationEntry(username, vCode, timestamp);
89
                    }
90

  
91
                    String resultPath = UrlConstructor.getRedirectUrl(request, "verify.jsp");
92
                    String resultPathWithVCode = UrlConstructor.getVerificationLink(resultPath, vCode);
93

  
94
                    String verificationCodeMsg = "<p>Hello,</p>" +
95
                            "<p> A request has been made to reset your OpenAIRE account password. To reset your " +
96
                            "password, you will need to submit this verification code in order to verify that the " +
97
                            "request was legitimate.</p>" +
98
                            "<p> The verification code is " + vCode + "</p>" +
99
                            "Click the URL below and proceed with verification." +
100
                            "<p><a href=" + resultPathWithVCode + ">" + resultPathWithVCode + "</a></p>" +
101
                            "<p>The verification code is valid for 24 hours.</p>" +
102
                            "<p>Thank you,</p>" +
103
                            "<p>OpenAIRE technical team</p>";
104

  
105
                    String verificationCodeSubject = "Your OpenAIRE password reset request";
106

  
107
                    emailSender.sendEmail(formEmail, verificationCodeSubject, verificationCodeMsg);
108

  
109
                    response.setContentType("text/html");
110
                    response.sendRedirect("./verify.jsp");
111
                }
112

  
113
            } catch (LDAPException ldape) {
114
                logger.error("LDAP error", ldape);
115
                response.sendRedirect(UrlConstructor.getRedirectUrl(request, "error.jsp"));
116
            } catch (MessagingException e) {
117
                logger.error("Error in sending email", e);
118
                request.getSession().setAttribute("message", "Error sending email.");
119
                response.sendRedirect("./forgotPassword.jsp");
120
            }
121
        }
122
    }
123
}
modules/dnet-openaire-users/branches/login/src/main/java/eu/dnetlib/openaire/usermanagement/registry/beans/Config.java
1
package eu.dnetlib.openaire.usermanagement.registry.beans;
2

  
3
import org.apache.log4j.Logger;
4
import org.springframework.beans.factory.annotation.Value;
5
import org.springframework.context.annotation.Bean;
6
import org.springframework.context.annotation.Configuration;
7
import org.springframework.context.annotation.PropertySource;
8
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
9
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
10
import org.springframework.session.web.http.CookieSerializer;
11
import org.springframework.session.web.http.DefaultCookieSerializer;
12

  
13
/**
14
 * Created by stefanos on 14/6/2017.
15
 */
16
@PropertySource(value = { "classpath:eu/dnet/openaire/usermanagement/redis.properties", "classpath:eu/dnet/openaire/usermanagement/springContext-dnetOpenaireUsersService.properties"} )
17
@Configuration
18
@EnableRedisHttpSession
19
public class Config {
20

  
21
    private static Logger logger = Logger.getLogger(Config.class);
22

  
23
    @Value("${redis.host:localhost}")
24
    private String host;
25

  
26
    @Value("${redis.port:6379}")
27
    private String port;
28

  
29
    @Value("${redis.password:#{null}}")
30
    private String password;
31

  
32
    @Value("${webbapp.front.domain:.openaire.eu}")
33
    private String domain;
34

  
35
    @Bean
36
    public LettuceConnectionFactory connectionFactory() {
37
        logger.info(String.format("Redis connection listens to %s:%s ",host,port));
38
        LettuceConnectionFactory factory = new LettuceConnectionFactory(host,Integer.parseInt(port));
39
        if(password != null) factory.setPassword(password);
40
        return factory;
41
    }
42

  
43
    @Bean
44
    public CookieSerializer cookieSerializer() {
45
        logger.info("Cookie Serializer: Domain is "+domain);
46
        DefaultCookieSerializer serializer = new DefaultCookieSerializer();
47
        serializer.setCookieName("openAIRESession"); // <1>
48
        serializer.setCookiePath("/"); // <2>
49
//        serializer.setDomainNamePattern(""); //with value "" set's the domain of the service e.g scoobydoo.di.uoa.gr
50
        serializer.setDomainName(domain);
51
        return serializer;
52
    }
53
}
modules/dnet-openaire-users/branches/login/src/main/java/eu/dnetlib/openaire/usermanagement/RegisterServlet.java
1
package eu.dnetlib.openaire.usermanagement;
2

  
3
import com.unboundid.ldap.sdk.LDAPException;
4
import eu.dnetlib.openaire.user.utils.EmailSender;
5
import eu.dnetlib.openaire.user.utils.InputValidator;
6
import org.apache.commons.validator.routines.EmailValidator;
7
import eu.dnetlib.openaire.user.utils.LDAPActions;
8
import eu.dnetlib.openaire.user.utils.VerificationActions;
9
import eu.dnetlib.openaire.user.utils.VerifyRecaptcha;
10
import eu.dnetlib.openaire.usermanagement.utils.UrlConstructor;
11
import org.apache.log4j.Logger;
12
import org.springframework.beans.factory.annotation.Autowired;
13
import org.springframework.beans.factory.annotation.Value;
14
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
15

  
16
import javax.mail.MessagingException;
17
import javax.mail.internet.AddressException;
18
import javax.mail.internet.InternetAddress;
19
import javax.servlet.ServletConfig;
20
import javax.servlet.ServletException;
21
import javax.servlet.http.HttpServlet;
22
import javax.servlet.http.HttpServletRequest;
23
import javax.servlet.http.HttpServletResponse;
24
import java.io.IOException;
25
import java.io.PrintWriter;
26
import java.sql.Timestamp;
27
import java.util.Date;
28
import java.util.UUID;
29

  
30
/**
31
 * Created by sofia on 20/10/2017.
32
 */
33
public class RegisterServlet extends HttpServlet {
34

  
35
    @Autowired
36
    private VerificationActions verificationActions;
37

  
38
    @Autowired
39
    private EmailSender emailSender;
40

  
41
    @Autowired
42
    private LDAPActions ldapActions;
43

  
44
    @Value("${google.recaptcha.secret}")
45
    private String secret;
46

  
47
    @Value("${google.recaptcha.key}")
48
    private String sitekey;
49

  
50

  
51
    public void init(ServletConfig config) throws ServletException {
52
        super.init(config);
53
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
54
                config.getServletContext());
55
        config.getServletContext().setAttribute("sitekey", sitekey);
56
    }
57

  
58
    private static Logger logger = Logger.getLogger(RegisterServlet.class);
59

  
60
        @Override
61
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
62
        response.setContentType("text/html");
63
        PrintWriter printWriter = response.getWriter();
64

  
65
        String firstName = request.getParameter("first_name").trim();
66
        String lastName = request.getParameter("last_name").trim();
67
        String organization = request.getParameter("organization").trim();
68
        String username = request.getParameter("username").trim();
69
        String email =request.getParameter("email").trim();
70
        String confirmEmail = request.getParameter("email_conf").trim();
71
        String password = request.getParameter("password");
72
        String confirmPassword = request.getParameter("password_conf");
73

  
74
        String gRecaptchaResponse = request.getParameter("g-recaptcha-response");
75

  
76
        boolean isRecaptchaVerified = VerifyRecaptcha.verify(gRecaptchaResponse, secret);
77
        //System.out.println("RESPONSE " + gRecaptchaResponse);
78

  
79
        if (organization == null){
80
            logger.info("organization is null");
81
        }
82

  
83
        if (firstName != null && lastName != null &&  username != null && email!= null &&
84
                email.equals(confirmEmail) && password!= null && password.equals(confirmPassword) &&
85
                EmailValidator.getInstance().isValid(email) && InputValidator.isValidPassword(password) && isRecaptchaVerified) {
86

  
87
            try {
88
                 if (InputValidator.isValidUsername(username) && !ldapActions.usernameExists(username) && !ldapActions.emailExists(email)
89
                         && !ldapActions.isZombieUsersEmail(email) && !ldapActions.isZombieUsersUsername(username) && EmailValidator.getInstance().isValid(email)) {
90

  
91
                     ldapActions.createZombieUser(username, email, firstName, lastName, organization, password);
92
                     logger.info("Zombie user successfully created");
93

  
94
                     UUID verificationCode = UUID.randomUUID();
95
                     Date creationDate = new Date();
96
                     String vCode = verificationCode.toString();
97

  
98
                     Timestamp timestamp = new Timestamp(creationDate.getTime());
99

  
100
                     if (!verificationActions.verificationEntryExists(username)) {
101
                         verificationActions.addVerificationEntry(username, vCode, timestamp);
102

  
103
                     } else {
104
                         verificationActions.updateVerificationEntry(username, vCode, timestamp);
105
                     }
106

  
107
                     String resultPath = UrlConstructor.getRedirectUrl(request, "activate.jsp");
108
                     String resultPathWithVCode = UrlConstructor.getVerificationLink(resultPath, vCode);
109

  
110
                     String verificationCodeMsg = "<p>Hello " + username + ",</p>" +
111
                             "<p> A request has been made to verify your email and activate your OpenAIRE account. To activate your " +
112
                             "account, you will need to submit your username and this activation code in order to verify that the " +
113
                             "request was legitimate.</p>" +
114
                             "<p>" +
115
                             "The activation code is " + vCode +
116
                             "</p>" +
117
                             "Click the URL below and proceed with activating your password." +
118
                             "<p><a href=" + resultPathWithVCode + ">" + resultPathWithVCode + "</a></p>" +
119
                             "<p>The activation code is valid for 24 hours.</p>" +
120
                             "<p>Thank you,</p>" +
121
                             "<p>OpenAIRE technical team</p>";
122

  
123
                     String verificationCodeSubject = "Activate your OpenAIRE account";
124

  
125
                     emailSender.sendEmail(email, verificationCodeSubject, verificationCodeMsg);
126

  
127
                     response.sendRedirect("./activate.jsp");
128

  
129
                 } else {
130

  
131
                     validateUsername(request, username);
132

  
133
                     if (ldapActions.usernameExists(username) || ldapActions.isZombieUsersUsername(username)) {
134
                        request.getSession().setAttribute("username_message", "Username already exists! Choose another one.");
135
                        logger.info("Username already exists");
136
                     }
137

  
138
                     if (!EmailValidator.getInstance().isValid(email)) {
139
                         request.getSession().setAttribute("email_message", "Please enter a valid email.");
140
                         logger.info("Invalid email.");
141
                     }
142

  
143
                     if (ldapActions.emailExists(email)) {
144
                         request.getSession().setAttribute("email_message", "There is another user with this email.");
145
                         logger.info("There is another user with this email");
146
                     }
147

  
148
                     if (ldapActions.isZombieUsersEmail(email)) {
149
                         request.getSession().setAttribute("email_message", "You have already registered with this email address! Please check your email to activate your account or contact OpenAIRE <a href=\"https://www.openaire.eu/support/helpdesk\">helpdesk</a>.");
150
                         logger.info("There is another user with this email");
151
                     }
152

  
153
                     request.getSession().setAttribute("first_name", firstName);
154
                     request.getSession().setAttribute("msg_first_name_error_display", "display:none");
155

  
156
                     request.getSession().setAttribute("last_name", lastName);
157
                     request.getSession().setAttribute("msg_last_name_error_display", "display:none");
158

  
159
                     request.getSession().setAttribute("organization", organization);
160
                     request.getSession().setAttribute("username", username);
161
                     request.getSession().setAttribute("email", email);
162
                     request.getSession().setAttribute("msg_email_error_display", "display:none" );
163

  
164
                     request.getSession().setAttribute("email_conf", confirmEmail);
165
                     request.getSession().setAttribute("msg_email_conf_error_display", "display:none");
166
                     request.getSession().setAttribute("msg_email_validation_error_display", "display:none");
167

  
168
                     request.getSession().setAttribute("msg_password_error_display", "display:none" );
169
                     request.getSession().setAttribute("msg_pass_conf_error_display", "display:none" );
170
                     request.getSession().setAttribute("msg_invalid_password_display", "display:none");
171

  
172
                     request.getSession().setAttribute("recaptcha_error_display", "display:none");
173

  
174
                     response.sendRedirect("./register.jsp");
175
                 }
176

  
177

  
178
            } catch (MessagingException e) {
179
                logger.error("Error in sending email", e);
180
                request.getSession().setAttribute("message","Error sending email");
181
                response.sendRedirect(UrlConstructor.getRedirectUrl(request, ".register.jsp"));
182

  
183
                //TODO better handling of these exceprions
184
            } catch (Exception e) {
185
                logger.error("LDAP error in creating user", e);
186
                response.sendRedirect(UrlConstructor.getRedirectUrl(request, "error.jsp"));
187
            }
188

  
189
        } else {
190

  
191
            request.getSession().setAttribute("first_name", firstName);
192
            request.getSession().setAttribute("last_name", lastName);
193
            request.getSession().setAttribute("organization", organization);
194
            request.getSession().setAttribute("username", username);
195
            request.getSession().setAttribute("email", email);
196
            request.getSession().setAttribute("email_conf", confirmEmail);
197

  
198
            if (!InputValidator.isFilled(firstName)) {
199
                logger.info("No first name");
200
                request.getSession().setAttribute("msg_first_name_error_display", "display:block" );
201
            }
202

  
203
            if (!InputValidator.isFilled(lastName)) {
204
                logger.info("No last name");
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff