Skip to content

Commit

Permalink
Merge remote-tracking branch 'remotes/origin/Dev_InitAuthorization'
Browse files Browse the repository at this point in the history
  • Loading branch information
tuansu2021998 committed Mar 31, 2020
2 parents bc5dcd3 + d45e697 commit a685829
Show file tree
Hide file tree
Showing 15 changed files with 244 additions and 214 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,12 @@
import capstone.lip.landinformationportal.repository.RealEstateRepository;
import capstone.lip.landinformationportal.specification.RealEstateSpecifications;
import capstone.lip.landinformationportal.specification.SearchCriteria;
import capstone.lip.landinformationportal.utils.EmailSender;

@EnableJpaAuditing
@SpringBootApplication
@ComponentScan
public class Application {
public class Application{
public static void main(String[] args) {
SpringApplication.run(Application.class, args);

Expand All @@ -37,9 +38,8 @@ public static void main(String[] args) {
// public void run(String... args) {
//
// System.out.print("hello");
// MaxMinAvg max = repo.getMaxMinAvg("hà đông");
// List<GroupByDateMaxMinCreate> list = repo.getGroupTimeAndPrice("hà đông");
// int i = 1;
// EmailSender.sendMailChangePassword("[email protected]", "tuan1234");
// int i= 1;
// i++;
// i--;
// }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
import javax.inject.Named;
import javax.servlet.http.HttpSession;

import org.primefaces.PrimeFaces;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
Expand All @@ -22,7 +24,9 @@
import capstone.lip.landinformationportal.common.UserRoleConstant;
import capstone.lip.landinformationportal.entity.User;
import capstone.lip.landinformationportal.service.Interface.IUserService;
import capstone.lip.landinformationportal.utils.EmailSender;
import capstone.lip.landinformationportal.utils.EncryptedPassword;
import capstone.lip.landinformationportal.utils.PasswordGenerator;

@Named
@ViewScoped
Expand All @@ -37,6 +41,9 @@ public class AuthenticationBean implements Serializable{
@Autowired
private IUserService userService;

@Value("${password.reset.length}")
private int passwordLength;

@PostConstruct
public void init() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Expand Down Expand Up @@ -73,6 +80,14 @@ public void signup() {

public void signin() {
User user = userService.findByUsername(usernameSignin);
if (user == null) {
PrimeFaces.current().executeScript("setMessageError('Tài khoản không tồn tại')");
return;
}
if (!EncryptedPassword.checkPassword(passwordSignin, user.getPassword())) {
PrimeFaces.current().executeScript("setMessageError('Mật khẩu không chính xác')");
return;
}
if (user!= null && EncryptedPassword.checkPassword(passwordSignin, user.getPassword())) {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(usernameSignin, passwordSignin);
SecurityContextHolder.getContext().setAuthentication(token);
Expand Down Expand Up @@ -122,6 +137,26 @@ public void redirectHomepage() {
} catch (IOException e) {
e.printStackTrace();
}
}
public void redirectListOwnReo() {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
try {
ec.redirect(ec.getRequestContextPath() + "/user/listownrealestate.xhtml");
} catch (IOException e) {
e.printStackTrace();
}
}
public void forgetPass() {
PrimeFaces.current().executeScript("setMessageForgetpass()");
String newPass = PasswordGenerator.generate(passwordLength);
User user = userService.findByUsername(usernameSignin);
EmailSender.sendMailChangePassword(user.getEmail(), newPass);

newPass = EncryptedPassword.encrytePassword(newPass);
user.setPassword(newPass);
userService.save(user);


}
public String getUsernameSignup() {
return usernameSignup;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
import org.primefaces.PrimeFaces;
import org.primefaces.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
Expand Down Expand Up @@ -159,7 +161,6 @@ public class ContributeNewRealEstateBean implements Serializable, StatusRealEsta
private String realEstateStatus;
private String realEstateLink;
private String realEstateType;
private String userId;
//submit data
private BigDecimal realEstatePriceSubmit;
private String realEstateNameSubmit;
Expand All @@ -179,7 +180,6 @@ public void init() {
listHousesFeature = housesFeatureService.findAll();
realEstateStatus = String.valueOf(NOT_VERIFIED);
realEstateType = CONTRIBUTOR;
userId = "1";
realEstatePrice = BigDecimal.ZERO;
newHouseMoney = BigDecimal.ZERO;
newLandMoney = BigDecimal.ZERO;
Expand All @@ -191,19 +191,14 @@ public void saveDataUploadToDB() {
nextLocatePoint();
//save to DB RE

User tempUser = new User();
List<User> userListAll = userService.findAll();
for (int i = 0; i < userListAll.size(); i++) {
if (userListAll.get(i).getUserId().toString().equals(userId)) {
tempUser.setUserId(userListAll.get(i).getUserId());
tempUser.setUsername(userListAll.get(i).getUsername());
tempUser.setPassword(userListAll.get(i).getPassword());
tempUser.setFullName(userListAll.get(i).getFullName());
tempUser.setRole(userListAll.get(i).getRole());
tempUser.setEmail(userListAll.get(i).getEmail());
tempUser.setPhone(userListAll.get(i).getPhone());
}
}
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String username="";
if (auth!= null) {
username = (String)auth.getPrincipal();
}

User tempUser = userService.findByUsername(username);

RealEstate newUploadRealEstate = new RealEstate().setRealEstateName(realEstateName)
.setRealEstateLat(realEstateLat).setRealEstateLng(realEstateLng)
.setRealEstateAddress(realEstateAddress);
Expand Down Expand Up @@ -851,14 +846,6 @@ public void setRealEstateType(String realEstateType) {
this.realEstateType = realEstateType;
}

public String getUserId() {
return userId;
}

public void setUserId(String userId) {
this.userId = userId;
}

public String getRealEstateName() {
return realEstateName;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import capstone.lip.landinformationportal.entity.HousesFeature;
import capstone.lip.landinformationportal.entity.LandsFeature;
import capstone.lip.landinformationportal.entity.RealEstate;
import capstone.lip.landinformationportal.entity.User;
import capstone.lip.landinformationportal.service.Interface.IRealEstateService;
import capstone.lip.landinformationportal.service.Interface.IUserService;
import com.google.gson.Gson;
Expand All @@ -19,6 +20,8 @@
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
*
Expand All @@ -36,13 +39,23 @@ public class ListOwnRealEstateBean implements Serializable {
private List<RealEstate> listUserRealEstate;
private RealEstate realEstateClicked;
private String jsonMultipleCoordinate;

private User currentUser;

@PostConstruct
public void init() {

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String username="";
if (auth!= null) {
username = (String)auth.getPrincipal();
}

currentUser = userService.findByUsername(username);

//Ham init nay phai truyen vao userId
listUserRealEstate = new ArrayList<>();
//truyen userId vao ham ben duoi, �ang hard code
listUserRealEstate = userService.getListRealEstate(1L);
listUserRealEstate = userService.getListRealEstate(currentUser.getUserId());
transferListCoordinate();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

import capstone.lip.landinformationportal.entity.User;
import capstone.lip.landinformationportal.service.Interface.IUserService;
import capstone.lip.landinformationportal.utils.EncryptedPassword;

import java.io.Serializable;
import java.text.ParseException;
import java.util.Date;
Expand All @@ -16,6 +18,9 @@
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.primefaces.component.password.Password;
Expand Down Expand Up @@ -52,7 +57,15 @@ public void init() {
// Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
// long userId = Long.parseLong(params.get("userId"));
// userSelected = userService.findById(userId); // get User from UserID
userSelected = userService.findById(userIdTemp);

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String usernameInToken="";
if (auth!= null) {
usernameInToken = (String)auth.getPrincipal();
}

userSelected = userService.findByUsername(usernameInToken);

username = userSelected.getUsername();
fullname = userSelected.getFullName();
email = userSelected.getEmail();
Expand Down Expand Up @@ -81,8 +94,8 @@ public void updateMyProfile(){
}

public void changePassword(){
if(oldPass.equals(userSelected.getPassword()) && newPass.equals(confirmNewPass)){
userSelected.setPassword(confirmNewPass);
if(EncryptedPassword.checkPassword(oldPass, userSelected.getPassword()) && newPass.equals(confirmNewPass)){
userSelected.setPassword(EncryptedPassword.encrytePassword(newPass));
userSelected = userService.save(userSelected);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@
import javax.inject.Named;
import org.primefaces.PrimeFaces;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
*
Expand Down Expand Up @@ -152,7 +154,6 @@ public class UpdateContributeRealEstateBean implements Serializable {
private String realEstateStatus;
private String realEstateLink;
private String realEstateSource;
private String userId;
//submit data
private BigDecimal realEstatePriceSubmit;
private String realEstateNameSubmit;
Expand Down Expand Up @@ -202,7 +203,6 @@ public void init() {
}

realEstateStatus = "0"; // Set tạm
userId = "1";

segmentStreetIdSelected = realEstateClicked.getListRealEstateAdjacentSegment().get(0).getSegmentOfStreet().getSegmentId().toString();
districtIdSelected = realEstateClicked.getListRealEstateAdjacentSegment().get(0).getSegmentOfStreet().getDistrict().getDistrictId().toString();
Expand All @@ -220,20 +220,15 @@ public void updateDataUploadToDB() {
realEstateLng = Double.parseDouble(lngSingleCoordinate);
}
//Update to DB RE

User tempUser = new User();
List<User> userListAll = userService.findAll();
for (int i = 0; i < userListAll.size(); i++) {
if (userListAll.get(i).getUserId().toString().equals(userId)) {
tempUser.setUserId(userListAll.get(i).getUserId());
tempUser.setUsername(userListAll.get(i).getUsername());
tempUser.setPassword(userListAll.get(i).getPassword());
tempUser.setFullName(userListAll.get(i).getFullName());
tempUser.setRole(userListAll.get(i).getRole());
tempUser.setEmail(userListAll.get(i).getEmail());
tempUser.setPhone(userListAll.get(i).getPhone());
}
}

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String username="";
if (auth!= null) {
username = (String)auth.getPrincipal();
}

User tempUser = userService.findByUsername(username);

realEstateClicked.setRealEstateLat(realEstateLat).setRealEstateLng(realEstateLng)
.setRealEstateAddress(realEstateAddress);
realEstateClicked.setRealEstatePrice(realEstatePrice);
Expand Down Expand Up @@ -944,14 +939,6 @@ public void setRealEstateType(String realEstateSource) {
this.realEstateSource = realEstateSource;
}

public String getUserId() {
return userId;
}

public void setUserId(String userId) {
this.userId = userId;
}

public BigDecimal getRealEstatePriceSubmit() {
return realEstatePriceSubmit;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.rememberme.InMemoryTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import capstone.lip.landinformationportal.common.UserRoleConstant;

import org.springframework.context.annotation.Bean;

@EnableWebSecurity
Expand All @@ -15,58 +18,13 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
public SecurityConfig() {
super(false);
}

// @Override
// protected AuthenticationManager authenticationManager() throws Exception {
// return new ProviderManager(Arrays.asList((AuthenticationProvider) new AuthProvider()));
// }

@Bean
public BCryptPasswordEncoder passwordEncoder() {
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
return bCryptPasswordEncoder;
}

@Override
protected void configure(HttpSecurity http) throws Exception {
// require all requests to be authenticated except for the resources
http.authorizeRequests().antMatchers("/javax.faces.resource/**", "/helloworld.xhtml").permitAll()
.antMatchers("/helloadmin.xhtml").authenticated().anyRequest().permitAll();
// login
http.formLogin().loginPage("/login.xhtml").permitAll().failureUrl("/login.xhtml?error=true");
// logout
http.logout().logoutSuccessUrl("/login.xhtml");

http.authorizeRequests().and().formLogin()
.loginProcessingUrl("/j_spring_security_check") // Submit URL
.loginPage("/login")//
.defaultSuccessUrl("/userAccountInfo")//
.failureUrl("/login?error=true")//
.usernameParameter("username")//
.passwordParameter("password")
// Cấu hình cho Logout Page.
.and().logout().logoutUrl("/logout").logoutSuccessUrl("/logoutSuccessful");

// not needed as JSF 2.2 is implicitly protected against CSRF
http.authorizeRequests()
.antMatchers("/admin/*").hasAuthority(UserRoleConstant.ROLE_ADMIN)
.antMatchers("/user/*").hasAuthority(UserRoleConstant.ROLE_USER)
.anyRequest().permitAll();
http.csrf().disable();

// Cấu hình Remember Me.
http.authorizeRequests().and() //
.rememberMe().tokenRepository(this.persistentTokenRepository()) //
.tokenValiditySeconds(1 * 24 * 60 * 60); // 24h
}
@Bean
public PersistentTokenRepository persistentTokenRepository() {
InMemoryTokenRepositoryImpl memory = new InMemoryTokenRepositoryImpl();
return memory;
}

// @Autowired
// public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
//// auth.inMemoryAuthentication().withUser("user")
//// .password("{noop}1234").roles("USER").and()
//// .withUser("admin").password("{noop}5678").roles("ADMIN");
//// auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
// auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
// }
}
Loading

0 comments on commit a685829

Please sign in to comment.