User and UserTest updated
[staff/due1/sed-hs15-srs-purple.git] / src / main / java / ch / bfh / ti / srs / core / User.java
1 package ch.bfh.ti.srs.core;
2
3 import ch.bfh.ti.srs.extern.Password;
4
5 public class User {
6
7 private final String userName;
8 private String password;
9 private String mail;
10 private String name;
11 private String lastname;
12
13
14 public User(String userName, String password) throws Exception{
15 if(userName == null) throw new IllegalArgumentException("Username must not be null");
16 if(userName.length() < 4) throw new IllegalArgumentException("Username must have at least 4 characters");
17 if(password == null) throw new IllegalArgumentException("Password must not be null");
18
19 this.userName = userName;
20 this.password = Password.getSaltedHash(password);
21 }
22
23 //Getter
24 public String getUserName(){
25 return userName;
26 }
27
28 public String getMail(){
29 return mail;
30 }
31
32 public String getName() {
33 return name;
34 }
35
36 public String getLastname() {
37 return lastname;
38 }
39
40
41 //Setter
42 public boolean setMail(String mail){
43 if(mail != null){
44 if(isValidEmailAddress(mail)){
45 this.mail = mail;
46 return true;
47 }
48 }
49 throw new IllegalArgumentException("Must be valid e-mail adress");
50 }
51
52 public void setName(String name) {
53 this.name = name;
54 }
55
56 public void setLastname(String lastname) {
57 this.lastname = lastname;
58 }
59
60
61 //Password methods
62 public boolean checkPassword(String password) throws Exception{
63 if(password == null) throw new IllegalArgumentException("Password must not be null");
64 return Password.check(password, this.password);
65 }
66
67 public void changePassword(String newPassword) throws Exception{
68 if(newPassword == null) throw new IllegalArgumentException("Password must not be null");
69 if(checkPassword(newPassword)) throw new IllegalArgumentException("Can not be the current password");
70 this.password = Password.getSaltedHash(newPassword);
71 }
72
73
74 //private Helper methods
75 private boolean isValidEmailAddress(String mail){
76 String ePattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$";
77 java.util.regex.Pattern p = java.util.regex.Pattern.compile(ePattern);
78 java.util.regex.Matcher m = p.matcher(mail);
79 return m.matches();
80 }
81 }