This commit is contained in:
byung eun park 2019-08-17 16:30:12 +09:00
parent 76654bca02
commit 562c8b3162
27 changed files with 2102 additions and 1225 deletions

View File

@ -1,98 +1,96 @@
package com.totopia.server.auth.controller; package com.totopia.server.auth.controller;
import org.springframework.beans.factory.annotation.Autowired; import com.totopia.server.auth.payload.JwtSigninResponse;
import org.springframework.http.HttpStatus; import com.totopia.server.auth.payload.SigninRequest;
import org.springframework.http.ResponseEntity; import com.totopia.server.auth.payload.SignupRequest;
import org.springframework.security.authentication.AuthenticationManager; import com.totopia.server.commons.data.payload.ApiResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import com.totopia.server.config.jwt.JwtTokenProvider;
import org.springframework.security.core.Authentication; import com.totopia.server.modules.user.entity.RoleEntity;
import org.springframework.security.core.context.SecurityContextHolder; import com.totopia.server.modules.user.entity.UserEntity;
import org.springframework.security.crypto.password.PasswordEncoder; import com.totopia.server.modules.user.repository.RoleRepository;
import org.springframework.web.bind.annotation.PostMapping; import com.totopia.server.modules.user.repository.UserRepository;
import org.springframework.web.bind.annotation.RequestBody; import com.totopia.server.modules.user.type.RoleName;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController; import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import javax.validation.Valid; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import com.totopia.server.auth.payload.JwtSigninResponse; import org.springframework.security.core.context.SecurityContextHolder;
import com.totopia.server.auth.payload.SigninRequest; import org.springframework.security.crypto.password.PasswordEncoder;
import com.totopia.server.auth.payload.SignupRequest; import org.springframework.web.bind.annotation.PostMapping;
import com.totopia.server.commons.data.payload.ApiResponse; import org.springframework.web.bind.annotation.RequestBody;
import com.totopia.server.config.jwt.JwtTokenProvider; import org.springframework.web.bind.annotation.RequestMapping;
import com.totopia.server.modules.user.entity.RoleEntity; import org.springframework.web.bind.annotation.RestController;
import com.totopia.server.modules.user.entity.UserEntity; import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import com.totopia.server.modules.user.repository.RoleRepository;
import com.totopia.server.modules.user.repository.UserRepository; import javax.validation.Valid;
import com.totopia.server.modules.user.type.RoleName; import java.net.URI;
import java.util.Collections;
import java.net.URI;
import java.util.Collections; /**
* Created by rajeevkumarsingh on 02/08/17.
/** */
* Created by rajeevkumarsingh on 02/08/17. @RestController
*/ @RequestMapping("/auth")
@RestController public class AuthController {
@RequestMapping("/auth")
public class AuthController { @Autowired
AuthenticationManager authenticationManager;
@Autowired
AuthenticationManager authenticationManager; @Autowired
UserRepository userRepository;
@Autowired
UserRepository userRepository; @Autowired
RoleRepository roleRepository;
@Autowired
RoleRepository roleRepository; @Autowired
PasswordEncoder passwordEncoder;
@Autowired
PasswordEncoder passwordEncoder; @Autowired
JwtTokenProvider tokenProvider;
@Autowired
JwtTokenProvider tokenProvider; @PostMapping("/signin")
public ResponseEntity<?> authenticateUser(@Valid @RequestBody SigninRequest signinRequest) {
@PostMapping("/signin")
public ResponseEntity<?> authenticateUser(@Valid @RequestBody SigninRequest signinRequest) { Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(signinRequest.getUsername(), signinRequest.getPassword()));
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(signinRequest.getUsername(), signinRequest.getPassword())); SecurityContextHolder.getContext().setAuthentication(authentication);
SecurityContextHolder.getContext().setAuthentication(authentication); String jwt = tokenProvider.generateToken(authentication);
return ResponseEntity.ok(new JwtSigninResponse(jwt));
String jwt = tokenProvider.generateToken(authentication); }
return ResponseEntity.ok(new JwtSigninResponse(jwt));
} @PostMapping("/signup")
public ResponseEntity<?> registerUser(@Valid @RequestBody SignupRequest signupRequest) throws Exception {
@PostMapping("/signup") if (userRepository.existsByUsername(signupRequest.getUsername())) {
public ResponseEntity<?> registerUser(@Valid @RequestBody SignupRequest signupRequest) throws Exception { return new ResponseEntity<ApiResponse>(
if (userRepository.existsByUsername(signupRequest.getUsername())) { ApiResponse.builder().success(false).message("Username is already taken!").build(), HttpStatus.BAD_REQUEST);
return new ResponseEntity<ApiResponse>( }
ApiResponse.builder().success(false).message("Username is already taken!").build(), HttpStatus.BAD_REQUEST);
} if (userRepository.existsByEmail(signupRequest.getEmail())) {
return new ResponseEntity<ApiResponse>(
if (userRepository.existsByEmail(signupRequest.getEmail())) { ApiResponse.builder().success(false).message("Email Address is already use!").build(),
return new ResponseEntity<ApiResponse>( HttpStatus.BAD_REQUEST);
ApiResponse.builder().success(false).message("Email Address is already use!").build(), }
HttpStatus.BAD_REQUEST);
} // Creating user's account
UserEntity user = UserEntity.builder().username(signupRequest.getUsername()).email(signupRequest.getEmail())
// Creating user's account .password(signupRequest.getPassword()).build();
UserEntity user = UserEntity.builder().username(signupRequest.getUsername()).email(signupRequest.getEmail())
.password(signupRequest.getPassword()).build(); user.setPassword(passwordEncoder.encode(user.getPassword()));
user.setPassword(passwordEncoder.encode(user.getPassword())); RoleEntity userRole = roleRepository.findByName(RoleName.ROLE_USER)
.orElseThrow(() -> new Exception("User Role not set."));
RoleEntity userRole = roleRepository.findByName(RoleName.ROLE_USER)
.orElseThrow(() -> new Exception("User Role not set.")); user.setRoles(Collections.singleton(userRole));
user.setRoles(Collections.singleton(userRole)); UserEntity result = userRepository.save(user);
UserEntity result = userRepository.save(user); URI location = ServletUriComponentsBuilder.fromCurrentContextPath().path("/users/{username}")
.buildAndExpand(result.getUsername()).toUri();
URI location = ServletUriComponentsBuilder.fromCurrentContextPath().path("/users/{username}")
.buildAndExpand(result.getUsername()).toUri(); return ResponseEntity.created(location).body(new ApiResponse(true, "User registered successfully"));
}
return ResponseEntity.created(location).body(new ApiResponse(true, "User registered successfully")); }
}
}

View File

@ -1,13 +1,59 @@
package com.totopia.server.auth.payload; package com.totopia.server.auth.payload;
import lombok.Data; public class JwtSigninResponse {
private String accessToken;
@Data private String tokenType = "Bearer";
public class JwtSigninResponse {
private String accessToken; public JwtSigninResponse(String accessToken) {
private String tokenType = "Bearer"; this.accessToken = accessToken;
}
public JwtSigninResponse(String accessToken) {
this.accessToken = accessToken; public String getAccessToken() {
} return this.accessToken;
} }
public String getTokenType() {
return this.tokenType;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public void setTokenType(String tokenType) {
this.tokenType = tokenType;
}
public boolean equals(final Object o) {
if (o == this) return true;
if (!(o instanceof JwtSigninResponse)) return false;
final JwtSigninResponse other = (JwtSigninResponse) o;
if (!other.canEqual((Object) this)) return false;
final Object this$accessToken = this.getAccessToken();
final Object other$accessToken = other.getAccessToken();
if (this$accessToken == null ? other$accessToken != null : !this$accessToken.equals(other$accessToken))
return false;
final Object this$tokenType = this.getTokenType();
final Object other$tokenType = other.getTokenType();
if (this$tokenType == null ? other$tokenType != null : !this$tokenType.equals(other$tokenType)) return false;
return true;
}
protected boolean canEqual(final Object other) {
return other instanceof JwtSigninResponse;
}
public int hashCode() {
final int PRIME = 59;
int result = 1;
final Object $accessToken = this.getAccessToken();
result = result * PRIME + ($accessToken == null ? 43 : $accessToken.hashCode());
final Object $tokenType = this.getTokenType();
result = result * PRIME + ($tokenType == null ? 43 : $tokenType.hashCode());
return result;
}
public String toString() {
return "JwtSigninResponse(accessToken=" + this.getAccessToken() + ", tokenType=" + this.getTokenType() + ")";
}
}

View File

@ -1,21 +1,97 @@
package com.totopia.server.auth.payload; package com.totopia.server.auth.payload;
import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotBlank;
import lombok.AllArgsConstructor; public class SigninRequest {
import lombok.Builder; @NotBlank
import lombok.Data; private String username;
import lombok.NoArgsConstructor;
@NotBlank
@Data private String password;
@AllArgsConstructor
@NoArgsConstructor public SigninRequest(@NotBlank String username, @NotBlank String password) {
@Builder this.username = username;
public class SigninRequest { this.password = password;
@NotBlank }
private String username;
public SigninRequest() {
@NotBlank }
private String password;
public static SigninRequestBuilder builder() {
} return new SigninRequestBuilder();
}
public @NotBlank String getUsername() {
return this.username;
}
public @NotBlank String getPassword() {
return this.password;
}
public void setUsername(@NotBlank String username) {
this.username = username;
}
public void setPassword(@NotBlank String password) {
this.password = password;
}
public boolean equals(final Object o) {
if (o == this) return true;
if (!(o instanceof SigninRequest)) return false;
final SigninRequest other = (SigninRequest) o;
if (!other.canEqual((Object) this)) return false;
final Object this$username = this.getUsername();
final Object other$username = other.getUsername();
if (this$username == null ? other$username != null : !this$username.equals(other$username)) return false;
final Object this$password = this.getPassword();
final Object other$password = other.getPassword();
if (this$password == null ? other$password != null : !this$password.equals(other$password)) return false;
return true;
}
protected boolean canEqual(final Object other) {
return other instanceof SigninRequest;
}
public int hashCode() {
final int PRIME = 59;
int result = 1;
final Object $username = this.getUsername();
result = result * PRIME + ($username == null ? 43 : $username.hashCode());
final Object $password = this.getPassword();
result = result * PRIME + ($password == null ? 43 : $password.hashCode());
return result;
}
public String toString() {
return "SigninRequest(username=" + this.getUsername() + ", password=" + this.getPassword() + ")";
}
public static class SigninRequestBuilder {
private @NotBlank String username;
private @NotBlank String password;
SigninRequestBuilder() {
}
public SigninRequest.SigninRequestBuilder username(@NotBlank String username) {
this.username = username;
return this;
}
public SigninRequest.SigninRequestBuilder password(@NotBlank String password) {
this.password = password;
return this;
}
public SigninRequest build() {
return new SigninRequest(username, password);
}
public String toString() {
return "SigninRequest.SigninRequestBuilder(username=" + this.username + ", password=" + this.password + ")";
}
}
}

View File

@ -1,28 +1,101 @@
package com.totopia.server.auth.payload; package com.totopia.server.auth.payload;
import javax.validation.constraints.Email; import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size; import javax.validation.constraints.Size;
import lombok.Data; public class SignupRequest {
@NotBlank
@Data @Size(min = 4, max = 40)
private String name;
public class SignupRequest {
@NotBlank @NotBlank
@Size(min = 4, max = 40) @Size(min = 3, max = 15)
private String name; private String username;
@NotBlank @NotBlank
@Size(min = 3, max = 15) @Size(max = 40)
private String username; @Email
private String email;
@NotBlank
@Size(max = 40) @NotBlank
@Email @Size(min = 6, max = 20)
private String email; private String password;
@NotBlank public SignupRequest() {
@Size(min = 6, max = 20) }
private String password;
} public @NotBlank @Size(min = 4, max = 40) String getName() {
return this.name;
}
public @NotBlank @Size(min = 3, max = 15) String getUsername() {
return this.username;
}
public @NotBlank @Size(max = 40) @Email String getEmail() {
return this.email;
}
public @NotBlank @Size(min = 6, max = 20) String getPassword() {
return this.password;
}
public void setName(@NotBlank @Size(min = 4, max = 40) String name) {
this.name = name;
}
public void setUsername(@NotBlank @Size(min = 3, max = 15) String username) {
this.username = username;
}
public void setEmail(@NotBlank @Size(max = 40) @Email String email) {
this.email = email;
}
public void setPassword(@NotBlank @Size(min = 6, max = 20) String password) {
this.password = password;
}
public boolean equals(final Object o) {
if (o == this) return true;
if (!(o instanceof SignupRequest)) return false;
final SignupRequest other = (SignupRequest) o;
if (!other.canEqual((Object) this)) return false;
final Object this$name = this.getName();
final Object other$name = other.getName();
if (this$name == null ? other$name != null : !this$name.equals(other$name)) return false;
final Object this$username = this.getUsername();
final Object other$username = other.getUsername();
if (this$username == null ? other$username != null : !this$username.equals(other$username)) return false;
final Object this$email = this.getEmail();
final Object other$email = other.getEmail();
if (this$email == null ? other$email != null : !this$email.equals(other$email)) return false;
final Object this$password = this.getPassword();
final Object other$password = other.getPassword();
if (this$password == null ? other$password != null : !this$password.equals(other$password)) return false;
return true;
}
protected boolean canEqual(final Object other) {
return other instanceof SignupRequest;
}
public int hashCode() {
final int PRIME = 59;
int result = 1;
final Object $name = this.getName();
result = result * PRIME + ($name == null ? 43 : $name.hashCode());
final Object $username = this.getUsername();
result = result * PRIME + ($username == null ? 43 : $username.hashCode());
final Object $email = this.getEmail();
result = result * PRIME + ($email == null ? 43 : $email.hashCode());
final Object $password = this.getPassword();
result = result * PRIME + ($password == null ? 43 : $password.hashCode());
return result;
}
public String toString() {
return "SignupRequest(name=" + this.getName() + ", username=" + this.getUsername() + ", email=" + this.getEmail() + ", password=" + this.getPassword() + ")";
}
}

View File

@ -1,40 +1,87 @@
package com.totopia.server.commons.data.entity; package com.totopia.server.commons.data.entity;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.springframework.data.annotation.CreatedDate; import lombok.experimental.SuperBuilder;
import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener; import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import lombok.AllArgsConstructor;
import lombok.Data; import javax.persistence.EntityListeners;
import lombok.NoArgsConstructor; import javax.persistence.MappedSuperclass;
import lombok.experimental.SuperBuilder; import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.EntityListeners; import java.io.Serializable;
import javax.persistence.MappedSuperclass; import java.util.Date;
import javax.persistence.Temporal;
import javax.persistence.TemporalType; @MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
import java.io.Serializable; @JsonIgnoreProperties(value = { "createdAt", "updatedAt" }, allowGetters = true)
import java.util.Date; @SuperBuilder
public abstract class DateAuditEntity implements Serializable {
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class) private static final long serialVersionUID = 3495202400889041952L;
@JsonIgnoreProperties(value = { "createdAt", "updatedAt" }, allowGetters = true)
@Data @CreatedDate
@SuperBuilder @Temporal(TemporalType.TIMESTAMP)
@NoArgsConstructor private Date createdAt;
@AllArgsConstructor
public abstract class DateAuditEntity implements Serializable { @LastModifiedDate
@Temporal(TemporalType.TIMESTAMP)
private static final long serialVersionUID = 3495202400889041952L; private Date updatedAt;
@CreatedDate public DateAuditEntity(Date createdAt, Date updatedAt) {
@Temporal(TemporalType.TIMESTAMP) this.createdAt = createdAt;
private Date createdAt; this.updatedAt = updatedAt;
}
@LastModifiedDate
@Temporal(TemporalType.TIMESTAMP) public DateAuditEntity() {
private Date updatedAt; }
} public Date getCreatedAt() {
return this.createdAt;
}
public Date getUpdatedAt() {
return this.updatedAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public boolean equals(final Object o) {
if (o == this) return true;
if (!(o instanceof DateAuditEntity)) return false;
final DateAuditEntity other = (DateAuditEntity) o;
if (!other.canEqual((Object) this)) return false;
final Object this$createdAt = this.getCreatedAt();
final Object other$createdAt = other.getCreatedAt();
if (this$createdAt == null ? other$createdAt != null : !this$createdAt.equals(other$createdAt)) return false;
final Object this$updatedAt = this.getUpdatedAt();
final Object other$updatedAt = other.getUpdatedAt();
if (this$updatedAt == null ? other$updatedAt != null : !this$updatedAt.equals(other$updatedAt)) return false;
return true;
}
protected boolean canEqual(final Object other) {
return other instanceof DateAuditEntity;
}
public int hashCode() {
final int PRIME = 59;
int result = 1;
final Object $createdAt = this.getCreatedAt();
result = result * PRIME + ($createdAt == null ? 43 : $createdAt.hashCode());
final Object $updatedAt = this.getUpdatedAt();
result = result * PRIME + ($updatedAt == null ? 43 : $updatedAt.hashCode());
return result;
}
public String toString() {
return "DateAuditEntity(createdAt=" + this.getCreatedAt() + ", updatedAt=" + this.getUpdatedAt() + ")";
}
}

View File

@ -1,36 +1,82 @@
package com.totopia.server.commons.data.entity; package com.totopia.server.commons.data.entity;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.springframework.data.annotation.CreatedBy; import lombok.experimental.SuperBuilder;
import org.springframework.data.annotation.LastModifiedBy; import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.LastModifiedBy;
import lombok.AllArgsConstructor;
import lombok.Data; import javax.persistence.MappedSuperclass;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor; /**
import lombok.experimental.SuperBuilder; * Created by rajeevkumarsingh on 19/08/17.
*/
import javax.persistence.MappedSuperclass;
@MappedSuperclass
/** @JsonIgnoreProperties(value = { "createdBy", "updatedBy" }, allowGetters = true)
* Created by rajeevkumarsingh on 19/08/17. @SuperBuilder
*/ public abstract class UserDateAuditEntity extends DateAuditEntity {
@MappedSuperclass private static final long serialVersionUID = 6379346917688414915L;
@JsonIgnoreProperties(value = { "createdBy", "updatedBy" }, allowGetters = true)
@SuperBuilder @CreatedBy
@Data private Long createdBy;
@NoArgsConstructor
@AllArgsConstructor @LastModifiedBy
@EqualsAndHashCode(callSuper = false) private Long updatedBy;
public abstract class UserDateAuditEntity extends DateAuditEntity {
public UserDateAuditEntity(Long createdBy, Long updatedBy) {
private static final long serialVersionUID = 6379346917688414915L; this.createdBy = createdBy;
this.updatedBy = updatedBy;
@CreatedBy }
private Long createdBy;
public UserDateAuditEntity() {
@LastModifiedBy }
private Long updatedBy;
public Long getCreatedBy() {
} return this.createdBy;
}
public Long getUpdatedBy() {
return this.updatedBy;
}
public void setCreatedBy(Long createdBy) {
this.createdBy = createdBy;
}
public void setUpdatedBy(Long updatedBy) {
this.updatedBy = updatedBy;
}
public String toString() {
return "UserDateAuditEntity(createdBy=" + this.getCreatedBy() + ", updatedBy=" + this.getUpdatedBy() + ")";
}
public boolean equals(final Object o) {
if (o == this) return true;
if (!(o instanceof UserDateAuditEntity)) return false;
final UserDateAuditEntity other = (UserDateAuditEntity) o;
if (!other.canEqual((Object) this)) return false;
final Object this$createdBy = this.getCreatedBy();
final Object other$createdBy = other.getCreatedBy();
if (this$createdBy == null ? other$createdBy != null : !this$createdBy.equals(other$createdBy)) return false;
final Object this$updatedBy = this.getUpdatedBy();
final Object other$updatedBy = other.getUpdatedBy();
if (this$updatedBy == null ? other$updatedBy != null : !this$updatedBy.equals(other$updatedBy)) return false;
return true;
}
protected boolean canEqual(final Object other) {
return other instanceof UserDateAuditEntity;
}
public int hashCode() {
final int PRIME = 59;
int result = 1;
final Object $createdBy = this.getCreatedBy();
result = result * PRIME + ($createdBy == null ? 43 : $createdBy.hashCode());
final Object $updatedBy = this.getUpdatedBy();
result = result * PRIME + ($updatedBy == null ? 43 : $updatedBy.hashCode());
return result;
}
}

View File

@ -1,15 +1,92 @@
package com.totopia.server.commons.data.payload; package com.totopia.server.commons.data.payload;
import lombok.AllArgsConstructor; public class ApiResponse {
import lombok.Builder; private Boolean success;
import lombok.Data; private String message;
import lombok.NoArgsConstructor;
public ApiResponse(Boolean success, String message) {
@Data this.success = success;
@AllArgsConstructor this.message = message;
@NoArgsConstructor }
@Builder
public class ApiResponse { public ApiResponse() {
private Boolean success; }
private String message;
} public static ApiResponseBuilder builder() {
return new ApiResponseBuilder();
}
public Boolean getSuccess() {
return this.success;
}
public String getMessage() {
return this.message;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public void setMessage(String message) {
this.message = message;
}
public boolean equals(final Object o) {
if (o == this) return true;
if (!(o instanceof ApiResponse)) return false;
final ApiResponse other = (ApiResponse) o;
if (!other.canEqual((Object) this)) return false;
final Object this$success = this.getSuccess();
final Object other$success = other.getSuccess();
if (this$success == null ? other$success != null : !this$success.equals(other$success)) return false;
final Object this$message = this.getMessage();
final Object other$message = other.getMessage();
if (this$message == null ? other$message != null : !this$message.equals(other$message)) return false;
return true;
}
protected boolean canEqual(final Object other) {
return other instanceof ApiResponse;
}
public int hashCode() {
final int PRIME = 59;
int result = 1;
final Object $success = this.getSuccess();
result = result * PRIME + ($success == null ? 43 : $success.hashCode());
final Object $message = this.getMessage();
result = result * PRIME + ($message == null ? 43 : $message.hashCode());
return result;
}
public String toString() {
return "ApiResponse(success=" + this.getSuccess() + ", message=" + this.getMessage() + ")";
}
public static class ApiResponseBuilder {
private Boolean success;
private String message;
ApiResponseBuilder() {
}
public ApiResponse.ApiResponseBuilder success(Boolean success) {
this.success = success;
return this;
}
public ApiResponse.ApiResponseBuilder message(String message) {
this.message = message;
return this;
}
public ApiResponse build() {
return new ApiResponse(success, message);
}
public String toString() {
return "ApiResponse.ApiResponseBuilder(success=" + this.success + ", message=" + this.message + ")";
}
}
}

View File

@ -1,40 +1,39 @@
package com.totopia.server.config; package com.totopia.server.config;
import org.springframework.context.annotation.Bean; import com.totopia.server.config.security.SecurityUserDetails;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Bean;
import org.springframework.data.domain.AuditorAware; import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing; import org.springframework.data.domain.AuditorAware;
import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.security.core.Authentication; import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import java.util.Optional;
import java.util.Optional;
import com.totopia.server.config.security.SecurityUserDetails;
@Configuration
@Configuration @EnableJpaAuditing
@EnableJpaAuditing public class AuditingConfig {
public class AuditingConfig {
@Bean
@Bean public AuditorAware<Long> auditorProvider() {
public AuditorAware<Long> auditorProvider() { return new SpringSecurityAuditAwareImpl();
return new SpringSecurityAuditAwareImpl(); }
} }
}
class SpringSecurityAuditAwareImpl implements AuditorAware<Long> {
class SpringSecurityAuditAwareImpl implements AuditorAware<Long> {
@Override
@Override public Optional<Long> getCurrentAuditor() {
public Optional<Long> getCurrentAuditor() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || !authentication.isAuthenticated()
if (authentication == null || !authentication.isAuthenticated() || authentication instanceof AnonymousAuthenticationToken) {
|| authentication instanceof AnonymousAuthenticationToken) { return Optional.empty();
return Optional.empty(); }
}
SecurityUserDetails securityUserDetails = (SecurityUserDetails) authentication.getPrincipal();
SecurityUserDetails securityUserDetails = (SecurityUserDetails) authentication.getPrincipal();
return Optional.ofNullable(securityUserDetails.getId());
return Optional.ofNullable(securityUserDetails.getId()); }
} }
}

View File

@ -1,66 +1,65 @@
package com.totopia.server.config; package com.totopia.server.config;
import com.totopia.server.config.jwt.JwtAuthenticationEntryPoint; import com.totopia.server.config.jwt.JwtAuthenticationEntryPoint;
import com.totopia.server.config.jwt.JwtAuthenticationFilter; import com.totopia.server.config.jwt.JwtAuthenticationFilter;
import com.totopia.server.config.security.SecurityUserDetailsService; import com.totopia.server.config.security.SecurityUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.BeanIds;
import org.springframework.security.config.BeanIds; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@Configuration @EnableWebSecurity
@EnableWebSecurity @EnableGlobalMethodSecurity(securedEnabled = true, jsr250Enabled = true, prePostEnabled = true)
@EnableGlobalMethodSecurity(securedEnabled = true, jsr250Enabled = true, prePostEnabled = true) public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
@Autowired SecurityUserDetailsService securityUserDetailsService;
SecurityUserDetailsService securityUserDetailsService;
@Autowired
@Autowired private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
@Bean
@Bean public JwtAuthenticationFilter jwtAuthenticationFilter() {
public JwtAuthenticationFilter jwtAuthenticationFilter() { return new JwtAuthenticationFilter();
return new JwtAuthenticationFilter(); }
}
@Override
@Override public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception { authenticationManagerBuilder.userDetailsService(securityUserDetailsService).passwordEncoder(passwordEncoder());
authenticationManagerBuilder.userDetailsService(securityUserDetailsService).passwordEncoder(passwordEncoder()); }
}
@Bean(BeanIds.AUTHENTICATION_MANAGER)
@Bean(BeanIds.AUTHENTICATION_MANAGER) @Override
@Override public AuthenticationManager authenticationManagerBean() throws Exception {
public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean();
return super.authenticationManagerBean(); }
}
@Bean
@Bean public PasswordEncoder passwordEncoder() {
public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder();
return new BCryptPasswordEncoder(); }
}
@Override
@Override protected void configure(HttpSecurity http) throws Exception {
protected void configure(HttpSecurity http) throws Exception { http.cors().and().csrf().disable().exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and()
http.cors().and().csrf().disable().exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests() .antMatchers("/", "/favicon.ico", "/**/*.png", "/**/*.gif", "/**/*.svg", "/**/*.jpg", "/**/*.html", "/**/*.css",
.antMatchers("/", "/favicon.ico", "/**/*.png", "/**/*.gif", "/**/*.svg", "/**/*.jpg", "/**/*.html", "/**/*.css", "/**/*.js")
"/**/*.js") .permitAll().antMatchers("/auth/**").permitAll().antMatchers("/users/**").permitAll().anyRequest()
.permitAll().antMatchers("/auth/**").permitAll().antMatchers("/users/**").permitAll().anyRequest() .authenticated();
.authenticated();
http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
} }
}

View File

@ -1,25 +1,25 @@
package com.totopia.server.config.jwt; package com.totopia.server.config.jwt;
import org.springframework.security.core.AuthenticationException; import org.slf4j.Logger;
import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component; import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.ServletException;
import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponse; import java.io.IOException;
import java.io.IOException;
@Component
@Component public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Slf4j
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint { private static final Logger log = org.slf4j.LoggerFactory.getLogger(JwtAuthenticationEntryPoint.class);
@Override @Override
public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
AuthenticationException e) throws IOException, ServletException { AuthenticationException e) throws IOException, ServletException {
log.error("Responding with unauthorized error. Message - {}", e.getMessage()); log.error("Responding with unauthorized error. Message - {}", e.getMessage());
httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage()); httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
} }
} }

View File

@ -1,66 +1,63 @@
package com.totopia.server.config.jwt; package com.totopia.server.config.jwt;
import org.springframework.beans.factory.annotation.Autowired; import com.totopia.server.config.security.SecurityUserDetailsService;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.slf4j.Logger;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils; import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;
import lombok.extern.slf4j.Slf4j; import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain; import javax.servlet.FilterChain;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import com.totopia.server.config.security.SecurityUserDetailsService;
public class JwtAuthenticationFilter extends OncePerRequestFilter {
import java.io.IOException;
private static final Logger log = org.slf4j.LoggerFactory.getLogger(JwtAuthenticationFilter.class);
@Slf4j @Autowired
public class JwtAuthenticationFilter extends OncePerRequestFilter { private JwtTokenProvider tokenProvider;
@Autowired @Autowired
private JwtTokenProvider tokenProvider; private SecurityUserDetailsService securityUserDetailsService;
@Autowired @Override
private SecurityUserDetailsService securityUserDetailsService; protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
@Override try {
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) String jwt = getJwtFromRequest(request);
throws ServletException, IOException {
try { if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) {
String jwt = getJwtFromRequest(request); String username = tokenProvider.getUsernameFromJWT(jwt);
if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) { /*
String username = tokenProvider.getUsernameFromJWT(jwt); * Note that you could also encode the user's username and roles inside JWT
* claims and create the UserDetails object by parsing those claims from the
/* * JWT. That would avoid the following database hit. It's completely up to you.
* Note that you could also encode the user's username and roles inside JWT */
* claims and create the UserDetails object by parsing those claims from the UserDetails userDetails = securityUserDetailsService.loadUserByUsername(username);
* JWT. That would avoid the following database hit. It's completely up to you. UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null,
*/ userDetails.getAuthorities());
UserDetails userDetails = securityUserDetailsService.loadUserByUsername(username); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null,
userDetails.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authentication);
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); }
} catch (Exception ex) {
SecurityContextHolder.getContext().setAuthentication(authentication); log.error("Could not set user authentication in security context", ex);
} }
} catch (Exception ex) {
log.error("Could not set user authentication in security context", ex); filterChain.doFilter(request, response);
} }
filterChain.doFilter(request, response); private String getJwtFromRequest(HttpServletRequest request) {
} String bearerToken = request.getHeader("Authorization");
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
private String getJwtFromRequest(HttpServletRequest request) { return bearerToken.substring(7, bearerToken.length());
String bearerToken = request.getHeader("Authorization"); }
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) { return null;
return bearerToken.substring(7, bearerToken.length()); }
} }
return null;
}
}

View File

@ -1,73 +1,65 @@
package com.totopia.server.config.jwt; package com.totopia.server.config.jwt;
import org.springframework.beans.factory.annotation.Value; import com.totopia.server.config.security.SecurityUserDetails;
import org.springframework.security.core.Authentication; import io.jsonwebtoken.*;
import org.springframework.security.core.GrantedAuthority; import org.slf4j.Logger;
import org.springframework.stereotype.Component; import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import io.jsonwebtoken.Claims; import org.springframework.security.core.GrantedAuthority;
import io.jsonwebtoken.ExpiredJwtException; import org.springframework.stereotype.Component;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MalformedJwtException; import java.util.Date;
import io.jsonwebtoken.SignatureAlgorithm; import java.util.stream.Collectors;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException; /**
import lombok.extern.slf4j.Slf4j; * Created by rajeevkumarsingh on 19/08/17.
*/
import java.util.Date; @Component
import java.util.stream.Collectors; public class JwtTokenProvider {
private static final String AUTHORITIES_KEY = "authorities";
import com.totopia.server.config.security.SecurityUserDetails; private static final Logger log = org.slf4j.LoggerFactory.getLogger(JwtTokenProvider.class);
/** @Value("${app.jwt.secret}")
* Created by rajeevkumarsingh on 19/08/17. private String jwtSecret;
*/
@Component @Value("${app.jwt.expiration}")
@Slf4j private int jwtExpirationInMs;
public class JwtTokenProvider {
private static final String AUTHORITIES_KEY = "authorities"; public String generateToken(Authentication authentication) {
@Value("${app.jwt.secret}") SecurityUserDetails userPrincipal = (SecurityUserDetails) authentication.getPrincipal();
private String jwtSecret;
Date now = new Date();
@Value("${app.jwt.expiration}") Date expiryDate = new Date(now.getTime() + jwtExpirationInMs);
private int jwtExpirationInMs;
final String authorities = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority)
public String generateToken(Authentication authentication) { .collect(Collectors.joining(","));
SecurityUserDetails userPrincipal = (SecurityUserDetails) authentication.getPrincipal(); return Jwts.builder().setSubject(userPrincipal.getUsername()).claim(AUTHORITIES_KEY, authorities)
.setIssuedAt(new Date()).setExpiration(expiryDate).signWith(SignatureAlgorithm.HS512, jwtSecret).compact();
Date now = new Date(); }
Date expiryDate = new Date(now.getTime() + jwtExpirationInMs);
public String getUsernameFromJWT(String token) {
final String authorities = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority) Claims claims = Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).getBody();
.collect(Collectors.joining(","));
return claims.getSubject();
return Jwts.builder().setSubject(userPrincipal.getUsername()).claim(AUTHORITIES_KEY, authorities) }
.setIssuedAt(new Date()).setExpiration(expiryDate).signWith(SignatureAlgorithm.HS512, jwtSecret).compact();
} public boolean validateToken(String authToken) {
try {
public String getUsernameFromJWT(String token) { Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(authToken);
Claims claims = Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).getBody(); return true;
} catch (SignatureException ex) {
return claims.getSubject(); log.error("Invalid JWT signature");
} } catch (MalformedJwtException ex) {
log.error("Invalid JWT token");
public boolean validateToken(String authToken) { } catch (ExpiredJwtException ex) {
try { log.error("Expired JWT token");
Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(authToken); } catch (UnsupportedJwtException ex) {
return true; log.error("Unsupported JWT token");
} catch (SignatureException ex) { } catch (IllegalArgumentException ex) {
log.error("Invalid JWT signature"); log.error("JWT claims string is empty.");
} catch (MalformedJwtException ex) { }
log.error("Invalid JWT token"); return false;
} catch (ExpiredJwtException ex) { }
log.error("Expired JWT token"); }
} catch (UnsupportedJwtException ex) {
log.error("Unsupported JWT token");
} catch (IllegalArgumentException ex) {
log.error("JWT claims string is empty.");
}
return false;
}
}

View File

@ -1,99 +1,194 @@
package com.totopia.server.config.security; package com.totopia.server.config.security;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import com.totopia.server.modules.user.entity.UserEntity; import com.totopia.server.modules.user.entity.UserEntity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import lombok.AllArgsConstructor; import java.util.List;
import lombok.Builder; import java.util.Objects;
import lombok.Data; import java.util.stream.Collectors;
import lombok.NoArgsConstructor;
public class SecurityUserDetails implements UserDetails {
import java.util.Collection; private static final long serialVersionUID = 1L;
import java.util.List;
import java.util.Objects; private Long id;
import java.util.stream.Collectors;
private String name;
@Data
@AllArgsConstructor private String username;
@NoArgsConstructor
@Builder @JsonIgnore
public class SecurityUserDetails implements UserDetails { private String email;
private static final long serialVersionUID = 1L;
@JsonIgnore
private Long id; private String password;
private String name; private Collection<? extends GrantedAuthority> authorities;
private String username; public SecurityUserDetails(Long id, String name, String username, String email, String password, Collection<? extends GrantedAuthority> authorities) {
this.id = id;
@JsonIgnore this.name = name;
private String email; this.username = username;
this.email = email;
@JsonIgnore this.password = password;
private String password; this.authorities = authorities;
}
private Collection<? extends GrantedAuthority> authorities;
public SecurityUserDetails() {
@Override }
public String getUsername() {
return username; public static SecurityUserDetailsBuilder builder() {
} return new SecurityUserDetailsBuilder();
}
@Override
public String getPassword() { @Override
return password; public String getUsername() {
} return username;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() { @Override
return authorities; public String getPassword() {
} return password;
}
@Override
public boolean isAccountNonExpired() { @Override
return true; public Collection<? extends GrantedAuthority> getAuthorities() {
} return authorities;
}
@Override
public boolean isAccountNonLocked() { @Override
return true; public boolean isAccountNonExpired() {
} return true;
}
@Override
public boolean isCredentialsNonExpired() { @Override
return true; public boolean isAccountNonLocked() {
} return true;
}
@Override
public boolean isEnabled() { @Override
return true; public boolean isCredentialsNonExpired() {
} return true;
}
@Override
public boolean equals(Object o) { @Override
if (this == o) public boolean isEnabled() {
return true; return true;
if (o == null || getClass() != o.getClass()) }
return false;
SecurityUserDetails that = (SecurityUserDetails) o; @Override
return Objects.equals(id, that.id); public boolean equals(Object o) {
} if (this == o)
return true;
@Override if (o == null || getClass() != o.getClass())
public int hashCode() { return false;
return Objects.hash(id); SecurityUserDetails that = (SecurityUserDetails) o;
} return Objects.equals(id, that.id);
}
public static SecurityUserDetails create(UserEntity user) {
List<GrantedAuthority> authorities = user.getRoles().stream() @Override
.map(role -> new SimpleGrantedAuthority(role.getName().name())).collect(Collectors.toList()); public int hashCode() {
return Objects.hash(id);
return SecurityUserDetails.builder().username(user.getUsername()).password(user.getPassword()) }
.authorities(authorities).build();
} public static SecurityUserDetails create(UserEntity user) {
List<GrantedAuthority> authorities = user.getRoles().stream()
} .map(role -> new SimpleGrantedAuthority(role.getName().name())).collect(Collectors.toList());
return SecurityUserDetails.builder().username(user.getUsername()).password(user.getPassword())
.authorities(authorities).build();
}
public Long getId() {
return this.id;
}
public String getName() {
return this.name;
}
public String getEmail() {
return this.email;
}
public void setId(Long id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setUsername(String username) {
this.username = username;
}
public void setEmail(String email) {
this.email = email;
}
public void setPassword(String password) {
this.password = password;
}
public void setAuthorities(Collection<? extends GrantedAuthority> authorities) {
this.authorities = authorities;
}
public String toString() {
return "SecurityUserDetails(id=" + this.getId() + ", name=" + this.getName() + ", username=" + this.getUsername() + ", email=" + this.getEmail() + ", password=" + this.getPassword() + ", authorities=" + this.getAuthorities() + ")";
}
public static class SecurityUserDetailsBuilder {
private Long id;
private String name;
private String username;
private String email;
private String password;
private Collection<? extends GrantedAuthority> authorities;
SecurityUserDetailsBuilder() {
}
public SecurityUserDetails.SecurityUserDetailsBuilder id(Long id) {
this.id = id;
return this;
}
public SecurityUserDetails.SecurityUserDetailsBuilder name(String name) {
this.name = name;
return this;
}
public SecurityUserDetails.SecurityUserDetailsBuilder username(String username) {
this.username = username;
return this;
}
public SecurityUserDetails.SecurityUserDetailsBuilder email(String email) {
this.email = email;
return this;
}
public SecurityUserDetails.SecurityUserDetailsBuilder password(String password) {
this.password = password;
return this;
}
public SecurityUserDetails.SecurityUserDetailsBuilder authorities(Collection<? extends GrantedAuthority> authorities) {
this.authorities = authorities;
return this;
}
public SecurityUserDetails build() {
return new SecurityUserDetails(id, name, username, email, password, authorities);
}
public String toString() {
return "SecurityUserDetails.SecurityUserDetailsBuilder(id=" + this.id + ", name=" + this.name + ", username=" + this.username + ", email=" + this.email + ", password=" + this.password + ", authorities=" + this.authorities + ")";
}
}
}

View File

@ -1,36 +1,35 @@
package com.totopia.server.config.security; package com.totopia.server.config.security;
import com.totopia.server.commons.exception.ResourceNotFoundException; import com.totopia.server.commons.exception.ResourceNotFoundException;
import com.totopia.server.modules.user.entity.UserEntity; import com.totopia.server.modules.user.entity.UserEntity;
import com.totopia.server.modules.user.repository.UserRepository; import com.totopia.server.modules.user.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service;
import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Transactional;
@Service
@Service public class SecurityUserDetailsService implements UserDetailsService {
public class SecurityUserDetailsService implements UserDetailsService { @Autowired
@Autowired UserRepository userRepository;
UserRepository userRepository;
@Override
@Override @Transactional
@Transactional public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// Let people login with either username or email
// Let people login with either username or email UserEntity user = userRepository.findByUsername(username)
UserEntity user = userRepository.findByUsername(username) .orElseThrow(() -> new UsernameNotFoundException("User not found with username : " + username));
.orElseThrow(() -> new UsernameNotFoundException("User not found with username : " + username));
return SecurityUserDetails.create(user);
return SecurityUserDetails.create(user); }
}
@Transactional
@Transactional public UserDetails loadUserById(Long id) {
public UserDetails loadUserById(Long id) { UserEntity user = userRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("User", "id", id));
UserEntity user = userRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("User", "id", id));
return SecurityUserDetails.create(user);
return SecurityUserDetails.create(user); }
} }
}

View File

@ -1,58 +1,57 @@
package com.totopia.server.init; package com.totopia.server.init;
import java.util.HashSet; import com.totopia.server.modules.dashboard.repository.DashboardRepository;
import java.util.stream.Collectors; import com.totopia.server.modules.user.entity.RoleEntity;
import java.util.stream.Stream; import com.totopia.server.modules.user.entity.UserEntity;
import com.totopia.server.modules.user.repository.RoleRepository;
import com.totopia.server.modules.dashboard.repository.DashboardRepository; import com.totopia.server.modules.user.repository.UserRepository;
import com.totopia.server.modules.user.entity.RoleEntity; import com.totopia.server.modules.user.type.RoleName;
import com.totopia.server.modules.user.entity.UserEntity; import org.springframework.beans.factory.annotation.Autowired;
import com.totopia.server.modules.user.repository.RoleRepository; import org.springframework.boot.CommandLineRunner;
import com.totopia.server.modules.user.repository.UserRepository; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import com.totopia.server.modules.user.type.RoleName; import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner; import java.util.HashSet;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import java.util.stream.Collectors;
import org.springframework.security.crypto.password.PasswordEncoder; import java.util.stream.Stream;
import org.springframework.stereotype.Component;
@Component
@Component @ConditionalOnProperty(name = "app.db-init", havingValue = "true")
@ConditionalOnProperty(name = "app.db-init", havingValue = "true") public class DbInitializer implements CommandLineRunner {
public class DbInitializer implements CommandLineRunner {
@Autowired
@Autowired private RoleRepository roleRepository;
private RoleRepository roleRepository;
@Autowired
@Autowired private UserRepository userRepository;
private UserRepository userRepository;
@Autowired
@Autowired PasswordEncoder passwordEncoder;
PasswordEncoder passwordEncoder;
@Autowired
@Autowired DashboardRepository dashboardRepository;
DashboardRepository dashboardRepository;
@Override
@Override public void run(String... strings) throws Exception {
public void run(String... strings) throws Exception { if (0 == roleRepository.count()) {
if (0 == roleRepository.count()) { RoleEntity role = null;
RoleEntity role = null; role = RoleEntity.builder().name(RoleName.ROLE_ADMIN).build();
role = RoleEntity.builder().name(RoleName.ROLE_ADMIN).build(); roleRepository.save(role);
roleRepository.save(role); role = RoleEntity.builder().name(RoleName.ROLE_USER).build();
role = RoleEntity.builder().name(RoleName.ROLE_USER).build(); roleRepository.save(role);
roleRepository.save(role); }
}
if (0 == userRepository.count()) {
if (0 == userRepository.count()) { UserEntity user = null;
UserEntity user = null; user = UserEntity.builder().username("admin").password(passwordEncoder.encode("admin")).nickname("admin")
user = UserEntity.builder().username("admin").password(passwordEncoder.encode("admin")).nickname("admin") .email("admin@example.com").block(false).resetCount(0L).sendEmail(true).roles(Stream.of(RoleEntity.builder().id(Short.valueOf((short) 1)).build())
.email("admin@example.com").roles(Stream.of(RoleEntity.builder().id(Short.valueOf((short) 1)).build()) .collect(Collectors.toCollection(HashSet::new)))
.collect(Collectors.toCollection(HashSet::new))) .build();
.build();
userRepository.save(user);
userRepository.save(user); }
}
System.out.println(" -- Database has been initialized");
System.out.println(" -- Database has been initialized"); }
} }
}

View File

@ -1,111 +1,102 @@
package com.totopia.server.modules.dashboard.controller; package com.totopia.server.modules.dashboard.controller;
import java.util.List; import com.totopia.server.commons.exception.ResourceNotFoundException;
import com.totopia.server.modules.dashboard.entity.DashboardEntity;
import javax.transaction.Transactional; import com.totopia.server.modules.dashboard.repository.DashboardRepository;
import org.springframework.beans.factory.annotation.Autowired;
import com.totopia.server.commons.exception.ResourceNotFoundException; import org.springframework.http.HttpStatus;
import com.totopia.server.modules.dashboard.entity.DashboardEntity; import org.springframework.http.ResponseEntity;
import com.totopia.server.modules.dashboard.repository.DashboardRepository; import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import javax.transaction.Transactional;
import org.springframework.http.ResponseEntity; import java.util.List;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping; @RestController
import org.springframework.web.bind.annotation.GetMapping; public class DashboardController {
import org.springframework.web.bind.annotation.PathVariable; @Autowired
import org.springframework.web.bind.annotation.PostMapping; private DashboardRepository dashboardRepository;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody; @PostMapping(value = "/dashboards")
import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(code = HttpStatus.CREATED)
import org.springframework.web.bind.annotation.RestController; public DashboardEntity save(@RequestBody DashboardEntity dashboard) {
return dashboardRepository.save(dashboard);
@RestController }
public class DashboardController {
@Autowired @PreAuthorize("hasAnyRole('ROLE_USER', 'ROLE_ADMIN', 'ROLE_SUPER_ADMIN')")
private DashboardRepository dashboardRepository; @GetMapping(value = "/dashboards")
public List<DashboardEntity> all() {
@PostMapping(value = "/dashboards") return dashboardRepository.findByOrderBySortOrder();
@ResponseStatus(code = HttpStatus.CREATED) }
public DashboardEntity save(@RequestBody DashboardEntity dashboard) {
return dashboardRepository.save(dashboard); @GetMapping(value = "/dashboards/{id}")
} public DashboardEntity findById(@PathVariable Integer id) {
return dashboardRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("Dashboard", "id", id));
@PreAuthorize("hasAnyRole('ROLE_USER', 'ROLE_ADMIN', 'ROLE_SUPER_ADMIN')") }
@GetMapping(value = "/dashboards")
public List<DashboardEntity> all() { @DeleteMapping(value = "/dashboards/{id}")
return dashboardRepository.findByOrderBySortOrder(); @Transactional
} public ResponseEntity<?> deleteDashboard(@PathVariable Integer id) {
@GetMapping(value = "/dashboards/{id}") return dashboardRepository.findById(id).map(dashboard -> {
public DashboardEntity findById(@PathVariable Integer id) { dashboardRepository.decreaseSortOrder(dashboard.getSortOrder(), (int) dashboardRepository.count());
return dashboardRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("Dashboard", "id", id)); dashboardRepository.delete(dashboard);
}
return ResponseEntity.ok().build();
@DeleteMapping(value = "/dashboards/{id}") }).orElseThrow(() -> new ResourceNotFoundException("Dashboard", "id", id));
@Transactional }
public ResponseEntity<?> deleteDashboard(@PathVariable Integer id) {
@PutMapping(value = "/dashboards/{id}")
return dashboardRepository.findById(id).map(dashboard -> { public ResponseEntity<DashboardEntity> updateDashboard(@PathVariable Integer id,
dashboardRepository.decreaseSortOrder(dashboard.getSortOrder(), (int) dashboardRepository.count()); @RequestBody DashboardEntity newDashboard) {
dashboardRepository.delete(dashboard);
return dashboardRepository.findById(id).map(dashboard -> {
return ResponseEntity.ok().build();
}).orElseThrow(() -> new ResourceNotFoundException("Dashboard", "id", id)); dashboardRepository.save(dashboard);
} return ResponseEntity.ok(dashboard);
}).orElseThrow(() -> new ResourceNotFoundException("Dashboard", "id", id));
@PutMapping(value = "/dashboards/{id}") }
public ResponseEntity<DashboardEntity> updateDashboard(@PathVariable Integer id,
@RequestBody DashboardEntity newDashboard) { @PutMapping(value = "/dashboards/{id}/display/{display}")
public ResponseEntity<DashboardEntity> updateDashboardDisplay(@PathVariable Integer id,
return dashboardRepository.findById(id).map(dashboard -> { @PathVariable Boolean display) {
dashboardRepository.save(dashboard); return dashboardRepository.findById(id).map(dashboard -> {
return ResponseEntity.ok(dashboard); dashboard.setDisplay(display);
}).orElseThrow(() -> new ResourceNotFoundException("Dashboard", "id", id));
} dashboardRepository.save(dashboard);
return ResponseEntity.ok(dashboard);
@PutMapping(value = "/dashboards/{id}/display/{display}") }).orElseThrow(() -> new ResourceNotFoundException("Dashboard", "id", id));
public ResponseEntity<DashboardEntity> updateDashboardDisplay(@PathVariable Integer id,
@PathVariable Boolean display) { }
return dashboardRepository.findById(id).map(dashboard -> { @PutMapping(value = "/dashboards/{id}/sort_order/{targetSortOrder}")
dashboard.setDisplay(display); @Transactional
public ResponseEntity<DashboardEntity> updateDashboardSortOrder(@PathVariable Integer id,
dashboardRepository.save(dashboard); @PathVariable Integer targetSortOrder) {
return ResponseEntity.ok(dashboard);
}).orElseThrow(() -> new ResourceNotFoundException("Dashboard", "id", id)); return dashboardRepository.findById(id).map(dashboard -> {
if (targetSortOrder.equals(dashboard.getSortOrder())) {
} return ResponseEntity.ok(dashboard);
}
@PutMapping(value = "/dashboards/{id}/sort_order/{targetSortOrder}")
@Transactional if (0 > targetSortOrder || dashboardRepository.count() < targetSortOrder) {
public ResponseEntity<DashboardEntity> updateDashboardSortOrder(@PathVariable Integer id, return ResponseEntity.ok(dashboard);
@PathVariable Integer targetSortOrder) { }
return dashboardRepository.findById(id).map(dashboard -> { Integer sourceSortOrder = dashboard.getSortOrder();
if (targetSortOrder.equals(dashboard.getSortOrder())) {
return ResponseEntity.ok(dashboard); if (targetSortOrder > sourceSortOrder) {
} dashboardRepository.decreaseSortOrder(sourceSortOrder, targetSortOrder);
} else {
if (0 > targetSortOrder || dashboardRepository.count() < targetSortOrder) { dashboardRepository.increaseSortOrder(sourceSortOrder, targetSortOrder);
return ResponseEntity.ok(dashboard); }
}
dashboard.setSortOrder(targetSortOrder);
Integer sourceSortOrder = dashboard.getSortOrder(); dashboardRepository.save(dashboard);
if (targetSortOrder > sourceSortOrder) { return ResponseEntity.ok(dashboard);
dashboardRepository.decreaseSortOrder(sourceSortOrder, targetSortOrder); }).orElseThrow(() -> new ResourceNotFoundException("Dashboard", "id", id));
} else {
dashboardRepository.increaseSortOrder(sourceSortOrder, targetSortOrder); }
} }
dashboard.setSortOrder(targetSortOrder);
dashboardRepository.save(dashboard);
return ResponseEntity.ok(dashboard);
}).orElseThrow(() -> new ResourceNotFoundException("Dashboard", "id", id));
}
}

View File

@ -1,54 +1,150 @@
package com.totopia.server.modules.dashboard.entity; package com.totopia.server.modules.dashboard.entity;
import javax.persistence.Basic; import com.totopia.server.commons.data.entity.UserDateAuditEntity;
import javax.persistence.Column; import lombok.experimental.SuperBuilder;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue; import javax.persistence.*;
import javax.persistence.GenerationType;
import javax.persistence.Id; @Entity
import javax.persistence.Table; @Table(name = "dashboard")
@SuperBuilder
import com.totopia.server.commons.data.entity.UserDateAuditEntity; public class DashboardEntity extends UserDateAuditEntity {
private static final long serialVersionUID = 8891163223262220481L;
import lombok.AllArgsConstructor;
import lombok.Builder; @Id
import lombok.Data; @GeneratedValue(strategy = GenerationType.IDENTITY)
import lombok.EqualsAndHashCode; private Integer id;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder; @Basic
@Column(name = "title", nullable = false, length = 150)
@Entity private String title;
@Table(name = "dashboard")
@Data @Basic
@SuperBuilder @Column(name = "description", nullable = true, length = 500)
@NoArgsConstructor private String description;
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false) @Basic
public class DashboardEntity extends UserDateAuditEntity { @Column(name = "url", nullable = false, length = 250)
private static final long serialVersionUID = 8891163223262220481L; private String url;
@Id @Basic
@GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "sort_order", nullable = false)
private Integer id; private Integer sortOrder;
@Basic @Basic
@Column(name = "title", nullable = false, length = 150) @Column(name = "display", nullable = false)
private String title; private Boolean display = true;
@Basic public DashboardEntity(Integer id, String title, String description, String url, Integer sortOrder, Boolean display) {
@Column(name = "description", nullable = true, length = 500) this.id = id;
private String description; this.title = title;
this.description = description;
@Basic this.url = url;
@Column(name = "url", nullable = false, length = 250) this.sortOrder = sortOrder;
private String url; this.display = display;
}
@Basic
@Column(name = "sort_order", nullable = false) public DashboardEntity() {
private Integer sortOrder; }
@Builder.Default public Integer getId() {
@Basic return this.id;
@Column(name = "display", nullable = false) }
private Boolean display = true;
} public String getTitle() {
return this.title;
}
public String getDescription() {
return this.description;
}
public String getUrl() {
return this.url;
}
public Integer getSortOrder() {
return this.sortOrder;
}
public Boolean getDisplay() {
return this.display;
}
public void setId(Integer id) {
this.id = id;
}
public void setTitle(String title) {
this.title = title;
}
public void setDescription(String description) {
this.description = description;
}
public void setUrl(String url) {
this.url = url;
}
public void setSortOrder(Integer sortOrder) {
this.sortOrder = sortOrder;
}
public void setDisplay(Boolean display) {
this.display = display;
}
public String toString() {
return "DashboardEntity(id=" + this.getId() + ", title=" + this.getTitle() + ", description=" + this.getDescription() + ", url=" + this.getUrl() + ", sortOrder=" + this.getSortOrder() + ", display=" + this.getDisplay() + ")";
}
public boolean equals(final Object o) {
if (o == this) return true;
if (!(o instanceof DashboardEntity)) return false;
final DashboardEntity other = (DashboardEntity) o;
if (!other.canEqual((Object) this)) return false;
final Object this$id = this.getId();
final Object other$id = other.getId();
if (this$id == null ? other$id != null : !this$id.equals(other$id)) return false;
final Object this$title = this.getTitle();
final Object other$title = other.getTitle();
if (this$title == null ? other$title != null : !this$title.equals(other$title)) return false;
final Object this$description = this.getDescription();
final Object other$description = other.getDescription();
if (this$description == null ? other$description != null : !this$description.equals(other$description))
return false;
final Object this$url = this.getUrl();
final Object other$url = other.getUrl();
if (this$url == null ? other$url != null : !this$url.equals(other$url)) return false;
final Object this$sortOrder = this.getSortOrder();
final Object other$sortOrder = other.getSortOrder();
if (this$sortOrder == null ? other$sortOrder != null : !this$sortOrder.equals(other$sortOrder)) return false;
final Object this$display = this.getDisplay();
final Object other$display = other.getDisplay();
if (this$display == null ? other$display != null : !this$display.equals(other$display)) return false;
return true;
}
protected boolean canEqual(final Object other) {
return other instanceof DashboardEntity;
}
public int hashCode() {
final int PRIME = 59;
int result = 1;
final Object $id = this.getId();
result = result * PRIME + ($id == null ? 43 : $id.hashCode());
final Object $title = this.getTitle();
result = result * PRIME + ($title == null ? 43 : $title.hashCode());
final Object $description = this.getDescription();
result = result * PRIME + ($description == null ? 43 : $description.hashCode());
final Object $url = this.getUrl();
result = result * PRIME + ($url == null ? 43 : $url.hashCode());
final Object $sortOrder = this.getSortOrder();
result = result * PRIME + ($sortOrder == null ? 43 : $sortOrder.hashCode());
final Object $display = this.getDisplay();
result = result * PRIME + ($display == null ? 43 : $display.hashCode());
return result;
}
}

View File

@ -1,24 +1,23 @@
package com.totopia.server.modules.dashboard.repository; package com.totopia.server.modules.dashboard.repository;
import org.springframework.data.jpa.repository.JpaRepository; import com.totopia.server.modules.dashboard.entity.DashboardEntity;
import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query; import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.repository.query.Param; import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
import java.util.List;
import com.totopia.server.modules.dashboard.entity.DashboardEntity;
public interface DashboardRepository extends JpaRepository<DashboardEntity, Integer> {
public interface DashboardRepository extends JpaRepository<DashboardEntity, Integer> { List<DashboardEntity> findByOrderBySortOrder();
List<DashboardEntity> findByOrderBySortOrder();
@Modifying
@Modifying @Query("update DashboardEntity d set d.sortOrder = d.sortOrder + 1 where d.sortOrder < :sourceSortOrder and d.sortOrder >= :targetSortOrder")
@Query("update DashboardEntity d set d.sortOrder = d.sortOrder + 1 where d.sortOrder < :sourceSortOrder and d.sortOrder >= :targetSortOrder") int increaseSortOrder(@Param("sourceSortOrder") Integer sourceSortOrder,
int increaseSortOrder(@Param("sourceSortOrder") Integer sourceSortOrder, @Param("targetSortOrder") Integer targetSortOrder);
@Param("targetSortOrder") Integer targetSortOrder);
@Modifying
@Modifying @Query("update DashboardEntity d set d.sortOrder = d.sortOrder - 1 where d.sortOrder > :sourceSortOrder and d.sortOrder <= :targetSortOrder")
@Query("update DashboardEntity d set d.sortOrder = d.sortOrder - 1 where d.sortOrder > :sourceSortOrder and d.sortOrder <= :targetSortOrder") int decreaseSortOrder(@Param("sourceSortOrder") Integer sourceSortOrder,
int decreaseSortOrder(@Param("sourceSortOrder") Integer sourceSortOrder, @Param("targetSortOrder") Integer targetSortOrder);
@Param("targetSortOrder") Integer targetSortOrder); }
}

View File

@ -1,62 +1,62 @@
package com.totopia.server.modules.user.controller; package com.totopia.server.modules.user.controller;
import com.totopia.server.commons.exception.ResourceNotFoundException; import com.totopia.server.commons.exception.ResourceNotFoundException;
import com.totopia.server.modules.user.entity.UserEntity; import com.totopia.server.modules.user.entity.UserEntity;
import com.totopia.server.modules.user.repository.UserRepository; import com.totopia.server.modules.user.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus; import org.springframework.data.web.PageableDefault;
import org.springframework.http.ResponseEntity; import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping; @RestController
import org.springframework.web.bind.annotation.PutMapping; public class UserController {
import org.springframework.web.bind.annotation.RequestBody; @Autowired
import org.springframework.web.bind.annotation.ResponseStatus; private UserRepository userRepository;
import org.springframework.web.bind.annotation.RestController;
@PostMapping(value = "/users")
@RestController @ResponseStatus(code = HttpStatus.CREATED)
public class UserController { public UserEntity save(@RequestBody UserEntity user) {
@Autowired return userRepository.save(user);
private UserRepository userRepository; }
@PostMapping(value = "/users") @GetMapping(value = "/users")
@ResponseStatus(code = HttpStatus.CREATED) public @ResponseBody Page<UserEntity> all(@PageableDefault(sort = {"username"}, direction = Sort.Direction.DESC, size = 10)Pageable pageable) {
public UserEntity save(@RequestBody UserEntity user) { Page<UserEntity> users = userRepository.findAll(pageable);
return userRepository.save(user); // Gson gson = new Gson();
} //
// String json = gson.toJson(users);
@GetMapping(value = "/users") return users;
public Page<UserEntity> all(Pageable pageable) { // public Page<UserEntity> all(Pageable pageable) {
return userRepository.findAll(pageable); // return userRepository.findAll(pageable);
} }
@GetMapping(value = "/users/{userId}") @GetMapping(value = "/users/{userId}")
public UserEntity findByUserId(@PathVariable Long userId) { public UserEntity findByUserId(@PathVariable Long userId) {
return userRepository.findById(userId).orElseThrow(() -> new ResourceNotFoundException("User", "userId", userId)); return userRepository.findById(userId).orElseThrow(() -> new ResourceNotFoundException("User", "userId", userId));
} }
@DeleteMapping(value = "/users/{userId}") @DeleteMapping(value = "/users/{userId}")
public ResponseEntity<?> deleteUser(@PathVariable Long userId) { public ResponseEntity<?> deleteUser(@PathVariable Long userId) {
return userRepository.findById(userId).map(user -> { return userRepository.findById(userId).map(user -> {
userRepository.delete(user); userRepository.delete(user);
return ResponseEntity.ok().build(); return ResponseEntity.ok().build();
}).orElseThrow(() -> new ResourceNotFoundException("User", "userId", userId)); }).orElseThrow(() -> new ResourceNotFoundException("User", "userId", userId));
} }
@PutMapping(value = "/users/{userId}") @PutMapping(value = "/users/{userId}")
public ResponseEntity<UserEntity> updateUser(@PathVariable Long userId, @RequestBody UserEntity newUser) { public ResponseEntity<UserEntity> updateUser(@PathVariable Long userId, @RequestBody UserEntity newUser) {
return userRepository.findById(userId).map(user -> { return userRepository.findById(userId).map(user -> {
userRepository.save(user); userRepository.save(user);
return ResponseEntity.ok(user); return ResponseEntity.ok(user);
}).orElseThrow(() -> new ResourceNotFoundException("User", "userId", userId)); }).orElseThrow(() -> new ResourceNotFoundException("User", "userId", userId));
} }
} }

View File

@ -1,26 +1,12 @@
package com.totopia.server.modules.user.entity; package com.totopia.server.modules.user.entity;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import com.totopia.server.commons.data.entity.UserDateAuditEntity; import com.totopia.server.commons.data.entity.UserDateAuditEntity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder; import lombok.experimental.SuperBuilder;
import javax.persistence.*;
@Entity(name = "bank_account") @Entity(name = "bank_account")
@Data
@SuperBuilder @SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class BankAccountEntity extends UserDateAuditEntity { public class BankAccountEntity extends UserDateAuditEntity {
private static final long serialVersionUID = -8628291684559836128L; private static final long serialVersionUID = -8628291684559836128L;
@ -46,4 +32,101 @@ public class BankAccountEntity extends UserDateAuditEntity {
@Column(name = "username", nullable = false) @Column(name = "username", nullable = false)
private String username; private String username;
public BankAccountEntity(Long id, String name, String number, String holder, String username) {
this.id = id;
this.name = name;
this.number = number;
this.holder = holder;
this.username = username;
}
public BankAccountEntity() {
}
public Long getId() {
return this.id;
}
public String getName() {
return this.name;
}
public String getNumber() {
return this.number;
}
public String getHolder() {
return this.holder;
}
public String getUsername() {
return this.username;
}
public void setId(Long id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setNumber(String number) {
this.number = number;
}
public void setHolder(String holder) {
this.holder = holder;
}
public void setUsername(String username) {
this.username = username;
}
public String toString() {
return "BankAccountEntity(id=" + this.getId() + ", name=" + this.getName() + ", number=" + this.getNumber() + ", holder=" + this.getHolder() + ", username=" + this.getUsername() + ")";
}
public boolean equals(final Object o) {
if (o == this) return true;
if (!(o instanceof BankAccountEntity)) return false;
final BankAccountEntity other = (BankAccountEntity) o;
if (!other.canEqual((Object) this)) return false;
final Object this$id = this.getId();
final Object other$id = other.getId();
if (this$id == null ? other$id != null : !this$id.equals(other$id)) return false;
final Object this$name = this.getName();
final Object other$name = other.getName();
if (this$name == null ? other$name != null : !this$name.equals(other$name)) return false;
final Object this$number = this.getNumber();
final Object other$number = other.getNumber();
if (this$number == null ? other$number != null : !this$number.equals(other$number)) return false;
final Object this$holder = this.getHolder();
final Object other$holder = other.getHolder();
if (this$holder == null ? other$holder != null : !this$holder.equals(other$holder)) return false;
final Object this$username = this.getUsername();
final Object other$username = other.getUsername();
if (this$username == null ? other$username != null : !this$username.equals(other$username)) return false;
return true;
}
protected boolean canEqual(final Object other) {
return other instanceof BankAccountEntity;
}
public int hashCode() {
final int PRIME = 59;
int result = 1;
final Object $id = this.getId();
result = result * PRIME + ($id == null ? 43 : $id.hashCode());
final Object $name = this.getName();
result = result * PRIME + ($name == null ? 43 : $name.hashCode());
final Object $number = this.getNumber();
result = result * PRIME + ($number == null ? 43 : $number.hashCode());
final Object $holder = this.getHolder();
result = result * PRIME + ($holder == null ? 43 : $holder.hashCode());
final Object $username = this.getUsername();
result = result * PRIME + ($username == null ? 43 : $username.hashCode());
return result;
}
} }

View File

@ -1,37 +1,106 @@
package com.totopia.server.modules.user.entity; package com.totopia.server.modules.user.entity;
import java.io.Serializable; import com.totopia.server.modules.user.type.RoleName;
import javax.persistence.Column; import javax.persistence.*;
import javax.persistence.Entity; import java.io.Serializable;
import javax.persistence.EnumType;
import javax.persistence.Enumerated; @Entity(name = "roles")
import javax.persistence.GeneratedValue; public class RoleEntity implements Serializable {
import javax.persistence.Id; private static final long serialVersionUID = 5100719044067326295L;
import javax.persistence.SequenceGenerator;
@Id
import com.totopia.server.modules.user.type.RoleName; @GeneratedValue(generator = "role_generator")
@SequenceGenerator(name = "role_generator", sequenceName = "role_sequence", initialValue = 1)
import lombok.AllArgsConstructor; private Short id;
import lombok.Builder;
import lombok.Data; @Enumerated(EnumType.STRING)
import lombok.NoArgsConstructor; @Column(name = "name", length = 60)
private RoleName name;
@Entity(name = "roles")
@Data public RoleEntity(Short id, RoleName name) {
@NoArgsConstructor this.id = id;
@AllArgsConstructor this.name = name;
@Builder }
public class RoleEntity implements Serializable {
private static final long serialVersionUID = 5100719044067326295L; public RoleEntity() {
}
@Id
@GeneratedValue(generator = "role_generator") public static RoleEntityBuilder builder() {
@SequenceGenerator(name = "role_generator", sequenceName = "role_sequence", initialValue = 1) return new RoleEntityBuilder();
private Short id; }
@Enumerated(EnumType.STRING) public Short getId() {
@Column(name = "name", length = 60) return this.id;
private RoleName name; }
} public RoleName getName() {
return this.name;
}
public void setId(Short id) {
this.id = id;
}
public void setName(RoleName name) {
this.name = name;
}
public boolean equals(final Object o) {
if (o == this) return true;
if (!(o instanceof RoleEntity)) return false;
final RoleEntity other = (RoleEntity) o;
if (!other.canEqual((Object) this)) return false;
final Object this$id = this.getId();
final Object other$id = other.getId();
if (this$id == null ? other$id != null : !this$id.equals(other$id)) return false;
final Object this$name = this.getName();
final Object other$name = other.getName();
if (this$name == null ? other$name != null : !this$name.equals(other$name)) return false;
return true;
}
protected boolean canEqual(final Object other) {
return other instanceof RoleEntity;
}
public int hashCode() {
final int PRIME = 59;
int result = 1;
final Object $id = this.getId();
result = result * PRIME + ($id == null ? 43 : $id.hashCode());
final Object $name = this.getName();
result = result * PRIME + ($name == null ? 43 : $name.hashCode());
return result;
}
public String toString() {
return "RoleEntity(id=" + this.getId() + ", name=" + this.getName() + ")";
}
public static class RoleEntityBuilder {
private Short id;
private RoleName name;
RoleEntityBuilder() {
}
public RoleEntity.RoleEntityBuilder id(Short id) {
this.id = id;
return this;
}
public RoleEntity.RoleEntityBuilder name(RoleName name) {
this.name = name;
return this;
}
public RoleEntity build() {
return new RoleEntity(id, name);
}
public String toString() {
return "RoleEntity.RoleEntityBuilder(id=" + this.id + ", name=" + this.name + ")";
}
}
}

View File

@ -1,131 +1,328 @@
package com.totopia.server.modules.user.entity; package com.totopia.server.modules.user.entity;
import java.util.Date; import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.Set; import com.totopia.server.commons.data.entity.DateAuditEntity;
import lombok.experimental.SuperBuilder;
import javax.persistence.Basic;
import javax.persistence.Column; import javax.persistence.*;
import javax.persistence.Entity; import java.util.Date;
import javax.persistence.FetchType; import java.util.Set;
import javax.persistence.Id;
import javax.persistence.JoinColumn; @Entity
import javax.persistence.JoinTable; @Table(name = "users", uniqueConstraints = { @UniqueConstraint(columnNames = { "username" }),
import javax.persistence.ManyToMany; @UniqueConstraint(columnNames = { "email" }) })
import javax.persistence.Table; @SuperBuilder
import javax.persistence.Temporal; public class UserEntity extends DateAuditEntity {
import javax.persistence.TemporalType; private static final long serialVersionUID = 8891163223262220481L;
import javax.persistence.UniqueConstraint;
@Id
import com.fasterxml.jackson.annotation.JsonIgnore; @Column(name = "username", unique = true, nullable = false, length = 150)
import com.totopia.server.commons.data.entity.DateAuditEntity; private String username;
import lombok.AllArgsConstructor; @Basic
import lombok.Data; @Column(name = "password", nullable = false, length = 100)
import lombok.EqualsAndHashCode; @JsonIgnore
import lombok.NoArgsConstructor; private String password;
import lombok.Builder.Default;
import lombok.experimental.SuperBuilder; @Basic
@Column(name = "nickname", nullable = false, length = 150)
@Entity private String nickname;
@Table(name = "users", uniqueConstraints = { @UniqueConstraint(columnNames = { "username" }),
@UniqueConstraint(columnNames = { "email" }) }) @Basic
@Data @Column(name = "email", nullable = false, length = 100)
@SuperBuilder private String email;
@NoArgsConstructor
@AllArgsConstructor @Basic
@EqualsAndHashCode(callSuper = false) @Column(name = "block", nullable = false)
public class UserEntity extends DateAuditEntity { private Boolean block = false;
private static final long serialVersionUID = 8891163223262220481L;
@Basic
@Id @Column(name = "send_email", nullable = false)
@Column(name = "username", unique = true, nullable = false, length = 150) private Boolean sendEmail = true;
private String username;
@Basic
@Basic @Column(name = "activation", nullable = true, length = 100)
@Column(name = "password", nullable = false, length = 100) private String activation;
@JsonIgnore
private String password; @Basic
@Temporal(TemporalType.TIMESTAMP)
@Basic @Column(name = "last_reset_time", nullable = true)
@Column(name = "nickname", nullable = false, length = 150) private Date lastResetTime;
private String nickname;
@Basic
@Basic @Column(name = "reset_count", nullable = false)
@Column(name = "email", nullable = false, length = 100) private Long resetCount = 0L;
private String email;
@Basic
@Basic @Column(name = "otp_key", nullable = true, length = 1000)
@Column(name = "block", nullable = false) private String otpKey;
@Default
private Boolean block = false; @Basic
@Column(name = "otep", nullable = true, length = 1000)
@Basic private String otep;
@Column(name = "send_email", nullable = false)
@Default @Basic
private Boolean sendEmail = true; @Column(name = "require_reset", nullable = true)
private Boolean requireReset = false;
@Basic
@Column(name = "activation", nullable = true, length = 100) @ManyToMany(fetch = FetchType.EAGER)
private String activation; @JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<RoleEntity> roles;
@Basic
@Temporal(TemporalType.TIMESTAMP) public UserEntity(String username, String password, String nickname, String email, Boolean block, Boolean sendEmail, String activation, Date lastResetTime, Long resetCount, String otpKey, String otep, Boolean requireReset, Set<RoleEntity> roles) {
@Column(name = "last_reset_time", nullable = true) this.username = username;
private Date lastResetTime; this.password = password;
this.nickname = nickname;
@Basic this.email = email;
@Column(name = "reset_count", nullable = false) this.block = block;
@Default this.sendEmail = sendEmail;
private Long resetCount = 0L; this.activation = activation;
this.lastResetTime = lastResetTime;
@Basic this.resetCount = resetCount;
@Column(name = "otp_key", nullable = true, length = 1000) this.otpKey = otpKey;
private String otpKey; this.otep = otep;
this.requireReset = requireReset;
@Basic this.roles = roles;
@Column(name = "otep", nullable = true, length = 1000) }
private String otep;
public UserEntity() {
@Basic }
@Column(name = "require_reset", nullable = true)
@Default public String getUsername() {
private Boolean requireReset = false; return this.username;
}
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) public String getPassword() {
private Set<RoleEntity> roles; return this.password;
} }
// 아이디 public String getNickname() {
// 로그인 아이디 return this.nickname;
// 로그인 패스워드 }
// 로그인 패스워드 문자
// 이메일 public String getEmail() {
// 닉네임 return this.email;
// 은행명 }
// 계좌번호
// 예금주 public Boolean getBlock() {
// 추천인 return this.block;
// 추천수 }
// 게시판 제한 여부
// 쿠폰 public Boolean getSendEmail() {
// 충전방식 return this.sendEmail;
// 비고 }
// 종목별 베팅제한
// 상태표기 public String getActivation() {
// 휴대폰번호 return this.activation;
// 추천권한 여부 }
// 가입상태
// 소속 public Date getLastResetTime() {
// 레벨 return this.lastResetTime;
// 보유머니 }
// 포인트
// 회원상태 public Long getResetCount() {
// 룰렛개수 return this.resetCount;
// 계좌순번 }
// 가입날짜
// 최근접속 날짜 public String getOtpKey() {
// 가입 아이피 return this.otpKey;
// 최근 접속 아이피 }
// 베팅 알림
// API 연결 public String getOtep() {
return this.otep;
}
public Boolean getRequireReset() {
return this.requireReset;
}
public Set<RoleEntity> getRoles() {
return this.roles;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public void setEmail(String email) {
this.email = email;
}
public void setBlock(Boolean block) {
this.block = block;
}
public void setSendEmail(Boolean sendEmail) {
this.sendEmail = sendEmail;
}
public void setActivation(String activation) {
this.activation = activation;
}
public void setLastResetTime(Date lastResetTime) {
this.lastResetTime = lastResetTime;
}
public void setResetCount(Long resetCount) {
this.resetCount = resetCount;
}
public void setOtpKey(String otpKey) {
this.otpKey = otpKey;
}
public void setOtep(String otep) {
this.otep = otep;
}
public void setRequireReset(Boolean requireReset) {
this.requireReset = requireReset;
}
public void setRoles(Set<RoleEntity> roles) {
this.roles = roles;
}
public String toString() {
return "UserEntity(username=" + this.getUsername() + ", password=" + this.getPassword() + ", nickname=" + this.getNickname() + ", email=" + this.getEmail() + ", block=" + this.getBlock() + ", sendEmail=" + this.getSendEmail() + ", activation=" + this.getActivation() + ", lastResetTime=" + this.getLastResetTime() + ", resetCount=" + this.getResetCount() + ", otpKey=" + this.getOtpKey() + ", otep=" + this.getOtep() + ", requireReset=" + this.getRequireReset() + ", roles=" + this.getRoles() + ")";
}
public boolean equals(final Object o) {
if (o == this) return true;
if (!(o instanceof UserEntity)) return false;
final UserEntity other = (UserEntity) o;
if (!other.canEqual((Object) this)) return false;
final Object this$username = this.getUsername();
final Object other$username = other.getUsername();
if (this$username == null ? other$username != null : !this$username.equals(other$username)) return false;
final Object this$password = this.getPassword();
final Object other$password = other.getPassword();
if (this$password == null ? other$password != null : !this$password.equals(other$password)) return false;
final Object this$nickname = this.getNickname();
final Object other$nickname = other.getNickname();
if (this$nickname == null ? other$nickname != null : !this$nickname.equals(other$nickname)) return false;
final Object this$email = this.getEmail();
final Object other$email = other.getEmail();
if (this$email == null ? other$email != null : !this$email.equals(other$email)) return false;
final Object this$block = this.getBlock();
final Object other$block = other.getBlock();
if (this$block == null ? other$block != null : !this$block.equals(other$block)) return false;
final Object this$sendEmail = this.getSendEmail();
final Object other$sendEmail = other.getSendEmail();
if (this$sendEmail == null ? other$sendEmail != null : !this$sendEmail.equals(other$sendEmail)) return false;
final Object this$activation = this.getActivation();
final Object other$activation = other.getActivation();
if (this$activation == null ? other$activation != null : !this$activation.equals(other$activation))
return false;
final Object this$lastResetTime = this.getLastResetTime();
final Object other$lastResetTime = other.getLastResetTime();
if (this$lastResetTime == null ? other$lastResetTime != null : !this$lastResetTime.equals(other$lastResetTime))
return false;
final Object this$resetCount = this.getResetCount();
final Object other$resetCount = other.getResetCount();
if (this$resetCount == null ? other$resetCount != null : !this$resetCount.equals(other$resetCount))
return false;
final Object this$otpKey = this.getOtpKey();
final Object other$otpKey = other.getOtpKey();
if (this$otpKey == null ? other$otpKey != null : !this$otpKey.equals(other$otpKey)) return false;
final Object this$otep = this.getOtep();
final Object other$otep = other.getOtep();
if (this$otep == null ? other$otep != null : !this$otep.equals(other$otep)) return false;
final Object this$requireReset = this.getRequireReset();
final Object other$requireReset = other.getRequireReset();
if (this$requireReset == null ? other$requireReset != null : !this$requireReset.equals(other$requireReset))
return false;
final Object this$roles = this.getRoles();
final Object other$roles = other.getRoles();
if (this$roles == null ? other$roles != null : !this$roles.equals(other$roles)) return false;
return true;
}
protected boolean canEqual(final Object other) {
return other instanceof UserEntity;
}
public int hashCode() {
final int PRIME = 59;
int result = 1;
final Object $username = this.getUsername();
result = result * PRIME + ($username == null ? 43 : $username.hashCode());
final Object $password = this.getPassword();
result = result * PRIME + ($password == null ? 43 : $password.hashCode());
final Object $nickname = this.getNickname();
result = result * PRIME + ($nickname == null ? 43 : $nickname.hashCode());
final Object $email = this.getEmail();
result = result * PRIME + ($email == null ? 43 : $email.hashCode());
final Object $block = this.getBlock();
result = result * PRIME + ($block == null ? 43 : $block.hashCode());
final Object $sendEmail = this.getSendEmail();
result = result * PRIME + ($sendEmail == null ? 43 : $sendEmail.hashCode());
final Object $activation = this.getActivation();
result = result * PRIME + ($activation == null ? 43 : $activation.hashCode());
final Object $lastResetTime = this.getLastResetTime();
result = result * PRIME + ($lastResetTime == null ? 43 : $lastResetTime.hashCode());
final Object $resetCount = this.getResetCount();
result = result * PRIME + ($resetCount == null ? 43 : $resetCount.hashCode());
final Object $otpKey = this.getOtpKey();
result = result * PRIME + ($otpKey == null ? 43 : $otpKey.hashCode());
final Object $otep = this.getOtep();
result = result * PRIME + ($otep == null ? 43 : $otep.hashCode());
final Object $requireReset = this.getRequireReset();
result = result * PRIME + ($requireReset == null ? 43 : $requireReset.hashCode());
final Object $roles = this.getRoles();
result = result * PRIME + ($roles == null ? 43 : $roles.hashCode());
return result;
}
// @Builder
// public UserEntity(String username, String password, String nickname, String email, Date createAt, Date updateAt) {
// super(createAt, updateAt);
// this.username = username;
// this.password = password;
// this.nickname = nickname;
// this.email = email;
// }
}
// 아이디
// 로그인 아이디
// 로그인 패스워드
// 로그인 패스워드 문자
// 이메일
// 닉네임
// 은행명
// 계좌번호
// 예금주
// 추천인
// 추천수
// 게시판 제한 여부
// 쿠폰
// 충전방식
// 비고
// 종목별 베팅제한
// 상태표기
// 휴대폰번호
// 추천권한 여부
// 가입상태
// 소속
// 레벨
// 보유머니
// 포인트
// 회원상태
// 룰렛개수
// 계좌순번
// 가입날짜
// 최근접속 날짜
// 가입 아이피
// 최근 접속 아이피
// 베팅 알림
// API 연결

View File

@ -1,9 +1,8 @@
package com.totopia.server.modules.user.repository; package com.totopia.server.modules.user.repository;
import org.springframework.data.jpa.repository.JpaRepository; import com.totopia.server.modules.user.entity.BankAccountEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import com.totopia.server.modules.user.entity.BankAccountEntity;
public interface BankAccountRepository extends JpaRepository<BankAccountEntity, Long> {
public interface BankAccountRepository extends JpaRepository<BankAccountEntity, Long> {
}
}

View File

@ -1,12 +1,11 @@
package com.totopia.server.modules.user.repository; package com.totopia.server.modules.user.repository;
import org.springframework.data.jpa.repository.JpaRepository; import com.totopia.server.modules.user.entity.RoleEntity;
import com.totopia.server.modules.user.type.RoleName;
import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository;
import com.totopia.server.modules.user.entity.RoleEntity; import java.util.Optional;
import com.totopia.server.modules.user.type.RoleName;
public interface RoleRepository extends JpaRepository<RoleEntity, Long> {
public interface RoleRepository extends JpaRepository<RoleEntity, Long> { Optional<RoleEntity> findByName(RoleName name);
Optional<RoleEntity> findByName(RoleName name); }
}

View File

@ -1,54 +1,53 @@
package com.totopia.server.modules.user.repository; package com.totopia.server.modules.user.repository;
import org.springframework.data.domain.Page; import com.totopia.server.modules.user.entity.UserEntity;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Page;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Date;
import java.util.Optional; import java.util.Date;
import java.util.Optional;
import com.totopia.server.modules.user.entity.UserEntity;
public interface UserRepository extends JpaRepository<UserEntity, Long> {
public interface UserRepository extends JpaRepository<UserEntity, Long> {
Optional<UserEntity> findByUsername(String username);
Optional<UserEntity> findByUsername(String username);
Boolean existsByEmail(String email);
Boolean existsByEmail(String email);
Optional<UserEntity> findByEmail(String email);
Optional<UserEntity> findByEmail(String email);
Boolean existsByUsername(String username);
Boolean existsByUsername(String username);
Page<UserEntity> findAllByNickname(String nickName, Pageable pageable) throws Exception;
Page<UserEntity> findAllByNickname(String nickName, Pageable pageable) throws Exception;
// 접속 제한 상태 유저 리스트
// 접속 제한 상태 유저 리스트 Page<UserEntity> findAllByBlockTrue(Pageable pageable) throws Exception;
Page<UserEntity> findAllByBlockTrue(Pageable pageable) throws Exception;
// 접속 제한 상태가 아닌 유저 리스트
// 접속 제한 상태가 아닌 유저 리스트 Page<UserEntity> findAllByBlockFalse(Pageable pageable) throws Exception;
Page<UserEntity> findAllByBlockFalse(Pageable pageable) throws Exception;
// // 어드민 유저 리스
// // 어드민 유저 리스 // Page<UserEntity> findAllByIsAdminTrue(Pageable pageable) throws Exception;
// Page<UserEntity> findAllByIsAdminTrue(Pageable pageable) throws Exception;
// 패스워드 리셋이 트루인 유저 리스
// 패스워드 리셋이 트루인 유저 리스 Page<UserEntity> findAllByRequireResetTrue(Pageable pageable) throws Exception;
Page<UserEntity> findAllByRequireResetTrue(Pageable pageable) throws Exception;
// // 어드민이 펄스이며, 활동중인 현재 회원 리스트
// // 어드민이 펄스이며, 활동중인 현재 회원 리스트 // Page<UserEntity> findAllByIsAdminFalseAndActivationEquals(String activation,
// Page<UserEntity> findAllByIsAdminFalseAndActivationEquals(String activation, // Pageable pageable) throws Exception;
// Pageable pageable) throws Exception;
// 날짜 검색
// 날짜 검색 Page<UserEntity> findAllByCreatedAtBetween(Date starDate, Date endDate, Pageable pageable) throws Exception;
Page<UserEntity> findAllByCreatedAtBetween(Date starDate, Date endDate, Pageable pageable) throws Exception;
Page<UserEntity> findAllByUpdatedAtBetween(Date starDate, Date endDate, Pageable pageable) throws Exception;
Page<UserEntity> findAllByUpdatedAtBetween(Date starDate, Date endDate, Pageable pageable) throws Exception;
Page<UserEntity> findAllByLastResetTimeBetween(Date starDate, Date endDate, Pageable pageable) throws Exception;
Page<UserEntity> findAllByLastResetTimeBetween(Date starDate, Date endDate, Pageable pageable) throws Exception;
// 현재 날짜 이후 가입된 회원의 리턴
// 현재 날짜 이후 가입된 회원의 리턴 Long countByCreatedAtGreaterThanEqual(Date date) throws Exception;
Long countByCreatedAtGreaterThanEqual(Date date) throws Exception;
// 유저 그룹별 회원 리스트
// 유저 그룹별 회원 리스트
// 유저 소속별 회원 리스트
// 유저 소속별 회원 리스트
}
}

View File

@ -1,5 +1,7 @@
# Spring Boot configuration # Spring Boot configuration
spring: spring:
# autoconfigure:
# exclude: org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
application: application:
name: totopia-server name: totopia-server
datasource: datasource:

View File

@ -14,7 +14,7 @@ import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import static org.junit.Assert.*; import static org.junit.Assert.assertEquals;
@Ignore @Ignore
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)