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.mitre.openid.connect.model.OIDCAuthenticationToken;
13
import org.springframework.beans.factory.annotation.Autowired;
14
import org.springframework.security.core.context.SecurityContextHolder;
15
import org.springframework.stereotype.Service;
16

    
17
import javax.servlet.ServletConfig;
18
import javax.servlet.ServletException;
19
import java.util.ArrayList;
20
import java.util.Arrays;
21
import java.util.List;
22
import java.util.regex.Pattern;
23

    
24
/**
25
 * Created by nikonas on 12/7/15.
26
 */
27
@Service("userService")
28
public class UserServiceImpl extends SpringGwtRemoteServiceServlet implements UserService {
29

    
30
    private static final Logger LOGGER = Logger
31
            .getLogger(UserServiceImpl.class);
32

    
33
    @Autowired
34
    private UserApi userAPI;
35

    
36
    @Autowired
37
    private EmailUtils emailUtils;
38

    
39

    
40
    public void init(ServletConfig config) throws ServletException {
41

    
42
        LOGGER.info("initializing user service impl ");
43
        super.init(config);
44

    
45
    }
46

    
47
    @Override
48
    public Tuple<UserProfile, String> login(String email_username, String password) throws UserAccessException {
49
        LOGGER.info("Checking credentials for user " + email_username);
50
        try {
51

    
52
            String email = email_username;
53

    
54
            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])?$");
55
            if (!rfc2822.matcher(email_username.trim().toLowerCase()).matches()) {
56
                LOGGER.debug("user logged in using username");
57
                email = this.userAPI.getEmailFromUsername(email_username);
58
            }
59
            if (email == null) {
60
                throw new UserAccessException("login.userNotExists", UserAccessException.ErrorCode.INVALID_USERNAME);
61
            }
62
            if (!this.userAPI.userExists(email)) {
63
                throw new UserAccessException("login.userNotExists", UserAccessException.ErrorCode.INVALID_USERNAME);
64
            }
65
            if (!this.userAPI.isUserActivated(email)) {
66
                throw new UserAccessException("login.notActivated", UserAccessException.ErrorCode.NOT_ACTIVATED);
67
            }
68
            if (!this.userAPI.correctCreds(email, password)) {
69
                throw new UserAccessException("login.InvalidPassword", UserAccessException.ErrorCode.INVALID_PASSWORD);
70
            }
71

    
72
            UserProfile userProfile = this.userAPI.getUser(email);
73
            String role = "";
74

    
75
            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"};
76
            if(Arrays.asList(adminEmails).contains(userProfile.getEmail()))
77
                role = "admin";
78

    
79
            return new Tuple<>(userProfile, role);
80

    
81
        } catch (Exception e) {
82
            LOGGER.error("An error occurred while checking credentials for user " + email_username, e);
83
            emailUtils.reportException(e);
84

    
85
            if (e instanceof UserAccessException) {
86
                throw (UserAccessException) e;
87
            }
88
            else {
89
                throw new UserAccessException("login.generalError", UserAccessException.ErrorCode.GENERAL_ERROR);
90
            }
91
        }
92

    
93
    }
94

    
95
    @Override
96
    public Tuple<UserProfile, String> getUserByEmail(String email) throws UserAccessException {
97
        LOGGER.info("Getting user with email " + email);
98
        try {
99

    
100
            UserProfile userProfile = this.userAPI.getUser(email);
101
            String role = "";
102

    
103
            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"};
104
            if(Arrays.asList(adminEmails).contains(userProfile.getEmail()))
105
                role = "admin";
106

    
107
            return new Tuple<>(userProfile, role);
108

    
109
        } catch (Exception e) {
110
            LOGGER.error("An error occurred while getting user with email " + email, e);
111
            emailUtils.reportException(e);
112

    
113
            throw new UserAccessException("login.generalError", UserAccessException.ErrorCode.GENERAL_ERROR);
114
        }
115
    }
116

    
117
    @Override
118
    public void register(UserProfile userProfile) throws UserAccessException {
119

    
120
        try {
121
            LOGGER.info("Registering user " + userProfile.getEmail());
122

    
123
            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])?$");
124
            if (!rfc2822.matcher(userProfile.getEmail().trim().toLowerCase()).matches()) {
125
                throw new UserAccessException("login.notValidEmail", UserAccessException.ErrorCode.INVALID_EMAIL_FORMAT);
126
            }
127

    
128
            if (this.userAPI.usernameExists(userProfile.getUsername())) {
129
                throw new UserAccessException("login.usernameAlreadyExists", UserAccessException.ErrorCode.USERNAME_ALREADY_EXISTS);
130
            }
131
            if (this.userAPI.userExists(userProfile.getEmail())) {
132
                throw new UserAccessException("login.mailAlreadyExists", UserAccessException.ErrorCode.MAIL_ALREADY_EXISTS);
133
            }
134

    
135
//            String activationId = "TEST";
136
            String activationId = this.userAPI.addUser(userProfile.getUsername(), userProfile.getEmail(), userProfile.getPassword(), userProfile.getFirstname(), userProfile.getLastname(), userProfile.getInstitution());
137

    
138
            emailUtils.sendActivationEmail(userProfile, activationId);
139

    
140
        } catch (Exception e) {
141
            LOGGER.error("Error while registering user " + userProfile.getEmail(), e);
142
            emailUtils.reportException(e);
143

    
144
            if (e instanceof UserAccessException)
145
                throw (UserAccessException) e;
146
            else
147
                throw new UserAccessException("login.generalError", UserAccessException.ErrorCode.GENERAL_ERROR);
148
        }
149

    
150
    }
151

    
152
    @Override
153
    public void activateUser(String activationId) throws UserAccessException {
154
        try {
155
            LOGGER.info("Activating user with activation with activation id " + activationId);
156

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

    
163
            if (e instanceof UserAccessException)
164
                throw (UserAccessException) e;
165
            else
166
                throw new UserAccessException("login.generalError", UserAccessException.ErrorCode.GENERAL_ERROR);
167
        }
168
    }
169

    
170
    @Override
171
    public void updateUser(UserProfile userProfile) throws UserAccessException {
172
        try {
173
            LOGGER.info("Editing user " + userProfile.getUsername());
174
            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])?$");
175
            if (!rfc2822.matcher(userProfile.getEmail().trim().toLowerCase()).matches()) {
176
                throw new UserAccessException("login.notValidEmail", UserAccessException.ErrorCode.INVALID_EMAIL_FORMAT);
177
            }
178

    
179
            String currentEmail = this.userAPI.getEmailFromUsername(userProfile.getUsername());
180
            if (!userProfile.getEmail().equalsIgnoreCase(currentEmail)) {
181
                if (this.userAPI.userExists(userProfile.getEmail())) {
182
                    throw new UserAccessException("login.mailAlreadyExists", UserAccessException.ErrorCode.MAIL_ALREADY_EXISTS);
183
                }
184
            }
185

    
186
            this.userAPI.editUser(userProfile);
187

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

    
197
    @Override
198
    public void prepareResetPassword(String email) throws UserAccessException {
199

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

    
209
            emailUtils.sendResetPasswordEmail(email, securityCode);
210

    
211
        } catch (Exception e) {
212
            LOGGER.error("Error while sending password recovery to user " + email, e);
213
            emailUtils.reportException(e);
214

    
215
            if (e instanceof UserAccessException)
216
                throw (UserAccessException) e;
217
            else
218
                throw new UserAccessException("login.generalError", UserAccessException.ErrorCode.GENERAL_ERROR);
219
        }
220
    }
221

    
222
    @Override
223
    public void resetPassword(String securityCode, String password) throws UserAccessException {
224
        try {
225
            LOGGER.debug("Reseting password with security code " + securityCode);
226

    
227
            if (securityCode.length() == 0) {
228
                throw new UserAccessException("resetPassword.wrongSecurityCode", UserAccessException.ErrorCode.WRONG_SECURITY_CODE);
229
            }
230

    
231
            this.userAPI.resetPassword(securityCode, password);
232

    
233
        } catch (Exception e) {
234
            LOGGER.error("Error while reseting password with security code " + securityCode);
235
            emailUtils.reportException(e);
236

    
237
            if (e instanceof UserAccessException)
238
                throw (UserAccessException) e;
239
            else
240
                throw new UserAccessException("login.generalError", UserAccessException.ErrorCode.GENERAL_ERROR);
241
        }
242
    }
243

    
244
    @Override
245
    public void resendActivation(String email) throws UserAccessException {
246

    
247
    }
248

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

    
261
            LOGGER.debug("User email -> " + userProfile.getEmail());
262

    
263
            String role = "";
264
            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"};
265
            if(Arrays.asList(adminEmails).contains(userProfile.getEmail()))
266
                role = "admin";
267
            return new Tuple<>(userProfile, role);
268
        } catch (Exception e) {
269
            LOGGER.debug("Error on security context holder",e);
270
            LOGGER.debug(Cookies.getCookie("currentUser"));
271
            throw e;
272
        }
273
    }
274

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

    
280
}
(5-5/6)