Project

General

Profile

1
package eu.dnetlib.repo.manager.server.services;
2

    
3
import com.google.gwt.user.client.Cookies;
4
import eu.dnetlib.domain.functionality.UserProfile;
5
import eu.dnetlib.gwt.server.service.SpringGwtRemoteServiceServlet;
6
import eu.dnetlib.repo.manager.client.services.UserService;
7
import eu.dnetlib.repo.manager.server.utils.EmailUtils;
8
import eu.dnetlib.repo.manager.shared.Tuple;
9
import eu.dnetlib.repo.manager.shared.UserAccessException;
10
import eu.dnetlib.users.UserApi;
11
import org.apache.log4j.Logger;
12
import org.eclipse.jetty.server.Authentication;
13
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
14
import org.springframework.beans.factory.annotation.Autowired;
15
import org.springframework.security.core.context.SecurityContextHolder;
16
import org.springframework.stereotype.Service;
17
import org.springframework.web.context.request.RequestContextHolder;
18

    
19
import javax.servlet.ServletConfig;
20
import javax.servlet.ServletException;
21
import javax.servlet.http.Cookie;
22
import javax.servlet.http.HttpSession;
23
import java.util.ArrayList;
24
import java.util.Arrays;
25
import java.util.List;
26
import java.util.regex.Pattern;
27

    
28
/**
29
 * Created by nikonas on 12/7/15.
30
 */
31
@Service("userService")
32
public class UserServiceImpl extends SpringGwtRemoteServiceServlet implements UserService {
33

    
34
    private static final Logger LOGGER = Logger
35
            .getLogger(UserServiceImpl.class);
36

    
37
    @Autowired
38
    private UserApi userAPI;
39

    
40
    @Autowired
41
    private EmailUtils emailUtils;
42

    
43

    
44
    public void init(ServletConfig config) throws ServletException {
45

    
46
        LOGGER.info("initializing user service impl ");
47
        super.init(config);
48

    
49
    }
50

    
51
    @Override
52
    public Tuple<UserProfile, String> login(String email_username, String password) throws UserAccessException {
53
        LOGGER.info("Checking credentials for user " + email_username);
54
        try {
55

    
56
            String email = email_username;
57

    
58
            Pattern rfc2822 = Pattern.compile("^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$");
59
            if (!rfc2822.matcher(email_username.trim().toLowerCase()).matches()) {
60
                LOGGER.debug("user logged in using username");
61
                email = this.userAPI.getEmailFromUsername(email_username);
62
            }
63
            if (email == null) {
64
                throw new UserAccessException("login.userNotExists", UserAccessException.ErrorCode.INVALID_USERNAME);
65
            }
66
            if (!this.userAPI.userExists(email)) {
67
                throw new UserAccessException("login.userNotExists", UserAccessException.ErrorCode.INVALID_USERNAME);
68
            }
69
            if (!this.userAPI.isUserActivated(email)) {
70
                throw new UserAccessException("login.notActivated", UserAccessException.ErrorCode.NOT_ACTIVATED);
71
            }
72
            if (!this.userAPI.correctCreds(email, password)) {
73
                throw new UserAccessException("login.InvalidPassword", UserAccessException.ErrorCode.INVALID_PASSWORD);
74
            }
75

    
76
            UserProfile userProfile = this.userAPI.getUser(email);
77
            String role = "";
78

    
79
            String[] adminEmails = new String[] {"stefania.martziou@gmail.com" , "antleb@di.uoa.gr", "ant.lebesis@gmail.com", "natalia@di.uoa.gr", "pedroprincipe@sdum.uminho.pt", "dpierrakos@gmail.com", "jochen.schirrwagen@uni-bielefeld.de", "aenne.loehden@uni-bielefeld.de"};
80
            if(Arrays.asList(adminEmails).contains(userProfile.getEmail()))
81
                role = "admin";
82

    
83
            return new Tuple<>(userProfile, role);
84

    
85
        } catch (Exception e) {
86
            LOGGER.error("An error occurred while checking credentials for user " + email_username, e);
87
            emailUtils.reportException(e);
88

    
89
            if (e instanceof UserAccessException) {
90
                throw (UserAccessException) e;
91
            }
92
            else {
93
                throw new UserAccessException("login.generalError", UserAccessException.ErrorCode.GENERAL_ERROR);
94
            }
95
        }
96

    
97
    }
98

    
99
    @Override
100
    public Tuple<UserProfile, String> getUserByEmail(String email) throws UserAccessException {
101
        LOGGER.info("Getting user with email " + email);
102
        try {
103

    
104
            UserProfile userProfile = this.userAPI.getUser(email);
105
            String role = "";
106

    
107
            String[] adminEmails = new String[] {"stefania.martziou@gmail.com" , "antleb@di.uoa.gr", "ant.lebesis@gmail.com", "natalia@di.uoa.gr", "pedroprincipe@sdum.uminho.pt", "dpierrakos@gmail.com", "jochen.schirrwagen@uni-bielefeld.de", "aenne.loehden@uni-bielefeld.de"};
108
            if(Arrays.asList(adminEmails).contains(userProfile.getEmail()))
109
                role = "admin";
110

    
111
            return new Tuple<>(userProfile, role);
112

    
113
        } catch (Exception e) {
114
            LOGGER.error("An error occurred while getting user with email " + email, e);
115
            emailUtils.reportException(e);
116

    
117
            throw new UserAccessException("login.generalError", UserAccessException.ErrorCode.GENERAL_ERROR);
118
        }
119
    }
120

    
121
    @Override
122
    public void register(UserProfile userProfile) throws UserAccessException {
123

    
124
        try {
125
            LOGGER.info("Registering user " + userProfile.getEmail());
126

    
127
            Pattern rfc2822 = Pattern.compile("^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$");
128
            if (!rfc2822.matcher(userProfile.getEmail().trim().toLowerCase()).matches()) {
129
                throw new UserAccessException("login.notValidEmail", UserAccessException.ErrorCode.INVALID_EMAIL_FORMAT);
130
            }
131

    
132
            if (this.userAPI.usernameExists(userProfile.getUsername())) {
133
                throw new UserAccessException("login.usernameAlreadyExists", UserAccessException.ErrorCode.USERNAME_ALREADY_EXISTS);
134
            }
135
            if (this.userAPI.userExists(userProfile.getEmail())) {
136
                throw new UserAccessException("login.mailAlreadyExists", UserAccessException.ErrorCode.MAIL_ALREADY_EXISTS);
137
            }
138

    
139
//            String activationId = "TEST";
140
            String activationId = this.userAPI.addUser(userProfile.getUsername(), userProfile.getEmail(), userProfile.getPassword(), userProfile.getFirstname(), userProfile.getLastname(), userProfile.getInstitution());
141

    
142
            emailUtils.sendActivationEmail(userProfile, activationId);
143

    
144
        } catch (Exception e) {
145
            LOGGER.error("Error while registering user " + userProfile.getEmail(), e);
146
            emailUtils.reportException(e);
147

    
148
            if (e instanceof UserAccessException)
149
                throw (UserAccessException) e;
150
            else
151
                throw new UserAccessException("login.generalError", UserAccessException.ErrorCode.GENERAL_ERROR);
152
        }
153

    
154
    }
155

    
156
    @Override
157
    public void activateUser(String activationId) throws UserAccessException {
158
        try {
159
            LOGGER.info("Activating user with activation with activation id " + activationId);
160

    
161
            if (!this.userAPI.activateUser(activationId))
162
                throw new UserAccessException("registration.okAccountAlreadyActivation", UserAccessException.ErrorCode.ALREADY_ACTIVATED);
163
        } catch (Exception e) {
164
            LOGGER.error("Error while activating user account with activation id " + activationId, e);
165
            emailUtils.reportException(e);
166

    
167
            if (e instanceof UserAccessException)
168
                throw (UserAccessException) e;
169
            else
170
                throw new UserAccessException("login.generalError", UserAccessException.ErrorCode.GENERAL_ERROR);
171
        }
172
    }
173

    
174
    @Override
175
    public void updateUser(UserProfile userProfile) throws UserAccessException {
176
        try {
177
            LOGGER.info("Editing user " + userProfile.getUsername());
178
            Pattern rfc2822 = Pattern.compile("^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$");
179
            if (!rfc2822.matcher(userProfile.getEmail().trim().toLowerCase()).matches()) {
180
                throw new UserAccessException("login.notValidEmail", UserAccessException.ErrorCode.INVALID_EMAIL_FORMAT);
181
            }
182

    
183
            String currentEmail = this.userAPI.getEmailFromUsername(userProfile.getUsername());
184
            if (!userProfile.getEmail().equalsIgnoreCase(currentEmail)) {
185
                if (this.userAPI.userExists(userProfile.getEmail())) {
186
                    throw new UserAccessException("login.mailAlreadyExists", UserAccessException.ErrorCode.MAIL_ALREADY_EXISTS);
187
                }
188
            }
189

    
190
            this.userAPI.editUser(userProfile);
191

    
192
        } catch (Exception e) {
193
            LOGGER.error("Error while editing user " + userProfile.getUsername(), e);
194
            if (e instanceof UserAccessException)
195
                throw (UserAccessException) e;
196
            else
197
                throw new UserAccessException("login.generalError", UserAccessException.ErrorCode.GENERAL_ERROR);
198
        }
199
    }
200

    
201
    @Override
202
    public void prepareResetPassword(String email) throws UserAccessException {
203

    
204
        try {
205
            LOGGER.debug("Sending password recovery to user " + email);
206
            if (!this.userAPI.userExists(email)) {
207
                throw new UserAccessException("login.userNotExists", UserAccessException.ErrorCode.INVALID_USERNAME);
208
            }
209
            List<String> to = new ArrayList<String>();
210
            to.add(email);
211
            String securityCode = this.userAPI.prepareResetPassword(email);
212

    
213
            emailUtils.sendResetPasswordEmail(email, securityCode);
214

    
215
        } catch (Exception e) {
216
            LOGGER.error("Error while sending password recovery to user " + email, e);
217
            emailUtils.reportException(e);
218

    
219
            if (e instanceof UserAccessException)
220
                throw (UserAccessException) e;
221
            else
222
                throw new UserAccessException("login.generalError", UserAccessException.ErrorCode.GENERAL_ERROR);
223
        }
224
    }
225

    
226
    @Override
227
    public void resetPassword(String securityCode, String password) throws UserAccessException {
228
        try {
229
            LOGGER.debug("Reseting password with security code " + securityCode);
230

    
231
            if (securityCode.length() == 0) {
232
                throw new UserAccessException("resetPassword.wrongSecurityCode", UserAccessException.ErrorCode.WRONG_SECURITY_CODE);
233
            }
234

    
235
            this.userAPI.resetPassword(securityCode, password);
236

    
237
        } catch (Exception e) {
238
            LOGGER.error("Error while reseting password with security code " + securityCode);
239
            emailUtils.reportException(e);
240

    
241
            if (e instanceof UserAccessException)
242
                throw (UserAccessException) e;
243
            else
244
                throw new UserAccessException("login.generalError", UserAccessException.ErrorCode.GENERAL_ERROR);
245
        }
246
    }
247

    
248
    @Override
249
    public void resendActivation(String email) throws UserAccessException {
250

    
251
    }
252

    
253
    @Override
254
    public Tuple<UserProfile, String> checkCookie() throws Exception {
255
        OIDCAuthenticationToken authentication;
256
        try {
257
            authentication = (OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
258
            UserProfile userProfile = new UserProfile();
259
            userProfile.setFirstname(authentication.getUserInfo().getGivenName());
260
            userProfile.setLastname(authentication.getUserInfo().getFamilyName());
261
            userProfile.setEmail(authentication.getUserInfo().getEmail());
262

    
263
            LOGGER.debug("User email -> " + userProfile.getEmail());
264

    
265
            String role = "";
266
            String[] adminEmails = new String[] {"stefania.martziou@gmail.com" , "antleb@di.uoa.gr", "ant.lebesis@gmail.com", "natalia@di.uoa.gr", "pedroprincipe@sdum.uminho.pt", "dpierrakos@gmail.com", "jochen.schirrwagen@uni-bielefeld.de", "aenne.loehden@uni-bielefeld.de"};
267
            if(Arrays.asList(adminEmails).contains(userProfile.getEmail()))
268
                role = "admin";
269
            return new Tuple<>(userProfile, role);
270
        } catch (Exception e) {
271
            LOGGER.debug("Error on security context holder",e);
272
            LOGGER.debug(Cookies.getCookie("currentUser"));
273
            throw e;
274
        }
275
    }
276

    
277
    @Override
278
    public void clearCookie(){
279
        SecurityContextHolder.clearContext();
280
    }
281

    
282
}
(5-5/6)