Project

General

Profile

1
package eu.dnetlib.goldoa.service.dao;
2

    
3
import eu.dnetlib.goldoa.domain.AccountAction;
4
import eu.dnetlib.goldoa.domain.Affiliation;
5
import eu.dnetlib.goldoa.domain.Budget;
6
import eu.dnetlib.goldoa.domain.Organization;
7
import eu.dnetlib.goldoa.domain.UserRole;
8
import eu.dnetlib.goldoa.domain.Project;
9
import eu.dnetlib.goldoa.domain.ProjectCoordinator;
10
import eu.dnetlib.goldoa.domain.Publisher;
11
import eu.dnetlib.goldoa.domain.Role;
12
import eu.dnetlib.goldoa.domain.User;
13
import eu.dnetlib.goldoa.service.UserManagerImpl;
14

    
15
import org.apache.commons.codec.digest.DigestUtils;
16
import org.hibernate.Criteria;
17
import org.hibernate.criterion.Order;
18
import org.hibernate.criterion.Restrictions;
19
import org.springframework.beans.factory.annotation.Autowired;
20
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
21
import org.springframework.jdbc.core.JdbcTemplate;
22
import org.springframework.jdbc.core.PreparedStatementSetter;
23
import org.springframework.jdbc.core.RowMapper;
24

    
25
import javax.sql.DataSource;
26
import java.sql.PreparedStatement;
27
import java.sql.ResultSet;
28
import java.sql.SQLException;
29
import java.sql.Timestamp;
30
import java.sql.Types;
31
import java.util.ArrayList;
32
import java.util.Date;
33
import java.util.List;
34

    
35
/**
36
 * Created by antleb on 3/13/15.
37
 */
38
public class UserDAO extends AbstractDao<String, User>{
39

    
40
	@Autowired
41
	private DataSource dataSource;
42

    
43
	private static final String GET_BY_ID =
44
			"select p.id, email, firstname, lastname, initials, password, telephone, active, orcidid, p.source, p.publisher, array_agg(distinct pro.project) as projects, array_agg(distinct a.organization||'||'||case when a.department is null then '' else a.department end||'||'||case when a.startdate is null then 0 else extract(epoch from a.startdate) end||'||'||case when a.enddate is null then 0 else extract(epoch from a.enddate) end) as affiliations, array_agg(distinct pr.role||'||'||pr.approved) as roles\n" +
45
					"from person p\n" +
46
					"left join person_role pr on p.id = pr.person\n" +
47
					"left join role r on r.id = pr.role\n" +
48
					"left join affiliation a on a.person = p.id\n" +
49
					"left join organisation o on o.id = a.organization\n" +
50
					"left join project_coordinator pro on pro.coordinator=p.id\n" +
51
					"where p.id = ?\n" +
52
					"group by p.id, p.email, firstname, lastname, initials, password, telephone, active, orcidid, p.source\n";
53

    
54
	private static final String GET_BY_EMAIL =
55
			"select p.id, email, firstname, lastname, initials, password, telephone, active, orcidid, p.source, p.publisher, array_agg(distinct pro.project) as projects, array_agg(distinct a.organization||'||'||case when a.department is null then '' else a.department end||'||'||case when a.startdate is null then 0 else extract(epoch from a.startdate) end||'||'||case when a.enddate is null then 0 else extract(epoch from a.enddate) end) as affiliations, array_agg(distinct pr.role||'||'||pr.approved) as roles\n" +
56
					"from person p\n" +
57
					"left join person_role pr on p.id = pr.person\n" +
58
					"left join role r on r.id = pr.role\n" +
59
					"left join affiliation a on a.person = p.id\n" +
60
					"left join organisation o on o.id = a.organization\n" +
61
					"left join project_coordinator pro on pro.coordinator=p.id\n" +
62
					"where email = ? and password is not null\n" +
63
					"group by p.id, p.email, firstname, lastname, initials, password, telephone, active, orcidid, p.source\n";
64

    
65
	private static final String GET_USERS =
66
			"select p.id, email, firstname, lastname, initials, password, telephone, active, orcidid, p.source, p.publisher, array_agg(distinct pro.project) as projects, array_agg(distinct a.organization||'||'||case when a.department is null then '' else a.department end||'||'||case when a.startdate is null then 0 else extract(epoch from a.startdate) end||'||'||case when a.enddate is null then 0 else extract(epoch from a.enddate) end) as affiliations, array_agg(distinct pr.role||'||'||pr.approved) as roles\n" +
67
					"from person p\n" +
68
					"left join person_role pr on p.id = pr.person\n" +
69
					"left join role r on r.id = pr.role\n" +
70
					"left join affiliation a on a.person = p.id\n" +
71
					"left join organisation o on o.id = a.organization\n" +
72
					"left join project_coordinator pro on pro.coordinator=p.id\n" +
73
					"where password is not null \n" +
74
					"group by p.id, p.email, firstname, lastname, initials, password, telephone, active, orcidid, p.source\n";
75

    
76
	private static final String INSERT_PERSON = "insert into person (email, firstname, lastname, initials, password, telephone, orcidid, source, publisher, id) values (?, ?, ?, ?, md5(?), ?, ?, ?, ?, ?);";
77

    
78
	private static final String UPDATE_PERSON = "update person set email=?, firstname=?, lastname=?, initials=?, password= (case when password=? then password else md5(?) end) , telephone=?, orcidid=?, source=?, publisher=? where id=?";
79

    
80
	private static final String INSERT_COORDINATORS = "insert into project_coordinator (project, coordinator) values (?, ?)";
81

    
82
	private static final String INSERT_PERSON_ROLE = "insert into person_role (person, role, approved) values (?, ? ,?)";
83

    
84
	private static final String INSERT_AFFILIATION = "insert into affiliation (id, person, organization, startdate, enddate, department) values (?, ?, ?, ?, ?, ?)";
85

    
86
	private static final String INSERT_ACTIVATION_TOKEN = "insert into account_action (\"user\", type, token, date, expires) values (?, ?, ? , ?, ?)";
87

    
88
	private static final String LOGIN = "select 1 from person where email = ? and password = md5(?)";
89

    
90
	private static final String GET_PERSON_TOKEN = "select 1 from person p join account_action ac on ac.user=p.id where p.email=? and ac.token=?";
91

    
92
	private static final String ACTIVATE_USER = "update person set active=true where id = ?";
93

    
94
	private static final String DELETE_ACTIVATION_TOKEN = "delete from account_action where user=? and token=? and type='activation'";
95

    
96
	private static final String UPDATE_PASSWORD = "update person set password=md5(?) where email=?";
97

    
98
	private static final String GET_MODERATORS = "select distinct email, firstname, lastname from person p join person_role pr on pr.person=p.id and pr.role='moderator' and approved=true";
99

    
100
	private static final String GET_ACCOUNTING_OFFICERS = "select distinct email, firstname, lastname from person p join person_role pr on pr.person=p.id and pr.role='accounting' and approved=true";
101

    
102
	/**
103
	 * Returns the person with the given id. Objects of different type are placeholders containing only their id.
104
	 * Objects representing relations are fully initialized, with placeholders for other main entities.
105
	 *
106
	 * @param userId
107
	 * @return
108
	 */
109
	public User getUserById(String userId) {
110
		return (User) createEntityCriteria().add(Restrictions.ilike("id", userId)).list().get(0);
111
	}
112

    
113
	/**
114
	 * Returns the person with the given email. Objects of different type are placeholders containing only their id.
115
	 * Objects representing relations are fully initialized, with placeholders for other main entities.
116
	 *
117
	 * @param email
118
	 * @return
119
	 */
120
	public User getUserByEmail(String email) {
121
		return (User) createEntityCriteria().add(Restrictions.ilike("email", email)).list().get(0);
122
	}
123

    
124
	public void saveToken(final String email, final String token, final int tokenTTL) {
125
		
126
		AccountAction acc_action = new AccountAction();
127
		
128
		acc_action.setUser(getUserByEmail(email));
129
		acc_action.setType("activation");
130
		acc_action.setToken(token);
131
		acc_action.setDate(new Timestamp(System.currentTimeMillis()));
132
		acc_action.setExpires(new Timestamp(System.currentTimeMillis() + 1000L * 60L * 60L * 24L * tokenTTL));
133
		getSession().persist(acc_action);
134
			
135
		
136
//		new JdbcTemplate(dataSource).update(INSERT_ACTIVATION_TOKEN, new PreparedStatementSetter() {
137
//			@Override
138
//			public void setValues(PreparedStatement ps) throws SQLException {
139
//
140
//				ps.setString(1, personId);
141
//				ps.setString(2, "activation");
142
//				ps.setString(3, token);
143
//				ps.setTimestamp(4, new Timestamp(System.currentTimeMillis()));
144
//				ps.setTimestamp(5, new Timestamp(System.currentTimeMillis() + 1000L * 60L * 60L * 24L * tokenTTL));
145
//			}
146
//		});
147
	}
148

    
149
	public boolean verifyLogin(String email, String password) {
150
		User user = (User) createEntityCriteria().add(Restrictions.eq("email", email))
151
				.add(Restrictions.eq("password", DigestUtils.md5Hex(password))).list().get(0);
152
		if(user != null)
153
			return true;
154
		return false;
155
	}
156

    
157
	public boolean verifyToken(final String email, final String token) {
158
//		private static final String GET_PERSON_TOKEN = "select 1 from person p join account_action ac "
159
//				+ "on ac.user=p.id where p.email=? and ac.token=?";	
160
		return new JdbcTemplate(dataSource).query(GET_PERSON_TOKEN, new Object[]{email, token}, new int[]{Types.VARCHAR, Types.VARCHAR}, new RowMapper<Object>() {
161
			@Override
162
			public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
163
				return 1;
164
			}
165
		}).size() > 0;
166
		
167
		
168
		
169
	}
170

    
171
	public void activateUser(final String email) {		
172
		User user = (User) createEntityCriteria().add(Restrictions.eq("email", email)).list().get(0);
173
		user.setActive(true);
174
		getSession().update(user);
175
	}
176

    
177
	public void deleteToken(final String email, final String token) {		
178
		Criteria cr = getSession().createCriteria(AccountAction.class);
179
		AccountAction ac = (AccountAction) cr.add(Restrictions.eq("email", email))
180
				.add(Restrictions.eq("token", token))
181
				.add(Restrictions.eq("type", "activation")).list().get(0);
182
		getSession().delete(ac);
183
	}
184

    
185
	public boolean updatePassword(final String newPassword, final String email) {
186
		User user = (User) createEntityCriteria().add(Restrictions.eq("email", email)).list().get(0);
187
		if(user != null){
188
			user.setPassword(DigestUtils.md5Hex(newPassword));
189
			getSession().update(user);
190
			return true;
191
		}
192
		return false;
193
		
194
	}
195

    
196
	@SuppressWarnings("unchecked")
197
	public List<Role> getRoles() {		
198
		Criteria cr = getSession().createCriteria(Role.class);
199
		return cr.list();
200
	}
201

    
202
	public void saveUser(final User user) {
203
		getSession().persist(user);
204
//		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
205
//
206
//		int updated = jdbcTemplate.update(UPDATE_PERSON, new PreparedStatementSetter() {
207
//			@Override
208
//			public void setValues(PreparedStatement ps) throws SQLException {
209
//				ps.setString(1, user.getEmail());
210
//				ps.setString(2, user.getName());
211
//				ps.setString(3, user.getLastname());
212
//				ps.setString(4, user.getInitials());
213
//				ps.setString(5, user.getPassword());
214
//				ps.setString(6, user.getPassword());
215
//				ps.setString(7, user.getTelephone());
216
//				ps.setString(8, user.getOrcidId());
217
//				ps.setString(9, user.getSource());
218
//				if (user.getPublisher() != null)
219
//					ps.setString(10, user.getPublisher().getId());
220
//				else
221
//					ps.setString(10, null);
222
//				ps.setString(11, user.getId());
223
//			}
224
//		});
225
//
226
//		if (updated == 0) {
227
//			jdbcTemplate.update(INSERT_PERSON, new PreparedStatementSetter() {
228
//				@Override
229
//				public void setValues(PreparedStatement ps) throws SQLException {
230
//					ps.setString(1, person.getEmail());
231
//					ps.setString(2, person.getName());
232
//					ps.setString(3, person.getLastname());
233
//					ps.setString(4, person.getInitials());
234
//					ps.setString(5, person.getPassword());
235
//					ps.setString(6, person.getTelephone());
236
//					ps.setString(7, person.getOrcidId());
237
//					ps.setString(8, person.getSource());
238
//					if (person.getPublisher() != null)
239
//						ps.setString(9, person.getPublisher().getId());
240
//					else
241
//						ps.setString(9, null);
242
//					ps.setString(10, person.getId());
243
//				}
244
//			});
245
//		}
246
	}
247

    
248
	public void deleteAffiliations(final String email) {
249
		Criteria cr = getSession().createCriteria(Affiliation.class);
250
		Affiliation af = (Affiliation) cr.add(Restrictions.eq("email",email)).list().get(0);
251
		getSession().delete(af);
252
	}
253

    
254
	public void deletePersonRoles(final String email) {
255
		Criteria cr = getSession().createCriteria(Affiliation.class);
256
		UserRole ur = (UserRole) cr.add(Restrictions.eq("email",email)).list().get(0);
257
		getSession().delete(ur);
258
	}
259

    
260
	//TODO MOVE TO PROJECT DAO
261
	public void removeProjectCoordinators(final String email) {
262
		Criteria cr = getSession().createCriteria(ProjectCoordinator.class);
263
		ProjectCoordinator pc = (ProjectCoordinator) cr.add(Restrictions.eq("email",email)).list().get(0);
264
		getSession().delete(pc);
265
	}
266

    
267
	public void saveProjectCoordinators(final String email, final List<ProjectCoordinator> projectCoordinators) {
268
		User user = (User) createEntityCriteria().add(Restrictions.eq("email", email)).list().get(0);
269
		user.setProjectCoordinators(projectCoordinators);
270
	}
271

    
272
	public void saveUserRoles(final String email, final List<UserRole> roles) {
273
		User user = getUserByEmail(email);
274
		user.setRole(roles);
275
//		persist(user);
276
	}
277

    
278
	/**
279
	 * @param person       included because the GWT serialization returns a different object than the original (perhaps...)
280
	 * @param affiliations
281
	 */
282
	public void saveAffiliations(final User user, final List<Affiliation> affiliations) {
283
		user.setAffiliations(affiliations);
284
//		new JdbcTemplate(dataSource).batchUpdate(INSERT_AFFILIATION, new BatchPreparedStatementSetter() {
285
//			@Override
286
//			public void setValues(PreparedStatement ps, int i) throws SQLException {
287
//				Affiliation affiliation = affiliations.get(i);
288
//
289
//				ps.setInt(1, UserManagerImpl.generateId(affiliation));
290
//				ps.setString(2, person.getId());
291
//
292
//				if (affiliation.getOrganization() != null)
293
//					ps.setString(3, affiliation.getOrganization().getId());
294
//				else
295
//					ps.setString(3, null);
296
//
297
//				if (affiliation.getStart() != null)
298
//					ps.setTimestamp(4, new Timestamp(affiliation.getStart().getTime()));
299
//				else
300
//					ps.setTimestamp(4, null);
301
//
302
//				if (affiliation.getEnd() != null)
303
//					ps.setTimestamp(5, new Timestamp(affiliation.getEnd().getTime()));
304
//				else
305
//					ps.setTimestamp(5, null);
306
//
307
//				ps.setString(6, affiliation.getDepartment());
308
//			}
309
//
310
//			@Override
311
//			public int getBatchSize() {
312
//				return affiliations != null ? affiliations.size() : 0;
313
//			}
314
//		});
315
	}
316

    
317
	public DataSource getDataSource() {
318
		return dataSource;
319
	}
320

    
321
	public void setDataSource(DataSource dataSource) {
322
		this.dataSource = dataSource;
323
	}
324

    
325
	@SuppressWarnings("unchecked")
326
	public List<User> getModerators() {	
327
		return createEntityCriteria().add(Restrictions.eq("approved", "true")).createAlias("userRole", "ur")
328
		.add(Restrictions.eq("ur.role","moderator")).list();
329
	}
330

    
331
	@SuppressWarnings("unchecked")
332
	public List<User> getAccountingOfficers() {
333
		return createEntityCriteria().add(Restrictions.eq("approved", "true")).createAlias("userRole", "ur")
334
		.add(Restrictions.eq("ur.role","accounting")).list();
335
	}
336

    
337
	public Role getRole(final String roleId) {
338
		Criteria cr = getSession().createCriteria(Role.class);
339
		cr.add(Restrictions.eq("role", roleId));
340
		return (Role) cr.list().get(0);
341
	}
342

    
343
	public void deactivateUser(String email) {
344
		User user = (User) createEntityCriteria().add(Restrictions.eq("email", email)).list().get(0);
345
		user.setActive(false);
346
		getSession().update(user);
347
	}
348

    
349
	public void acceptUserRole(String email, String roleId) {
350
		UserRole ur = (UserRole) createEntityCriteria().add(Restrictions.eq("email", email)).createAlias("userRole", "ur")
351
		.add(Restrictions.eq("ur.id",roleId)).list().get(0);
352
		ur.setApproved(true);
353
		getSession().update(ur);
354
//		
355
//		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
356
//
357
//		if (jdbcTemplate.update("update person_role set approved=true where person=? and role=?", new Object[]{userId, roleId}, new int[]{Types.VARCHAR, Types.VARCHAR}) == 0) {
358
//			jdbcTemplate.update("insert into person_role (person, role, approved) values (?, ?, true)", new Object[]{userId, roleId}, new int[]{Types.VARCHAR, Types.VARCHAR});
359
//		}
360
	}
361

    
362
	public void rejectUserRole(String email, String roleId) {
363
		UserRole ur = (UserRole) createEntityCriteria().add(Restrictions.eq("email", email)).createAlias("userRole", "ur")
364
		.add(Restrictions.eq("ur.id",roleId)).list().get(0);
365
		getSession().delete(ur);
366
		//new JdbcTemplate(dataSource).update("delete from person_role where person=? and role=?", new Object[]{userId, roleId}, new int[]{Types.VARCHAR, Types.VARCHAR});
367
	}
368

    
369
	@SuppressWarnings("unchecked")
370
	public List<User> getUsers() {
371
		return createEntityCriteria().list();
372
	}
373

    
374
	private User readPerson(ResultSet rs) throws SQLException {
375
		return null;
376
//		Person person = new Person();
377
//
378
//		person.setId(rs.getString("id"));
379
//		person.setEmail(rs.getString("email"));
380
//		person.setName(rs.getString("firstname"));
381
//		person.setLastname(rs.getString("lastname"));
382
//		person.setInitials(rs.getString("initials"));
383
//		person.setTelephone(rs.getString("telephone"));
384
//		person.setActive(rs.getBoolean("active"));
385
//		person.setOrcidId(rs.getString("orcidid"));
386
//		person.setPassword(rs.getString("password"));
387
//		person.setSource(rs.getString("source"));
388
//		person.setPublisher(new Publisher(rs.getString("publisher")));
389
//
390
//		person.setCoordinatedProjects(new ArrayList<Project>());
391
//		for (String projectId : (String[]) rs.getArray("projects").getArray()) {
392
//			person.getCoordinatedProjects().add(new Project(projectId));
393
//		}
394
//
395
//		person.setAffiliations(new ArrayList<Affiliation>());
396
//		for (String affString : (String[]) rs.getArray("affiliations").getArray()) {
397
//			if (affString != null) {
398
//				String[] parts = affString.split("\\|\\|");
399
//				String org = parts[0];
400
//				String dep = parts[1];
401
//				Date start = parts[2] == "0" ? null : new Date(Long.parseLong(parts[2]));
402
//				Date end = parts[3] == "0" ? null : new Date(Long.parseLong(parts[3]));
403
//
404
//				Affiliation affiliation = new Affiliation();
405
//
406
//				affiliation.setPerson(person);
407
//				affiliation.setOrganization(new Organization(org));
408
//				affiliation.setDepartment(dep);
409
//				affiliation.setStart(start);
410
//				affiliation.setEnd(end);
411
//
412
//				person.getAffiliations().add(affiliation);
413
//			}
414
//		}
415
//
416
//		person.setRoles(new ArrayList<PersonRole>());
417
//		for (String rString : (String[]) rs.getArray("roles").getArray()) {
418
//			if (rString != null) {
419
//				String[] parts = rString.split("\\|\\|");
420
//				String role = parts[0];
421
//				boolean approved = Boolean.parseBoolean(parts[1]);
422
//
423
//				person.getRoles().add(new PersonRole(person, getRole(role), approved));
424
//			}
425
//		}
426
//
427
//		return person;
428
	}
429
}
(9-9/9)